89 Commits

Author SHA1 Message Date
root
82ca9afb67 fix(metering): generate UUID in Node for raw INSERTs into usage_records
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Prisma's `@default(uuid())` runs in the client layer and is bypassed by
`$queryRawUnsafe` / `$executeRawUnsafe`. The DB column has no server-side
default and pgcrypto/uuid-ossp aren't enabled, so every aggregate /
increment call failed with 23502 NOT NULL on `id`.

Pass a `randomUUID()` from `node:crypto` as the first parameter in all
four raw INSERTs (aggregateUsage, recordApiRequest, recordWebhookSent,
recordPushSent).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 09:25:10 +00:00
root
54e348c49f feat(web-club-admin): in-product help for bots + webhook edit UX
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Help system (new):
- HelpProvider in dashboard layout drives a right-side Sheet with topic
  content; HelpIcon ("?") buttons open it inline without leaving context.
- 8 topics written for managers in plain language: overview, create,
  dashboard, scenarios (with per-step-type sections), subscribers,
  broadcasts, webhooks, analytics.
- Full-page mirrors at /help/bots and /help/bots/[topic] so links can be
  shared with colleagues.
- ~45 HelpIcon callouts placed at every functional block in the bot UI,
  including each step header and sub-section in the scenario step editor.
- Real PNG screenshots embedded from public/help/bots/.

UI improvements bundled in:
- Webhooks: edit dialog reuses the create form, power toggle, edit/test/
  delete actions on each row.
- Subscribers: minor layout tweaks alongside the help icons.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 08:52:23 +00:00
root
a1bfe0d25b docs: deferred backlog + Bitrix24 bot bridge integration spec
- backlog.md: technical items intentionally postponed (log retention, async
  callback endpoint, external API for broadcasts).
- tz-bitrix-bot-bridge.md: spec for the Bitrix24 PHP module that talks to
  MyFitCRM bots via HTTPS.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 08:51:33 +00:00
root
7c0cadc378 feat(telegram-bot): webhook delivery log + HTML sanitization + adapter polish
- New tg_bot_webhook_deliveries table tracks every outbound webhook attempt
  (status code, response body/headers, error, attempts) for audit and retries.
- Reusable Telegram-safe HTML sanitizer extracts only Telegram-allowed tags.
- MAX and Telegram adapters: unify message payload, broader event handling.
- Scenario engine and subscriber service: refinements for referral counting
  and onboarding flow consistency.
- CSV export: type-safe stringification of subscriber cells.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 08:51:12 +00:00
root
5c700bed18 feat(network-admin): separate workspace for CLUBS_ADMIN with club management
- New (network-admin) layout in web-club-admin for users with access to
  multiple clubs: admin/clubs (list+CRUD), admin/staff (network-wide),
  admin/license, admin/audit
- NetworkAdminShell + NetworkAdminSidebar + NetworkTopBar with club
  switcher
- DashboardShell detects network access and renders top bar accordingly
- Clubs components: create-club-dialog, edit-club-dialog, actions-menu
- /structure route (club org-chart) in standard dashboard layout
- Doc pages: auth-refactor-plan, org-structure-plan, visual-editor-redesign
- scripts/add-club-subdomain.sh (auto-provision nginx vhost on trial)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 13:08:05 +00:00
root
142b2a446b feat(registration): trial auto-provisioning with club+user creation
- Migration 00012_trial_auto_provision: PlatformLeadStatus adds
  REPEAT_REQUEST; platform_leads new columns convertedUserId,
  convertedClubSlug, activationToken (unique), generatedPassword;
  "Повторный запрос" stage added to default pipeline
- Schema backfill: department models (Department, DepartmentMember,
  DepartmentLog) + DepartmentType/DeptMemberRole/DeptLogAction enums +
  User back-relations (previously only in migration 00010)
- RegistrationService: auto-provisions Club + User on lead confirmation,
  generates activation token + password, handles REPEAT_REQUEST for
  existing emails
