- findForEvolution() now excludes DELETED conversations (should not learn from deleted data)
- getConversation() rejects DELETED conversations for user-facing operations (sendMessage, getMessages, etc.)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The delete conversation endpoint was a no-op — it verified ownership but
never actually modified the record. Users saw conversations disappear
(frontend optimistic removal) but they reappeared on refresh.
Changes:
- conversation.entity.ts: Add DELETED status, softDelete() and isDeleted()
- conversation.service.ts: Call softDelete() + update instead of no-op
- conversation-postgres.repository.ts: Exclude DELETED conversations
from findByUserId() queries so they don't appear in user's list
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
AdminConversationController's GET /:id was intercepting requests to
AdminEvaluationRuleController (matching "evaluation-rules" as an id param).
Similarly, DELETE /:id was matching "cache" as an id.
Changes:
- conversation.module.ts: Register AdminMcpController and
AdminEvaluationRuleController before AdminConversationController
(more specific prefixes must come first in NestJS)
- admin-evaluation-rule.controller.ts: Move static routes (POST /test,
DELETE /cache) before dynamic routes (GET/:id, DELETE/:id)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The AdminEvaluationRuleController in ConversationModule needs the
EVALUATION_RULE_REPOSITORY token. Even though AgentsModule is @Global(),
Symbol-based providers must be explicitly exported to be available
in other modules.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Adds tenant_id UUID column to user_memories, system_experiences,
knowledge_articles, and knowledge_chunks tables with default tenant
backfill and indexes. Migration already applied to production DB.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
claude-haiku-3-5-20241022 returns 404 on the proxy. Updated to
claude-haiku-4-5-20251001 in agent configs and context injector.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The mapEventToStreamChunk was mapping both 'usage' (per-turn) and 'end'
(final) events to type 'end', causing the gateway to emit multiple
stream_end events. This made the frontend create a separate message
bubble (with its own bot avatar) for each agent loop turn.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
WebSocket gateway was missing AsyncLocalStorage tenant context setup,
causing 'Tenant context not set' error on every message. Now extracts
tenantId from handshake and wraps handleMessage in tenantContext.runAsync().
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add tenant_id column to conversations, messages, token_usages tables
- Create standalone migration SQL script for production deployment
- Add agent_executions table to init-db.sql for new installations
- Fix MessageORM created_at nullable mismatch with database schema
- Backfill existing data with default tenant ID
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Replace IKnowledgeClient TypeScript interface (erased at runtime) with KnowledgeClientService concrete class injection
- Fix method signatures to match KnowledgeClientService API:
- getUserMemories() → getUserTopMemories(), field type → memoryType
- retrieveForPrompt(query, userId) → retrieveForPrompt({ query, userId })
- getRelevantExperiences(query, n) → searchExperiences({ query, limit: n }), field type → experienceType
- Remove unused ContextData import
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add x-admin-id header to API interceptor from auth store
- Required for super admin tenant management APIs
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Fix toDto method to handle statDate being string or Date
- Fix getTrendData method to handle statDate being string or Date
- PostgreSQL date type returns string, not Date object
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Add is_super_admin column to admins table in migration script
- Add index for is_super_admin column
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Update AdminPostgresRepository.findByUsername to support super admin
- Add fallback to find super admin by username and isSuperAdmin flag
- Add is_super_admin column to admins table
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Fix nginx admin location try_files to use relative path for alias directive
- Add database migrations for multi-tenancy support in user-service
- Add tenant_id column to users, user_profiles, user_contacts, verification_codes tables
- Create migration rollback scripts and documentation
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
- Add tenants feature module with Clean Architecture structure
- Create tenantsApi for super admin endpoints
- Add React Query hooks for tenant CRUD operations
- Implement TenantsPage with statistics, list, and modals
- Add tenant route and sidebar menu item
- Support create/edit tenant, suspend/activate, admin management
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add SuperAdmin module for tenant management (CRUD, suspend/activate)
- Add tenant management REST API (/super-admin/tenants/*)
- Add user profile menu in ChatSidebar with dropdown
- Add ProfilePage and BindPhonePage for user account management
- Update init-db.sql with tenant_id columns for all 16 tables
- Add database seed script (scripts/seed.ts) with ts-node
- Integrate db:seed into deploy.sh rebuild command
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Use SimpleTenantFinder for evolution-service middleware (same as other services)
- Keep TenantFinderService available via TenantModule for super-admin
- Add useExternalFinder option to TenantContextModule
- Remove @Global() decorator from TenantContextModule class
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
All services were providing TenantContextService directly without
making it global, causing DI resolution failures in child modules.
Now using TenantContextModule.forRoot() which exports TenantContextService
globally so all repositories can access it.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
npm install was clearing the @iconsulting/shared folder that was
copied before it. Moving the COPY command after npm install ensures
the shared package remains in node_modules.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- deploy.sh deploy now uses --no-cache by default to ensure
@iconsulting/shared package is correctly bundled into images
- Add --cache option if user wants to use Docker cache for faster builds
- This fixes the "Cannot find module '@iconsulting/shared'" error
that occurred when Docker used cached images without the latest shared code
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add UserProfile entity with immigration-specific fields:
- Basic info (name, birth date, nationality, current location)
- Immigration intent (target countries, types, timeline)
- Education records with WES evaluation flag
- Work records with NOC codes
- Language scores (IELTS, TOEFL, etc.)
- Family members info
- Financial info for investment immigration
- Profile completion percentage calculation
- Add UserContact entity for identity binding:
- Support multiple contact types (EMAIL, WECHAT, WHATSAPP, TELEGRAM, LINE)
- Verification code flow with expiration
- Notification settings (paid feature)
- Notification types: POLICY_UPDATE, DEADLINE_REMINDER, etc.
- Add API endpoints:
- GET/PUT /users/me/profile/* for profile sections
- GET/POST/PUT/DELETE /users/me/contacts for contact management
- POST /users/me/contacts/:type/verification for verification flow
- POST/PUT/DELETE /users/me/contacts/:type/notifications
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- knowledge-postgres.repository: add tenant_id to all queries and raw SQL
- memory-postgres.repository: add tenant_id filtering for UserMemory and SystemExperience
- admin-postgres.repository: add tenant_id filtering (direct injection for nullable tenantId)
- All 11 repositories now have proper tenant isolation
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Apply TenantContextMiddleware to all 6 services
- Add SimpleTenantFinder for services without direct tenant DB access
- Add TenantFinderService for evolution-service with database access
- Refactor 8 repositories to extend BaseTenantRepository:
- user-postgres.repository.ts
- verification-code-postgres.repository.ts
- conversation-postgres.repository.ts
- message-postgres.repository.ts
- token-usage-postgres.repository.ts
- file-postgres.repository.ts
- order-postgres.repository.ts
- payment-postgres.repository.ts
- Add @iconsulting/shared dependency to evolution-service and knowledge-service
- Configure middleware to exclude health and super-admin paths
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add token aggregation to statistics/overview endpoint
- Include total tokens, cost, and API calls for all time
- Include today's token usage and cost breakdown
- Display token stats in ConversationsPage with 2 rows of cards
- Add formatNumber helper for K/M number formatting
- Export GlobalTokenStats and TodayTokenStats types
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add 'error' chunk type to StreamChunk for partial token capture
- Record partial tokens to token_usage table even on API errors
- Capture error chunk tokens in conversation.service.ts
- Save partial response and tokens before re-throwing errors
- Add token aggregation from token_usage table for accurate stats
- Display detailed token info in admin (cache tokens, cost, API calls)
- Export TokenDetails type for frontend consumption
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Problem:
- Token usage was recorded to token_usage table but not to conversation entity
- Message count was not being incremented
- Dashboard showed 0 tokens for all conversations
Solution:
- Add inputTokens/outputTokens fields to StreamChunk interface
- Return token usage in 'end' chunk from ClaudeAgentServiceV2
- Capture token usage in conversation.service.ts sendMessage
- Call conversation.addTokens() and incrementMessageCount() after each exchange
- Consolidate conversation updates into single repo.update() call
Files changed:
- claude-agent-v2.service.ts: Add token fields to StreamChunk, return in 'end'
- conversation.service.ts: Track tokens and message counts properly
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
## Device Tracking (conversation-service)
- Add DeviceInfoDto class for validating device information
- Extract client IP from X-Forwarded-For and X-Real-IP headers
- Capture User-Agent header automatically on conversation creation
- Support optional fingerprint and region from client
- Pass deviceInfo through service layer to entity for persistence
Files changed:
- conversation.controller.ts: Add extractClientIp() method and header capture
- conversation.dto.ts: Add DeviceInfoDto with validation decorators
- conversation.service.ts: Update CreateConversationParams interface
## Build Optimization (admin-client)
- Implement code splitting via Rollup manualChunks
- Separate vendor libraries into cacheable chunks:
- vendor-react: react, react-dom, react-router-dom (160KB)
- vendor-antd: antd, @ant-design/icons (1013KB)
- vendor-charts: recharts (409KB)
- vendor-data: @tanstack/react-query, axios, zustand (82KB)
- Main bundle reduced from 1732KB to 61KB (96% reduction)
- Set chunkSizeWarningLimit to 1100KB for antd
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Both user-service and evolution-service need the same JWT_SECRET
to verify admin tokens correctly.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Backend (user-service):
- Add admin user management APIs (list, search, statistics, detail)
- Add pagination and filtering support for user queries
- Add JWT token authentication for admin endpoints
Frontend (admin-client):
- Add UsersPage with user list, search, filters and statistics
- Add SettingsPage with admin profile, password change, system info
- Update App.tsx routes to use new pages
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Move specific routes (logs/actions, logs/entity-types) before
parameterized route (logs/:id) to prevent NestJS from matching
'actions' and 'entity-types' as UUID parameters.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The useEvolutionStatistics and useSystemHealth hooks call endpoints that
depend on a non-existent knowledge-service internal API. Removed these
calls and the related UI sections to prevent 500 errors.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Backend (evolution-service):
- Add analytics module with scheduled statistics aggregation
- Implement daily_statistics aggregation (OVERALL, CHANNEL, CATEGORY)
- Add monthly financial report generation and management
- Create audit log service for operation tracking
- Schedule cron jobs for automatic data aggregation
Frontend (admin-client):
- Replace dashboard mock data with real API calls
- Add analytics page with trend charts and dimension breakdown
- Add financial reports page with confirm/lock workflow
- Add audit logs page with filtering and detail view
- Update navigation with analytics submenu
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>