- RegistrationListener: send activation email/SMS; logs status transitions
- LP RegistrationWizard: post-submit states, resend flow
- /document/trial-auto-provision-plan: design doc

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 13:06:05 +00:00
root
acc8ab0b0d feat(platform-telephony): SIP-based calls with recordings + platform users
Backfill platform_users schema (tables existed only in DB/generated client):
- Schema: PlatformUser, PlatformRefreshToken, PlatformRole enum
- Migration 00011_platform_users: table for SUPER_ADMIN/SALES_MANAGER/SUPPORT

Platform telephony:
- Schema: PlatformSipConfig, PlatformCall + PlatformCallDirection /
  PlatformCallStatus enums; PlatformLead.calls back-relation
- Migration 00015_platform_calls (idempotent: IF NOT EXISTS + DO $$)
- API /v1/platform-telephony: call log CRUD, status updates, recording
  upload, comments, SIP config upsert; excluded from tenant middleware
- Softphone UI in platform-admin: SoftphoneProvider + widget in dashboard
  layout, click-to-call from lead detail, call timeline entries with
  recordings/duration, /settings/telephony config page
- Kamailio + rtpengine in docker-compose (host network, recording volume)
- infra/kamailio: Dockerfile, kamailio.cfg, tls.cfg (certs gitignored)
- LP /support/mango-sip-trace: Mango Office 403 INVITE diagnostic page
- Sidebar: Телефония entry (SUPER_ADMIN)
- +sip.js@0.21.2
- .gitignore: /data/recordings, /infra/kamailio/certs

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 13:01:42 +00:00
root
3cd7eb9051 feat(staff-invites): email-based staff onboarding with tokens
- DB migration 00013_staff_invites: StaffInvite model with PENDING/VIEWED/
  ACCEPTED/EXPIRED/CANCELLED status, unique token, 7-day expiry
- API /v1/staff-invites: create (bulk emails + role), list, cancel, resend
- API /v1/invite/:token (public): view (marks VIEWED), accept (firstName,
  lastName, patronymic, phone, password, avatar → creates User)
- UI /staff: tabs Staff/Invites, invite dialog (emails textarea + role
  picker), invites table with status badges
- app.module: register StaffInvitesModule, exclude /v1/invite/(.*) from
  tenant middleware

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:45:30 +00:00
root
7b92834eb2 feat(departments): hierarchical org structure with members and roles
- DB migration 00010_org_structure: Department tree, DepartmentType
  (DEPARTMENT/TEAM), DeptMember with roles (EMPLOYEE/HEAD/DEPUTY),
  DepartmentLog audit trail, DeptLogAction enum
- DTOs: add-member, move-member, update-member, move-department
- DepartmentsService: CRUD, tree navigation, member management, move
  operations with audit logging
- UI /staff org-chart: drag-and-drop tree visualization with bottom bar,
  context menu (create/rename/move/delete), detail panel, user select
  dialog, node/connector components
- Create department wizard with type selection and parent picker

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:41:41 +00:00
root
1e4562ad46 feat(auth): platform login, forgot/reset password, per-role flows
- PlatformAuthService + PlatformAuthController: separate login for
  platform users (super admin, sales, support) distinct from club staff
- PlatformAuthGuard: JWT strategy for /platform-* endpoints
- Forgot password: POST /auth/forgot-password issues time-limited reset
  token; reset-password/[token] page validates and sets new hash
- Email-based password reset for both club-admin and platform-admin UIs
- JWT strategy extended to carry platform role claims
- Login DTO accepts email (platform) or phone (club staff)
- Typed AuthedRequest shape replaces `any` in request handlers
- Minor fixes: softphone unused type, sip context setRemoteDescription
  signature

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:35:19 +00:00
root
3afdd04b3e feat(telegram-bot): oneWay mode, emoji sanitization, form-urlencoded webhooks
- BotScenario.oneWay flag: prevent revisiting message/input nodes (acts
  at executeFromNode level with _visited_nodes array; reset on /start)
- Engine enriches variables with subscriber profile (_first_name,
  _last_name, _username, _phone, _source, _chat_id, _subscriber_id,
  _bot_id, _club_id) for use in webhook bodies and templates
- stripEmoji() removes 4-byte UTF-8 from names before CRM sync
  (Bitrix rejected leads with emoji-only names)
- Bot webhook processor supports application/x-www-form-urlencoded
  (Bitrix custom module expects form data, not JSON)
- Step editor: oneWay toggle in scenario header

Fixes: infinite send_to_crm duplication, Bitrix lead creation failures
for users with emoji in Telegram first_name, and referral loop when
user clicks /start from an input node.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:14:24 +00:00
root
ab7e666a4f chore(tooling): add quality gate hooks, custom skills, ignore debug artifacts
- Pre-commit hook: typecheck + unit tests for affected apps
- Pre-push hook: full gate (typecheck + unit + E2E + diff summary)
- Block-compile hook: prevent production compile on live server
- Custom skills: /test (smart runner by git diff), /review-pr (RBAC,
  multi-tenancy, OWASP, architecture conventions)
- .gitignore: debug screenshots, playwright-report, generated seed.js,
  data/{avatars,bot-media,backups,incidents,screenshots,recordings}

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 12:11:20 +00:00
root
0396e3b7b6 feat(bots): MAX messenger support alongside Telegram
- DB: BotMessenger enum + tg_bots.messenger field (default telegram)
- Adapter pattern: MessengerAdapter interface, TelegramAdapter (thin wrapper),
  MaxAdapter (platform-api.max.ru REST client), MessengerFactory routes by
  bot.messenger
- MAX infrastructure: max-bot-incoming queue, MaxPollingService,
  MaxIncomingProcessor (stub echo for handshake), MaxWebhookController at
  /v1/bots/webhook/max/:botId
- Guards: TelegramPollingService/TelegramIncomingProcessor only handle
  messenger='telegram' — MAX traffic routed separately
- BotManagerService.create/activate/deactivate use appropriate adapter via
  factory; webhook URL chosen by messenger
- UI: sidebar "Telegram-бот" → "Боты", messenger picker in create dialog,
  colored badge per messenger in bot cards
- Telegram bot unchanged throughout — all existing logic preserved

MAX bot tested end-to-end: webhook receives updates, MaxAdapter parses
dialog/chat correctly (sender.user_id for private chats, recipient.chat_id
for groups), echo response delivered.

Also fixes stale auth.service.spec.ts expectations and unused code in
invite-related components.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 11:39:36 +00:00
root
c988282b1a feat: trial registration with questionnaire, flash call, legal docs
- 6-step registration wizard on landing page (phone, SMS, profile, business, location, interests)
- uCaller flash call verification (0.40 rub/call vs 3-8 rub/SMS)
- PlatformLead/PlatformPipeline/PlatformStage models (separate from CRM)
- Registration API: start, verify-sms, resend, questionnaire
- Platform leads kanban + lead detail page with questionnaire answers
- 3 legal documents adapted for IP Lopashov: terms, privacy, data-processing
- SMTP via Yandex 360 (support@myfitcrm.ru) for welcome emails
- Telegram notification on new lead registration
- Migration 00009

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 07:40:56 +00:00
root
4ccad0026e feat: CLUBS_ADMIN multi-club management, ClubGroup, UserClubAccess
- Add CLUBS_ADMIN role with ClubGroup ownership (1 owner → N clubs)
- UserClubAccess for multi-club staff access with per-club roles
- Provisioning: provisionClubInGroup with license slot validation
- ClubSwitcher component, subdomain-based club routing
- Network staff management across club groups
- RolesGuard: CLUBS_ADMIN inherits CLUB_ADMIN permissions
- Auth: switch-club endpoint, club group ownership validation
- Platform-admin: clubs/licenses/audit filtered by group for CLUBS_ADMIN
- Migrations 00007-00008, documents, platform leads UI

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 07:40:22 +00:00
root
389dacec5e feat(telegram-bot): multi-image, WYSIWYG editor, referral logic, blocked users
Images:
- Multi-image support: sendPhoto / sendMediaGroup
- Local file upload via multipart for bot-media
- Media upload API endpoint
- Image support in input nodes

Step Editor:
- WYSIWYG contentEditable with formatting toolbar
- Paste from Miro/Docs preserves formatting
- Ctrl+Z undo, local state prevents cursor jumping
- Button drag-and-drop reordering
- Node rename with automatic reference updates
- Progressive delay intervals UI

Referral system:
- Bonus by registered friends (phone), not clicks
- onFriendRegistered notifies referrer
- Existing users get "promo for new users" message
- Invalid/self ref link protection, FK safety
- count_referrals action type
- 7 referral messages configurable in scenario settings

Blocked users:
- Catch blocked errors in engine + delay processor
- Dashboard and analytics stat cards

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 09:50:45 +00:00
root
022cb21eda feat(telegram-bot): visual scenario editor with 3 modes (step/schema/json)
- Step Editor: form-based editing for content managers (no JSON knowledge needed)
  - Editable text/buttons/targets via dropdowns
  - Main flow + collapsible sidebar branches
  - Add/delete steps, buttons, conditions

- Schema (React Flow): WatBot-style canvas with draggable nodes
  - NodeShell + PortRow components for clean card design
  - White cards with colored left accent borders
  - Blue bezier curves for all connections
  - Auto-layout: main column + BFS side columns
  - Pan/zoom, snap-to-grid, MiniMap

- Backend: polling service, /stop command, screenshot API, analytics

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 06:07:36 +00:00
root
fe07f3e13f feat(telegram-bot): add Telegram Bot Constructor module
Full-stack module for building Telegram chatbot scenarios in CRM.

Backend (NestJS):
- 6 Prisma models: TgBot, TgBotScenario, TgBotSubscriber, TgBotMessage,
  TgBotBroadcast, TgBotWebhook
- JSON scenario engine with 6 node types: message, condition, action,
  input, delay, referral
- Referral mechanics: deep links, invite tracking, friend routing
- Broadcasts with 10 audience filters, batch sending with rate limiting
- Outgoing webhooks: 9 event types, HMAC-SHA256 signing, retry
- CRM integration: create deals from bot scenarios
- Analytics: subscriber stats, referral metrics, funnel, daily growth
- 12 services, 4 BullMQ processors, 7 controllers, ~35 REST endpoints

Frontend (web-club-admin):
- 8 pages: bot list, dashboard, subscribers, broadcasts, scenario editor,
  webhooks, analytics
- Visual scenario editor with React Flow: 6 custom node types
- Sidebar: module-aware visibility (Hide, Don't Block)

Includes Powerhouse Gym referral scenario (24 nodes) and user docs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 10:40:03 +00:00
root
24d6042c00 fix(crm): super_admin видит все pipelines и deals без фильтра по clubId
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Для super_admin clubId=null — не добавляем фильтр WHERE clubId,
чтобы видеть данные всех клубов. Club roles фильтруют по своему clubId.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 15:35:08 +00:00
root
75bafc68f6 fix(crm): revert OR-фильтр pipelines, привязать к клубу в БД
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
clubId=null — платформенные данные, недоступны club_admin.
Вернул строгий фильтр по clubId. Pipelines привязаны к клубу в БД.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 15:02:27 +00:00
root
7e13c5ffc1 fix(crm): pipelines видны всем ролям (club-specific + shared)
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
findAll теперь возвращает pipelines с clubId текущего клуба И с
clubId=null (общие, созданные суперадмином). Ранее club_admin не
видел pipelines → фронтенд не загружал сделки.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 14:59:22 +00:00
root
3c822312ee fix(api): убрать by-number маршруты, GET /:id принимает UUID и number
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Удалены отдельные эндпоинты /by-number/:number для deals и users.
Теперь GET /:id определяет формат параметра (число → getByNumber,
UUID → getById) и вызывает соответствующий метод. Фронтенд вызывает
/crm/deals/{number} и /users/{number} напрямую.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 14:28:25 +00:00
root
91b13923cb fix(crm): клик по сделке — фоллбэк на UUID если нет number
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- onDealClick передаёт number (string) или UUID как фоллбэк
- deal/[id] загружает по by-number или по UUID в зависимости от формата
- Проставлен number=100 для сделки без номера в БД

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 14:21:23 +00:00
root
e791aa9201 feat(staff): роутинг сотрудников по number вместо UUID
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- API: GET /users/by-number/:number + findByNumber в UsersService
- Список: клик по сотруднику → /staff/{number}
- Детальная: загрузка через /users/by-number/{number}
- PATCH/avatar/password операции используют user.id (UUID) внутри
- Синхронизировано в web-platform-admin

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 14:11:46 +00:00
root
20830dda8b fix(crm): фоллбэк /crm/{uuid} → /crm/deal/{number} для старых ссылок
Старый маршрут /crm/[id] теперь редиректит UUID-ссылки (из кеша
браузера или внешних источников) на новый формат /crm/deal/{number}.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 14:03:53 +00:00
root
3bb4d5a28f feat(crm): роутинг с int ID, edit mode по карандашику, кнопки под блоками
- API: GET /crm/deals/by-number/:number для поиска сделки по номеру
- Маршруты: /crm/deal/kanban, /crm/deal/list, /crm/deal/{number}
- /crm редиректит на /crm/deal/kanban
- Карандашик в блоке переводит ВСЕ editable поля в edit mode
- Кнопки «Общий/Мой вид» и «Добавить раздел» — под блоками
- Убран double-click для редактирования полей
- onDealClick передаёт deal.number, API операции через deal.id (UUID)
- Изменения синхронизированы в web-platform-admin

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 13:53:08 +00:00
root
7eaef128f9 fix(infra): увеличить лимит памяти API до 1G, добавить source-maps
API с booking-модулем потребляет ~160MB (через dist/main.js),
ранее nest start тянул ~800MB и PM2 убивал по лимиту 512M.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 13:11:12 +00:00
5fcf8323d4 Merge pull request 'feat(booking): модуль онлайн-записи + CRM улучшения' (#3) from feature/booking-module into main
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
2026-02-27 12:49:31 +00:00
root
f87923233b fix: ESLint-фиксы, CRM card layout по ролям, нумерация сотрудников
Some checks failed
CI / Lint & Format (pull_request) Has been cancelled
PR Check / Lint & Typecheck (pull_request) Has been cancelled
CI / Backend Tests (pull_request) Has been cancelled
CI / Build All Apps (pull_request) Has been cancelled
CI / E2E Tests (Playwright) (pull_request) Has been cancelled
CI / Deploy to Production (pull_request) Has been cancelled
- API: роли в uppercase (login + refreshToken), user.number (порядковый),
  card-layout с roleAccess, notifications typing fix
- Mobile: void для floating promises, типизация Ionicons, удаление unused imports
- Web: CRM deal detail — динамическая раскладка по блокам, useUser хук,
  card-layout-editor расширен, staff number в списках
- Watchdog: мелкие правки

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 12:23:07 +00:00
root
afe2bb08fe feat(booking): модуль онлайн-записи — полный стек (API + Mobile + Web)
7 спринтов: Prisma-модели (14 таблиц, 5 enum), NestJS-модуль (CRUD, доступность,
расписание, групповые занятия, абонементы, оплаты, waitlist, webhooks, CRM-бридж,
уведомления, аналитика, кэш), мобильные экраны (список записей, детали, групповые
занятия), веб-панели (букинг-настройки, сайдбар), миграция PostgreSQL.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 12:14:46 +00:00
root
6cc65569e1 feat(crm): inline-редактирование, стадии, дела, загрузка аватаров
- GET /users/staff endpoint с поиском по имени
- Fix /staff → /users/staff во всех CRM-компонентах
- Searchable combobox для выбора ответственного (create/edit deal)
- Default assignee = текущий пользователь при создании сделки
- Bitrix-style переключатель стадий (цветные прямоугольники)
- Inline-редактирование карточки сделки (вместо диалога)
- Форма создания дел (активностей) в activity-list
- Loading states для Win/Lose/Delete/Complete (защита от двойных кликов)
- Fix body parser: NestJS API вместо дублирующих express middleware
- Копирование staff-компонентов в platform-admin (аватар, сотрудники)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 10:48:07 +00:00
root
204f8ce396 feat(crm): мультисущностная архитектура, роли, раскладка карточек
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- packages/crm-ui: переиспользуемые компоненты (EntityKanban, EntityTable,
  EntityCard, EntityFormDialog, StageSwitcher, ActivityList, TimelineFeed,
  FieldManager, PipelineManager, StageBadge)
- Pipeline entityType: воронки привязаны к типу сущности
- Role system: таблица roles + user_roles, multi-role JWT, RolesGuard
- Card layouts: admin-default + user-override раскладка карточек
- Field roleAccess: видимость полей per role (hidden/readonly/editable)
- EntityPermissions: multi-role поддержка (string | string[])
- DnD стадий, произвольный цвет стадий, FieldManager entityType prop

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 09:27:51 +00:00
root
a10673fdeb feat(crm): порядковые номера сделок, управление стадиями, редактирование, кастомные поля
— Очистка тестового мусора: дубликаты полей, пайплайнов, причин проигрыша
— Порядковые номера сделок (#N) per-club с @@unique([clubId, number])
— DELETE endpoints для стадий (с переносом сделок) и пайплайнов
— onDelete: Cascade→Restrict для стадий, SetNull для истории
— PipelineManager: полный CRUD воронок и стадий с палитрой цветов
— FieldManager: CRUD кастомных полей с типами и опциями
— EditDealDialog: редактирование сделки (контакт, сумма, компания, ответственный)
— Кастомные поля в форме создания и карточке сделки
— Soft-delete сделок, выбор ответственного, расширенные фильтры
— Поиск по номеру сделки (#42 / 42)
— Исправлены pre-existing тесты: module.guard, themes, auth, reports

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 07:33:46 +00:00
root
21c395d0d5 chatbot: [Цитата сообщения на которое отвечает пользователь]:
Задача #62 завершен
2026-02-26 19:40:01 +00:00
root
3d28f62ad0 chatbot: сделай тестовый документ
=== ОГРАНИЧЕНИЯ ЧАТБОТА ===
Ты можешь ТОЛЬКО:
2026-02-26 19:13:37 +00:00
root
cbb84cfa65 fix: merge-протокол worktree — split strategy (документы vs код), rebase
Корневая проблема: validateAndMerge() никогда не вызывалась из
task-manager — документы создавались в worktree, но не мёрджились
в main. Пользователь видел старый контент.

Исправлено:
- task-manager.ts: вызов validateAndMerge() после завершения задачи
- worktree-manager.ts: две стратегии мёрджа:
  - Документы (apps/*/document/**): fast path без lint/typecheck/test,
    rebase + merge, рестарт только web-platform-admin
  - Код: полный путь lint → typecheck → test → rebase → merge
- Rebase вместо ff-only решает расхождение веток при параллельной работе
- Восстановлен документ франшиз (90+ записей из chatbot worktree)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 17:40:28 +00:00
root
8da9515445 docs: AI-first workflow — test-first, декомпозиция по слоям, quality gate
Формализация процесса разработки на основе анализа статьи Zilliz
о провале Claude Code на крупном проекте. Новый документ описывает:
- Формат задачи с Definition of Done до начала работы
- Test-first подход (тесты → код → проверка)
- Послойная декомпозиция (Prisma → API → UI), max 20 файлов/коммит
- Автоматический quality gate (typecheck всех apps + тесты)
- Таблица антипаттернов и метрики качества

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 17:11:01 +00:00
root
e4b5e3c7c3 feat: карточка сотрудника, профили с role switcher, sidebar user info во всех панелях
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- Backend: GET/PATCH /users/:id, POST /users/:id/password, POST /users/:id/avatar
- Prisma: email, roomId, comment поля в User, relation к Room
- Static files: avatars через useStaticAssets, multer upload (5MB, JPEG/PNG/WebP)
- Club-admin: /staff/[id] — аватар, ФИО, email, телефон, роль, департамент, зал, комментарий, смена пароля
- Все панели: sidebar с user info + logout, /profile с role switcher для admin/super_admin
- Ecosystem: dist/main.js вместо nest start для стабильного запуска
- .npmrc: public-hoist-pattern для @types/* (fix pnpm + @types/react)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 11:13:57 +00:00
root
d7aa2ac6b4 feat: документ фитнес-студий, fix TS-ошибки CRM, typecheck защита от build-краша
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- Документ: сравнительный анализ 11 фитнес-студий Екатеринбурга
  (fitness-studios-comparison) — специализация, цены, ИНН, масштаб
- Fix: 3 strict-TS ошибки в CRM (possibly undefined) блокировавшие сборку
- Safety: скрипт typecheck (tsc --noEmit) во всех web-приложениях —
  безопасная проверка типов без удаления .next/
- CLAUDE.md: правило «никогда не запускать build на живом сервере»

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 10:10:01 +00:00
root
accfa61e08 fix: E2E тесты — 143/143 passed, 0 failed
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- Global setup: единый логин всех пользователей перед тестами (без rate limit)
- Playwright проекты: testMatch привязка файлов к проектам (убрал 5x дублирование)
- LP порт: 3004 → 3050 (реальный порт из ecosystem.config)
- Theme тесты: мок API через page.route() (предотвращение 401→logout)
- Web UI тесты: защита response?.status() ?? 200 от undefined
- getCachedTokens(): чтение токенов из файла вместо loginAs в каждом beforeAll

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 08:40:39 +00:00
root
8f1635f3a2 docs: уточнение Hide Don't Block — прямой URL допускает «контент недоступен»
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Ссылка от коллеги по прямому URL — допустимо показать страницу «Контент недоступен».
Но ссылка нигде в интерфейсе пользователя не должна появляться: ни в меню, ни в списках, ни в карточках.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 07:36:53 +00:00
root
f6d10aa276 docs: принцип Hide Don't Block + Role Switcher суперадмина
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- UX-авторизация: недоступные элементы не рендерятся (не «403 / нет прав»)
- Role Switcher: суперадмин переключает роль в header без перелогинивания
- Обновлены: CLAUDE.md, roles-rbac.md, business-logic.md, sprints.md
- Sprint 10: добавлены задачи 48-54 (RoleGate, filterByRole, impersonate API)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 07:34:05 +00:00
root
021337ce79 fix: CRM баги — permissions в win/lose/move, enum source, E2E тесты 17/17
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- DealManager.win/lose/move: добавлен skipPermissions в context (controller guard уже проверяет роли)
- WebhookProcessor: source 'LANDING' → 'FORM' (enum CrmDealSource)
- E2E: кэширование токенов в beforeAll, default pipeline setup, contactName в deal creation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 07:29:02 +00:00
root
fb414d4a57 feat: CRM-модуль — Entity Factory Pattern, сделки, воронки, таймлайн, вебхуки
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Sprint 9: Полная реализация CRM-модуля на базе Entity Factory Pattern.

Backend (45 файлов):
- Entity Factory Core: EntityManager<T> с lifecycle-хуками, событиями, правами
- Pipelines & Stages: CRUD, дефолтные B2B/B2C воронки с 7-8 стадиями
- Deals: создание, перемещение по стадиям, win/lose, cursor-пагинация, kanban view
- Timeline: лента событий (комментарии, звонки, стадии, формы), pin/unpin
- Activities: дела с планированием, завершением, просроченные через BullMQ scheduler
- Custom Fields: 8 типов (STRING/INTEGER/FLOAT/BOOLEAN/DATE/TIME/EMAIL/PHONE), CRUD
- Webhooks: антифрод (honeypot/timing/disposable/phone/fingerprint/IP), Smart Field Detection
- Trainings: entity manager с timeline-интеграцией
- CRM Scheduler: BullMQ processor (overdue activities, stale deals, unprocessed leads)

Frontend — Platform Admin + Club Admin:
- Kanban-доска с HTML5 drag-and-drop между стадиями
- Табличный вид со всеми фильтрами (pipeline, source, search)
- Карточка сделки: контакт, реквизиты, таймлайн, дела, тренировки
- Настройки CRM: 4 вкладки (воронки, кастомные поля, вебхуки, причины проигрыша)
- Форма лендинга: honeypot, timing, UTM, POST на /crm/deals/from-form

E2E тесты: Pipelines, Deals CRUD, Timeline, Activities, Form spam, RBAC, Lost Reasons, Custom Fields

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-26 07:04:59 +00:00
root
8110651561 fix: персистентность тем + кросс-сервисная синхронизация
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Корневая причина: @unique на themeId в Prisma → P2002 ошибка при
повторной установке ранее использованной темы → .catch() скрывал ошибку →
API fetch на перезагрузке возвращал старую тему и перезаписывал localStorage.

Исправления:
- Убран @unique с themeId в PlatformTheme (разрешает аудит-трейл)
- Добавлен @@index([createdAt]) для быстрого findFirst orderBy desc
- handleApply теперь показывает ошибки пользователю вместо .catch(() => {})
- Лендинг: @theme inline → @theme, добавлен ThemeSync компонент
  (подтягивает primary color из API и применяет к LP)
- Lint-фиксы в competitor-analysis-skk

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 15:26:25 +00:00
root
3959db8779 fix: темы теперь применяются к сайдбару — @theme inline → @theme, E2E тесты
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- Заменили @theme inline на @theme в globals.css всех 3 приложений —
  Tailwind v4 теперь генерирует var() ссылки вместо хардкода значений,
  что позволяет runtime-переключение тем через CSS custom properties
- Исправлен дублирующийся React-ключ #42A5F5 в палитре Azure Professional
- Исправлена key-стратегия: key={color.hex} → key={color.name}
- Убраны неиспользуемые импорты в theme-provider (web-admin, web-club-admin)
- Добавлены E2E тесты: применение темы к сайдбару, отсутствие duplicate keys

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 15:04:07 +00:00
root
bad59cfcbc fix: полный ребрендинг FitCRM → MyFitCRM — лендинг, логины, документы, тесты
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- Лендинг: layout title, Hero, Footer, Problems, Testimonials, FAQ, Integrations
- Логин-страницы: web-admin, web-club-admin, web-platform-admin (лого MF + MyFitCRM)
- Mobile: экран авторизации
- Backend: TOTP issuer, seed.ts, integration-sync comments
- Документы: dev-status, competitor-analysis, best-design-solutions
- Темы: превью в настройках тем
- E2E тесты: landing.spec.ts, e2e-tests.ts data

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 14:43:36 +00:00
root
3578e49c7e chore: обновление страницы «Разработка» — Sprint 8 прогресс 92%, theme-aware компоненты
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 14:38:08 +00:00
root
1e0e9750b1 feat: улучшение тем, ребрендинг MyFitCRM, полное покрытие темами всех сервисов
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- Обновлены цветовые схемы 9 тем (WCAG AA, контраст sidebar ≥8:1)
- Заменены 60+ hardcoded цветов на theme-aware классы (text-text, bg-card, text-error и т.д.)
- Создан SVG-логотип MyFitCRM (компонент Logo с вариантами full/icon)
- Ребрендинг FitCRM → MyFitCRM во всех 5 сервисах (17 файлов)
- Добавлена поддержка тем в web-admin и web-club-admin (ThemeProvider, globals.css)
- Обновлена страница «Разработка»: спринты, прогресс, theme-aware компоненты

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 14:27:05 +00:00
root
3d5945523a feat: backend API модуль тем оформления — NestJS + Prisma + E2E интеграция
Some checks failed
CI / Lint & Format (push) Has been cancelled
CI / Backend Tests (push) Has been cancelled
CI / Build All Apps (push) Has been cancelled
CI / E2E Tests (Playwright) (push) Has been cancelled
CI / Deploy to Production (push) Has been cancelled
- ThemesModule: service, controller, DTOs, theme-definitions (10 тем)
- PlatformTheme Prisma-модель (37-я таблица), GET /v1/theme/current (публичный)
- PUT /v1/admin/themes/active, GET /v1/admin/themes, GET /v1/admin/themes/history (superadmin)
- EventEmitter2 theme.changed для webhook-доставки
- 10 unit-тестов, ThemeProvider фетч из API + localStorage fallback
- Оптимистичное обновление темы, стабильные E2E waitForFunction

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 13:34:01 +00:00