Spaces:
Running
Running
axeronis commited on
Commit ·
20ee727
1
Parent(s): 9964547
feat: Unified AI Brain 2.0 (Merged Knowledge Base & Persona, Removed /knowledge routes)
Browse files- backend/alembic/versions/2025_12_16_0305-2bd4aa712577_add_pending_changes.py +912 -0
- backend/app/api/billing.py +155 -974
- backend/app/api/deps.py +21 -0
- backend/app/api/google_calendar.py +94 -0
- backend/app/api/meta_webhooks.py +308 -0
- backend/app/api/voice.py +30 -0
- backend/app/api/websocket_voice.py +92 -0
- backend/app/core/config.py +7 -0
- backend/app/core/redis.py +30 -0
- backend/app/main.py +6 -2
- backend/app/models/knowledge.py +1 -1
- backend/app/models/tenant.py +12 -0
- backend/app/services/ai_memory_manager.py +6 -0
- backend/app/services/booking_service.py +83 -8
- backend/app/services/cache_service.py +78 -0
- backend/app/services/google_calendar.py +177 -0
- backend/app/services/llm_client.py +19 -0
- backend/app/services/meta_instagram.py +118 -0
- backend/app/services/meta_whatsapp.py +187 -0
- backend/app/services/stripe_service.py +115 -0
- backend/app/services/voice_manager.py +124 -0
- backend/app/services/voice_service.py +43 -0
- backend/app/services/whatsapp_qr.py +9 -3
- backend/app/tasks/ai.py +12 -0
- backend/app/tasks/email.py +26 -0
- backend/app/worker.py +29 -0
- backend/scripts/fix_env.py +35 -0
- backend/scripts/health_check.py +78 -0
- backend/scripts/patch_db_schema.py +70 -0
- backend/scripts/test_meta_ig.py +42 -0
- backend/scripts/test_meta_wa.py +43 -0
- backend/scripts/test_voice.py +28 -0
- backend/test_voice.mp3 +3 -0
- frontend/app/dashboard/page.tsx +156 -311
- frontend/app/globals.css +98 -47
- frontend/app/knowledge/page.tsx +0 -404
- frontend/app/live/page.tsx +51 -0
- frontend/app/page.tsx +131 -1
- frontend/app/settings/billing/page.tsx +306 -167
- frontend/app/settings/brain/page.tsx +364 -12
- frontend/components/Sidebar.tsx +92 -114
- frontend/components/Voice/LiveConversation.tsx +121 -0
- frontend/hooks/useAudioStream.ts +157 -0
backend/alembic/versions/2025_12_16_0305-2bd4aa712577_add_pending_changes.py
ADDED
|
@@ -0,0 +1,912 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""add_pending_changes
|
| 2 |
+
|
| 3 |
+
Revision ID: 2bd4aa712577
|
| 4 |
+
Revises: 2025_12_14_1000
|
| 5 |
+
Create Date: 2025-12-16 03:05:58.626841
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
from typing import Sequence, Union
|
| 9 |
+
|
| 10 |
+
from alembic import op
|
| 11 |
+
import sqlalchemy as sa
|
| 12 |
+
import sqlmodel
|
| 13 |
+
from sqlalchemy.dialects import postgresql
|
| 14 |
+
|
| 15 |
+
# revision identifiers, used by Alembic.
|
| 16 |
+
revision: str = '2bd4aa712577'
|
| 17 |
+
down_revision: Union[str, None] = '2025_12_14_1000'
|
| 18 |
+
branch_labels: Union[str, Sequence[str], None] = None
|
| 19 |
+
depends_on: Union[str, Sequence[str], None] = None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def upgrade() -> None:
|
| 23 |
+
# ### commands auto generated by Alembic - please adjust! ###
|
| 24 |
+
op.drop_table('system_announcements')
|
| 25 |
+
op.alter_column('ai_feedback', 'feedback_type',
|
| 26 |
+
existing_type=postgresql.ENUM('POSITIVE', 'NEGATIVE', 'CORRECTION', 'INSTRUCTION', name='feedbacktype'),
|
| 27 |
+
comment=None,
|
| 28 |
+
existing_comment='Type: positive, negative, correction, instruction',
|
| 29 |
+
existing_nullable=False)
|
| 30 |
+
op.alter_column('ai_feedback', 'is_applied',
|
| 31 |
+
existing_type=sa.BOOLEAN(),
|
| 32 |
+
comment=None,
|
| 33 |
+
existing_comment='Whether feedback was converted to training example',
|
| 34 |
+
existing_nullable=False)
|
| 35 |
+
op.drop_index('idx_ai_feedback_conversation', table_name='ai_feedback')
|
| 36 |
+
op.drop_index('idx_ai_feedback_created', table_name='ai_feedback')
|
| 37 |
+
op.drop_index('idx_ai_feedback_status', table_name='ai_feedback')
|
| 38 |
+
op.drop_index('idx_ai_feedback_tenant', table_name='ai_feedback')
|
| 39 |
+
op.drop_index('idx_ai_feedback_type', table_name='ai_feedback')
|
| 40 |
+
op.drop_table_comment(
|
| 41 |
+
'ai_feedback',
|
| 42 |
+
existing_comment='User feedback on AI responses for continuous learning',
|
| 43 |
+
schema=None
|
| 44 |
+
)
|
| 45 |
+
op.alter_column('ai_learning_rules', 'priority',
|
| 46 |
+
existing_type=sa.INTEGER(),
|
| 47 |
+
comment=None,
|
| 48 |
+
existing_comment='Priority 1-10, higher number = higher priority',
|
| 49 |
+
existing_nullable=False)
|
| 50 |
+
op.drop_index('idx_ai_rules_active', table_name='ai_learning_rules', postgresql_where='(is_active = true)')
|
| 51 |
+
op.drop_index('idx_ai_rules_category', table_name='ai_learning_rules')
|
| 52 |
+
op.drop_index('idx_ai_rules_priority', table_name='ai_learning_rules')
|
| 53 |
+
op.drop_index('idx_ai_rules_tenant', table_name='ai_learning_rules')
|
| 54 |
+
op.drop_table_comment(
|
| 55 |
+
'ai_learning_rules',
|
| 56 |
+
existing_comment='Custom learned rules from user feedback',
|
| 57 |
+
schema=None
|
| 58 |
+
)
|
| 59 |
+
op.alter_column('ai_training_examples', 'weight',
|
| 60 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 61 |
+
comment=None,
|
| 62 |
+
existing_comment='Importance weight (0.0-2.0), higher = more important',
|
| 63 |
+
existing_nullable=False)
|
| 64 |
+
op.alter_column('ai_training_examples', 'success_rate',
|
| 65 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 66 |
+
comment=None,
|
| 67 |
+
existing_comment='Success rate when this example is used',
|
| 68 |
+
existing_nullable=False)
|
| 69 |
+
op.drop_index('idx_ai_training_active', table_name='ai_training_examples', postgresql_where='(is_active = true)')
|
| 70 |
+
op.drop_index('idx_ai_training_category', table_name='ai_training_examples')
|
| 71 |
+
op.drop_index('idx_ai_training_status', table_name='ai_training_examples')
|
| 72 |
+
op.drop_index('idx_ai_training_tenant', table_name='ai_training_examples')
|
| 73 |
+
op.drop_index('idx_ai_training_weight', table_name='ai_training_examples')
|
| 74 |
+
op.drop_table_comment(
|
| 75 |
+
'ai_training_examples',
|
| 76 |
+
existing_comment='Few-shot learning examples for personalized AI',
|
| 77 |
+
schema=None
|
| 78 |
+
)
|
| 79 |
+
op.alter_column('conversations', 'taken_over_at',
|
| 80 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 81 |
+
type_=sa.DateTime(),
|
| 82 |
+
existing_nullable=True)
|
| 83 |
+
op.alter_column('conversations', 'started_at',
|
| 84 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 85 |
+
type_=sa.DateTime(),
|
| 86 |
+
existing_nullable=False,
|
| 87 |
+
existing_server_default=sa.text('now()'))
|
| 88 |
+
op.alter_column('conversations', 'ended_at',
|
| 89 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 90 |
+
type_=sa.DateTime(),
|
| 91 |
+
existing_nullable=True)
|
| 92 |
+
op.create_index(op.f('ix_conversations_is_active'), 'conversations', ['is_active'], unique=False)
|
| 93 |
+
op.drop_index('idx_crm_field_mappings_default', table_name='crm_field_mappings', postgresql_where='(is_default = true)')
|
| 94 |
+
op.drop_index('idx_crm_field_mappings_type', table_name='crm_field_mappings')
|
| 95 |
+
op.drop_table_comment(
|
| 96 |
+
'crm_field_mappings',
|
| 97 |
+
existing_comment='Field mapping templates for different CRM systems',
|
| 98 |
+
schema=None
|
| 99 |
+
)
|
| 100 |
+
op.alter_column('crm_integrations', 'auto_sync',
|
| 101 |
+
existing_type=sa.BOOLEAN(),
|
| 102 |
+
comment=None,
|
| 103 |
+
existing_comment='Automatically sync on lead updates',
|
| 104 |
+
existing_nullable=False)
|
| 105 |
+
op.alter_column('crm_integrations', 'field_mapping',
|
| 106 |
+
existing_type=postgresql.JSON(astext_type=sa.Text()),
|
| 107 |
+
comment=None,
|
| 108 |
+
existing_comment='JSON mapping: MicroFunnel field → CRM field',
|
| 109 |
+
existing_nullable=True)
|
| 110 |
+
op.alter_column('crm_integrations', 'sync_only_hot_leads',
|
| 111 |
+
existing_type=sa.BOOLEAN(),
|
| 112 |
+
comment=None,
|
| 113 |
+
existing_comment='Only sync leads with heat_score >= 70',
|
| 114 |
+
existing_nullable=False)
|
| 115 |
+
op.drop_index('idx_crm_integrations_tenant', table_name='crm_integrations')
|
| 116 |
+
op.drop_index('idx_crm_integrations_type', table_name='crm_integrations')
|
| 117 |
+
op.drop_table_comment(
|
| 118 |
+
'crm_integrations',
|
| 119 |
+
existing_comment='CRM integration configurations for tenants',
|
| 120 |
+
schema=None
|
| 121 |
+
)
|
| 122 |
+
op.alter_column('crm_sync_logs', 'duration_ms',
|
| 123 |
+
existing_type=sa.INTEGER(),
|
| 124 |
+
comment=None,
|
| 125 |
+
existing_comment='API call duration in milliseconds',
|
| 126 |
+
existing_nullable=True)
|
| 127 |
+
op.drop_index('idx_crm_sync_logs_created', table_name='crm_sync_logs')
|
| 128 |
+
op.drop_index('idx_crm_sync_logs_integration', table_name='crm_sync_logs')
|
| 129 |
+
op.drop_index('idx_crm_sync_logs_lead', table_name='crm_sync_logs')
|
| 130 |
+
op.drop_index('idx_crm_sync_logs_success', table_name='crm_sync_logs')
|
| 131 |
+
op.drop_index('idx_crm_sync_logs_tenant', table_name='crm_sync_logs')
|
| 132 |
+
op.drop_table_comment(
|
| 133 |
+
'crm_sync_logs',
|
| 134 |
+
existing_comment='Log of all CRM synchronization operations',
|
| 135 |
+
schema=None
|
| 136 |
+
)
|
| 137 |
+
op.alter_column('knowledge_base', 'created_at',
|
| 138 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 139 |
+
type_=sa.DateTime(),
|
| 140 |
+
existing_nullable=False,
|
| 141 |
+
existing_server_default=sa.text('now()'))
|
| 142 |
+
op.alter_column('knowledge_base', 'updated_at',
|
| 143 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 144 |
+
type_=sa.DateTime(),
|
| 145 |
+
existing_nullable=False,
|
| 146 |
+
existing_server_default=sa.text('now()'))
|
| 147 |
+
op.alter_column('lead_crm_links', 'sync_hash',
|
| 148 |
+
existing_type=sa.VARCHAR(),
|
| 149 |
+
comment=None,
|
| 150 |
+
existing_comment='MD5 hash of lead data to detect changes',
|
| 151 |
+
existing_nullable=True)
|
| 152 |
+
op.drop_index('idx_lead_crm_links_crm_contact', table_name='lead_crm_links')
|
| 153 |
+
op.drop_index('idx_lead_crm_links_crm_lead', table_name='lead_crm_links')
|
| 154 |
+
op.drop_index('idx_lead_crm_links_integration', table_name='lead_crm_links')
|
| 155 |
+
op.drop_index('idx_lead_crm_links_lead', table_name='lead_crm_links')
|
| 156 |
+
op.drop_index('idx_lead_crm_links_tenant', table_name='lead_crm_links')
|
| 157 |
+
op.drop_table_comment(
|
| 158 |
+
'lead_crm_links',
|
| 159 |
+
existing_comment='Links between MicroFunnel leads and external CRM records',
|
| 160 |
+
schema=None
|
| 161 |
+
)
|
| 162 |
+
op.alter_column('leads', 'status',
|
| 163 |
+
existing_type=sa.VARCHAR(),
|
| 164 |
+
type_=sa.Enum('NEW', 'QUALIFIED', 'IN_PROGRESS', 'CLOSED_WON', 'CLOSED_LOST', 'JUNK', name='leadstatus'),
|
| 165 |
+
existing_nullable=False,
|
| 166 |
+
existing_server_default=sa.text("'new'::character varying"))
|
| 167 |
+
op.alter_column('leads', 'heat_level',
|
| 168 |
+
existing_type=sa.VARCHAR(),
|
| 169 |
+
type_=sa.Enum('HOT', 'WARM', 'COLD', 'JUNK', name='leadheat'),
|
| 170 |
+
existing_nullable=False,
|
| 171 |
+
existing_server_default=sa.text("'cold'::character varying"))
|
| 172 |
+
op.alter_column('leads', 'psychotype',
|
| 173 |
+
existing_type=sa.VARCHAR(),
|
| 174 |
+
type_=sa.Enum('DOMINANT', 'INFLUENTIAL', 'STEADY', 'CONSCIENTIOUS', 'UNKNOWN', name='psychotype'),
|
| 175 |
+
existing_nullable=False,
|
| 176 |
+
existing_server_default=sa.text("'unknown'::character varying"))
|
| 177 |
+
op.alter_column('leads', 'ai_summary_json',
|
| 178 |
+
existing_type=postgresql.JSONB(astext_type=sa.Text()),
|
| 179 |
+
type_=sa.JSON(),
|
| 180 |
+
nullable=True,
|
| 181 |
+
existing_server_default=sa.text("'{}'::jsonb"))
|
| 182 |
+
op.alter_column('leads', 'current_stage_id',
|
| 183 |
+
existing_type=sa.UUID(),
|
| 184 |
+
comment=None,
|
| 185 |
+
existing_comment='Current stage in the sales playbook workflow',
|
| 186 |
+
existing_nullable=True)
|
| 187 |
+
op.alter_column('leads', 'first_message_at',
|
| 188 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 189 |
+
type_=sa.DateTime(),
|
| 190 |
+
existing_nullable=False,
|
| 191 |
+
existing_server_default=sa.text('now()'))
|
| 192 |
+
op.alter_column('leads', 'last_message_at',
|
| 193 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 194 |
+
type_=sa.DateTime(),
|
| 195 |
+
existing_nullable=False,
|
| 196 |
+
existing_server_default=sa.text('now()'))
|
| 197 |
+
op.alter_column('leads', 'last_activity_at',
|
| 198 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 199 |
+
type_=sa.DateTime(),
|
| 200 |
+
existing_nullable=False,
|
| 201 |
+
existing_server_default=sa.text('now()'))
|
| 202 |
+
op.alter_column('leads', 'assigned_at',
|
| 203 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 204 |
+
type_=sa.DateTime(),
|
| 205 |
+
existing_nullable=True)
|
| 206 |
+
op.alter_column('leads', 'created_at',
|
| 207 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 208 |
+
type_=sa.DateTime(),
|
| 209 |
+
existing_nullable=False,
|
| 210 |
+
existing_server_default=sa.text('now()'))
|
| 211 |
+
op.alter_column('leads', 'updated_at',
|
| 212 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 213 |
+
type_=sa.DateTime(),
|
| 214 |
+
existing_nullable=False,
|
| 215 |
+
existing_server_default=sa.text('now()'))
|
| 216 |
+
op.drop_index('idx_leads_crm_id', table_name='leads', postgresql_where='(crm_id IS NOT NULL)')
|
| 217 |
+
op.drop_index('idx_leads_crm_sync', table_name='leads', postgresql_where='(crm_sync_status IS NOT NULL)')
|
| 218 |
+
op.drop_index('idx_leads_current_stage', table_name='leads')
|
| 219 |
+
op.drop_index('idx_leads_processing_status', table_name='leads')
|
| 220 |
+
op.drop_index('ix_leads_ever_qualified', table_name='leads')
|
| 221 |
+
op.drop_index('ix_leads_qualified_at', table_name='leads')
|
| 222 |
+
op.create_index(op.f('ix_leads_linkedin_urn'), 'leads', ['linkedin_urn'], unique=False)
|
| 223 |
+
op.drop_constraint('leads_current_stage_id_fkey', 'leads', type_='foreignkey')
|
| 224 |
+
op.create_foreign_key(None, 'leads', 'sales_stages', ['current_stage_id'], ['id'])
|
| 225 |
+
op.drop_column('leads', 'crm_sync_status')
|
| 226 |
+
op.drop_column('leads', 'crm_id')
|
| 227 |
+
op.alter_column('messages', 'content',
|
| 228 |
+
existing_type=sa.TEXT(),
|
| 229 |
+
type_=sqlmodel.sql.sqltypes.AutoString(),
|
| 230 |
+
existing_nullable=False)
|
| 231 |
+
op.alter_column('messages', 'created_at',
|
| 232 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 233 |
+
type_=sa.DateTime(),
|
| 234 |
+
existing_nullable=False,
|
| 235 |
+
existing_server_default=sa.text('now()'))
|
| 236 |
+
op.alter_column('notification_settings', 'telegram_enabled',
|
| 237 |
+
existing_type=sa.BOOLEAN(),
|
| 238 |
+
nullable=False,
|
| 239 |
+
existing_server_default=sa.text('true'))
|
| 240 |
+
op.alter_column('notification_settings', 'dashboard_enabled',
|
| 241 |
+
existing_type=sa.BOOLEAN(),
|
| 242 |
+
nullable=False,
|
| 243 |
+
existing_server_default=sa.text('true'))
|
| 244 |
+
op.alter_column('notification_settings', 'email_enabled',
|
| 245 |
+
existing_type=sa.BOOLEAN(),
|
| 246 |
+
nullable=False,
|
| 247 |
+
existing_server_default=sa.text('false'))
|
| 248 |
+
op.alter_column('notification_settings', 'notify_hot_leads',
|
| 249 |
+
existing_type=sa.BOOLEAN(),
|
| 250 |
+
nullable=False,
|
| 251 |
+
existing_server_default=sa.text('true'))
|
| 252 |
+
op.alter_column('notification_settings', 'notify_inactive_leads',
|
| 253 |
+
existing_type=sa.BOOLEAN(),
|
| 254 |
+
nullable=False,
|
| 255 |
+
existing_server_default=sa.text('false'))
|
| 256 |
+
op.alter_column('notification_settings', 'notify_new_leads',
|
| 257 |
+
existing_type=sa.BOOLEAN(),
|
| 258 |
+
nullable=False,
|
| 259 |
+
existing_server_default=sa.text('false'))
|
| 260 |
+
op.alter_column('notification_settings', 'created_at',
|
| 261 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 262 |
+
nullable=False,
|
| 263 |
+
existing_server_default=sa.text('CURRENT_TIMESTAMP'))
|
| 264 |
+
op.alter_column('notification_settings', 'updated_at',
|
| 265 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 266 |
+
nullable=False,
|
| 267 |
+
existing_server_default=sa.text('CURRENT_TIMESTAMP'))
|
| 268 |
+
op.drop_index('idx_notification_settings_tenant_id', table_name='notification_settings')
|
| 269 |
+
op.drop_constraint('notification_settings_tenant_id_key', 'notification_settings', type_='unique')
|
| 270 |
+
op.create_index(op.f('ix_notification_settings_tenant_id'), 'notification_settings', ['tenant_id'], unique=True)
|
| 271 |
+
op.drop_constraint('notification_settings_tenant_id_fkey', 'notification_settings', type_='foreignkey')
|
| 272 |
+
op.create_foreign_key(None, 'notification_settings', 'tenants', ['tenant_id'], ['id'])
|
| 273 |
+
op.alter_column('notifications', 'message',
|
| 274 |
+
existing_type=sa.TEXT(),
|
| 275 |
+
type_=sqlmodel.sql.sqltypes.AutoString(),
|
| 276 |
+
existing_nullable=False)
|
| 277 |
+
op.alter_column('notifications', 'is_read',
|
| 278 |
+
existing_type=sa.BOOLEAN(),
|
| 279 |
+
nullable=False,
|
| 280 |
+
existing_server_default=sa.text('false'))
|
| 281 |
+
op.alter_column('notifications', 'sent_telegram',
|
| 282 |
+
existing_type=sa.BOOLEAN(),
|
| 283 |
+
nullable=False,
|
| 284 |
+
existing_server_default=sa.text('false'))
|
| 285 |
+
op.alter_column('notifications', 'sent_dashboard',
|
| 286 |
+
existing_type=sa.BOOLEAN(),
|
| 287 |
+
nullable=False,
|
| 288 |
+
existing_server_default=sa.text('true'))
|
| 289 |
+
op.alter_column('notifications', 'created_at',
|
| 290 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 291 |
+
nullable=False,
|
| 292 |
+
existing_server_default=sa.text('CURRENT_TIMESTAMP'))
|
| 293 |
+
op.drop_index('idx_notifications_created_at', table_name='notifications')
|
| 294 |
+
op.drop_index('idx_notifications_is_read', table_name='notifications')
|
| 295 |
+
op.drop_index('idx_notifications_tenant_id', table_name='notifications')
|
| 296 |
+
op.drop_index('idx_notifications_type', table_name='notifications')
|
| 297 |
+
op.create_index(op.f('ix_notifications_created_at'), 'notifications', ['created_at'], unique=False)
|
| 298 |
+
op.create_index(op.f('ix_notifications_is_read'), 'notifications', ['is_read'], unique=False)
|
| 299 |
+
op.create_index(op.f('ix_notifications_tenant_id'), 'notifications', ['tenant_id'], unique=False)
|
| 300 |
+
op.create_index(op.f('ix_notifications_type'), 'notifications', ['type'], unique=False)
|
| 301 |
+
op.drop_constraint('notifications_lead_id_fkey', 'notifications', type_='foreignkey')
|
| 302 |
+
op.drop_constraint('notifications_tenant_id_fkey', 'notifications', type_='foreignkey')
|
| 303 |
+
op.create_foreign_key(None, 'notifications', 'leads', ['lead_id'], ['id'])
|
| 304 |
+
op.create_foreign_key(None, 'notifications', 'tenants', ['tenant_id'], ['id'])
|
| 305 |
+
op.create_foreign_key(None, 'partner_earnings', 'partners', ['partner_id'], ['id'])
|
| 306 |
+
op.alter_column('partners', 'status',
|
| 307 |
+
existing_type=postgresql.ENUM('PENDING', 'ACTIVE', 'BANNED', name='partner_status'),
|
| 308 |
+
type_=sa.Enum('PENDING', 'ACTIVE', 'BANNED', name='partnerstatus'),
|
| 309 |
+
nullable=False,
|
| 310 |
+
comment=None,
|
| 311 |
+
existing_comment='Partner franchise status: PENDING (not paid), ACTIVE (paid $500), BANNED (suspended)',
|
| 312 |
+
existing_server_default=sa.text("'PENDING'::partner_status"))
|
| 313 |
+
op.drop_index('idx_partners_status', table_name='partners')
|
| 314 |
+
op.alter_column('products', 'description',
|
| 315 |
+
existing_type=sa.TEXT(),
|
| 316 |
+
type_=sqlmodel.sql.sqltypes.AutoString(),
|
| 317 |
+
existing_nullable=True)
|
| 318 |
+
op.alter_column('products', 'price',
|
| 319 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 320 |
+
nullable=False,
|
| 321 |
+
existing_server_default=sa.text('0.0'))
|
| 322 |
+
op.alter_column('products', 'currency',
|
| 323 |
+
existing_type=sa.VARCHAR(),
|
| 324 |
+
nullable=False,
|
| 325 |
+
existing_server_default=sa.text("'USD'::character varying"))
|
| 326 |
+
op.alter_column('products', 'in_stock',
|
| 327 |
+
existing_type=sa.BOOLEAN(),
|
| 328 |
+
nullable=False,
|
| 329 |
+
existing_server_default=sa.text('true'))
|
| 330 |
+
op.alter_column('products', 'is_active',
|
| 331 |
+
existing_type=sa.BOOLEAN(),
|
| 332 |
+
nullable=False,
|
| 333 |
+
existing_server_default=sa.text('true'))
|
| 334 |
+
op.alter_column('products', 'created_at',
|
| 335 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 336 |
+
nullable=False,
|
| 337 |
+
existing_server_default=sa.text("(now() AT TIME ZONE 'utc'::text)"))
|
| 338 |
+
op.alter_column('products', 'updated_at',
|
| 339 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 340 |
+
nullable=False,
|
| 341 |
+
existing_server_default=sa.text("(now() AT TIME ZONE 'utc'::text)"))
|
| 342 |
+
op.drop_index('idx_products_category', table_name='products')
|
| 343 |
+
op.drop_index('idx_products_name', table_name='products')
|
| 344 |
+
op.drop_index('idx_products_sku', table_name='products')
|
| 345 |
+
op.drop_index('idx_products_tenant_id', table_name='products')
|
| 346 |
+
op.drop_constraint('products_tenant_id_fkey', 'products', type_='foreignkey')
|
| 347 |
+
op.create_foreign_key(None, 'products', 'tenants', ['tenant_id'], ['id'])
|
| 348 |
+
op.alter_column('sales_scripts', 'created_at',
|
| 349 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 350 |
+
type_=sa.DateTime(),
|
| 351 |
+
existing_nullable=False,
|
| 352 |
+
existing_server_default=sa.text('now()'))
|
| 353 |
+
op.alter_column('sales_scripts', 'updated_at',
|
| 354 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 355 |
+
type_=sa.DateTime(),
|
| 356 |
+
existing_nullable=False,
|
| 357 |
+
existing_server_default=sa.text('now()'))
|
| 358 |
+
op.add_column('tenants', sa.Column('stripe_customer_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True))
|
| 359 |
+
op.add_column('tenants', sa.Column('stripe_subscription_id', sqlmodel.sql.sqltypes.AutoString(), nullable=True))
|
| 360 |
+
op.add_column('tenants', sa.Column('meta_wa_config', sa.JSON(), nullable=True))
|
| 361 |
+
op.add_column('tenants', sa.Column('meta_ig_config', sa.JSON(), nullable=True))
|
| 362 |
+
op.add_column('tenants', sa.Column('google_calendar_config', sa.JSON(), nullable=True))
|
| 363 |
+
op.alter_column('tenants', 'name',
|
| 364 |
+
existing_type=sa.TEXT(),
|
| 365 |
+
type_=sqlmodel.sql.sqltypes.AutoString(),
|
| 366 |
+
existing_nullable=False)
|
| 367 |
+
op.alter_column('tenants', 'subscription_plan',
|
| 368 |
+
existing_type=sa.VARCHAR(),
|
| 369 |
+
type_=sa.Enum('TRIAL', 'START', 'GROWTH', 'UNLIMITED', name='subscriptionplan'),
|
| 370 |
+
existing_nullable=False,
|
| 371 |
+
existing_server_default=sa.text("'start'::character varying"))
|
| 372 |
+
op.alter_column('tenants', 'subscription_status',
|
| 373 |
+
existing_type=sa.VARCHAR(length=20),
|
| 374 |
+
nullable=False,
|
| 375 |
+
existing_server_default=sa.text("'trial'::character varying"))
|
| 376 |
+
op.alter_column('tenants', 'subscription_start',
|
| 377 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 378 |
+
type_=sa.DateTime(),
|
| 379 |
+
existing_nullable=False,
|
| 380 |
+
existing_server_default=sa.text('now()'))
|
| 381 |
+
op.alter_column('tenants', 'subscription_end',
|
| 382 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 383 |
+
type_=sa.DateTime(),
|
| 384 |
+
existing_nullable=True)
|
| 385 |
+
op.alter_column('tenants', 'leads_this_month',
|
| 386 |
+
existing_type=sa.INTEGER(),
|
| 387 |
+
nullable=False,
|
| 388 |
+
existing_server_default=sa.text('0'))
|
| 389 |
+
op.alter_column('tenants', 'overage_charges',
|
| 390 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 391 |
+
nullable=False,
|
| 392 |
+
existing_server_default=sa.text('0.0'))
|
| 393 |
+
op.alter_column('tenants', 'business_name',
|
| 394 |
+
existing_type=sa.TEXT(),
|
| 395 |
+
type_=sqlmodel.sql.sqltypes.AutoString(),
|
| 396 |
+
existing_nullable=False)
|
| 397 |
+
op.alter_column('tenants', 'business_type',
|
| 398 |
+
existing_type=sa.VARCHAR(length=50),
|
| 399 |
+
nullable=False,
|
| 400 |
+
existing_server_default=sa.text("'hybrid'::character varying"))
|
| 401 |
+
op.alter_column('tenants', 'whatsapp_config',
|
| 402 |
+
existing_type=postgresql.JSONB(astext_type=sa.Text()),
|
| 403 |
+
type_=sa.JSON(),
|
| 404 |
+
comment=None,
|
| 405 |
+
existing_comment='WhatsApp Business API configuration: { access_token, phone_number_id, verify_token }',
|
| 406 |
+
existing_nullable=True)
|
| 407 |
+
op.alter_column('tenants', 'ai_settings',
|
| 408 |
+
existing_type=postgresql.JSONB(astext_type=sa.Text()),
|
| 409 |
+
type_=sa.JSON(),
|
| 410 |
+
comment=None,
|
| 411 |
+
existing_comment='AI Brain configuration: business description, selling style, custom qualification fields, and ideal customer profile',
|
| 412 |
+
existing_nullable=True,
|
| 413 |
+
existing_server_default=sa.text('\'{"custom_fields": ["Бюджет", "Срочность", "Статус решения"], "selling_style": "Consultative", "business_description": "Мы продаем услуги и товары", "ideal_customer_profile": "Целевой клиент с реальной потребностью"}\'::jsonb'))
|
| 414 |
+
op.alter_column('tenants', 'tone_of_voice',
|
| 415 |
+
existing_type=sa.VARCHAR(length=50),
|
| 416 |
+
comment=None,
|
| 417 |
+
existing_comment='AI communication tone: Professional, Friendly, Empathetic, Bold',
|
| 418 |
+
existing_nullable=True,
|
| 419 |
+
existing_server_default=sa.text("'Professional'::character varying"))
|
| 420 |
+
op.alter_column('tenants', 'sales_methodology',
|
| 421 |
+
existing_type=sa.VARCHAR(length=50),
|
| 422 |
+
comment=None,
|
| 423 |
+
existing_comment='Sales framework: SPIN, Sandler, Challenger, Consultative, MEDDIC',
|
| 424 |
+
existing_nullable=True,
|
| 425 |
+
existing_server_default=sa.text("'Consultative'::character varying"))
|
| 426 |
+
op.alter_column('tenants', 'custom_instructions',
|
| 427 |
+
existing_type=sa.TEXT(),
|
| 428 |
+
type_=sqlmodel.sql.sqltypes.AutoString(),
|
| 429 |
+
comment=None,
|
| 430 |
+
existing_comment='User-defined global rules for AI behavior',
|
| 431 |
+
existing_nullable=True,
|
| 432 |
+
existing_server_default=sa.text("''::text"))
|
| 433 |
+
op.alter_column('tenants', 'banned_words',
|
| 434 |
+
existing_type=postgresql.JSONB(astext_type=sa.Text()),
|
| 435 |
+
type_=sa.JSON(),
|
| 436 |
+
comment=None,
|
| 437 |
+
existing_comment='Array of words/phrases AI must avoid',
|
| 438 |
+
existing_nullable=True,
|
| 439 |
+
existing_server_default=sa.text("'[]'::jsonb"))
|
| 440 |
+
op.alter_column('tenants', 'booking_settings',
|
| 441 |
+
existing_type=postgresql.JSONB(astext_type=sa.Text()),
|
| 442 |
+
type_=sa.JSON(),
|
| 443 |
+
existing_nullable=True)
|
| 444 |
+
op.alter_column('tenants', 'created_at',
|
| 445 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 446 |
+
type_=sa.DateTime(),
|
| 447 |
+
existing_nullable=False,
|
| 448 |
+
existing_server_default=sa.text('now()'))
|
| 449 |
+
op.alter_column('tenants', 'updated_at',
|
| 450 |
+
existing_type=postgresql.TIMESTAMP(timezone=True),
|
| 451 |
+
type_=sa.DateTime(),
|
| 452 |
+
existing_nullable=False,
|
| 453 |
+
existing_server_default=sa.text('now()'))
|
| 454 |
+
op.drop_index('idx_tenants_ai_settings', table_name='tenants', postgresql_using='gin')
|
| 455 |
+
op.drop_index('idx_tenants_banned_words', table_name='tenants', postgresql_using='gin')
|
| 456 |
+
op.drop_index('idx_tenants_methodology', table_name='tenants')
|
| 457 |
+
op.drop_index('idx_tenants_next_billing', table_name='tenants', postgresql_where="((subscription_status)::text = 'active'::text)")
|
| 458 |
+
op.drop_index('idx_tenants_subscription_status', table_name='tenants')
|
| 459 |
+
op.drop_index('idx_tenants_tone', table_name='tenants')
|
| 460 |
+
op.drop_index('idx_tenants_whatsapp_config', table_name='tenants', postgresql_using='gin')
|
| 461 |
+
op.create_index(op.f('ix_tenants_name'), 'tenants', ['name'], unique=False)
|
| 462 |
+
op.create_index(op.f('ix_tenants_stripe_customer_id'), 'tenants', ['stripe_customer_id'], unique=False)
|
| 463 |
+
op.create_foreign_key(None, 'tenants', 'partners', ['partner_ref_id'], ['id'])
|
| 464 |
+
op.drop_column('tenants', 'crm_config')
|
| 465 |
+
op.drop_column('tenants', 'telegram_webhook_secret')
|
| 466 |
+
# ### end Alembic commands ###
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def downgrade() -> None:
|
| 470 |
+
# ### commands auto generated by Alembic - please adjust! ###
|
| 471 |
+
op.add_column('tenants', sa.Column('telegram_webhook_secret', sa.VARCHAR(), autoincrement=False, nullable=True))
|
| 472 |
+
op.add_column('tenants', sa.Column('crm_config', postgresql.JSONB(astext_type=sa.Text()), autoincrement=False, nullable=True))
|
| 473 |
+
op.drop_constraint(None, 'tenants', type_='foreignkey')
|
| 474 |
+
op.drop_index(op.f('ix_tenants_stripe_customer_id'), table_name='tenants')
|
| 475 |
+
op.drop_index(op.f('ix_tenants_name'), table_name='tenants')
|
| 476 |
+
op.create_index('idx_tenants_whatsapp_config', 'tenants', ['whatsapp_config'], unique=False, postgresql_using='gin')
|
| 477 |
+
op.create_index('idx_tenants_tone', 'tenants', ['tone_of_voice'], unique=False)
|
| 478 |
+
op.create_index('idx_tenants_subscription_status', 'tenants', ['subscription_status'], unique=False)
|
| 479 |
+
op.create_index('idx_tenants_next_billing', 'tenants', ['next_billing_date'], unique=False, postgresql_where="((subscription_status)::text = 'active'::text)")
|
| 480 |
+
op.create_index('idx_tenants_methodology', 'tenants', ['sales_methodology'], unique=False)
|
| 481 |
+
op.create_index('idx_tenants_banned_words', 'tenants', ['banned_words'], unique=False, postgresql_using='gin')
|
| 482 |
+
op.create_index('idx_tenants_ai_settings', 'tenants', ['ai_settings'], unique=False, postgresql_using='gin')
|
| 483 |
+
op.alter_column('tenants', 'updated_at',
|
| 484 |
+
existing_type=sa.DateTime(),
|
| 485 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 486 |
+
existing_nullable=False,
|
| 487 |
+
existing_server_default=sa.text('now()'))
|
| 488 |
+
op.alter_column('tenants', 'created_at',
|
| 489 |
+
existing_type=sa.DateTime(),
|
| 490 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 491 |
+
existing_nullable=False,
|
| 492 |
+
existing_server_default=sa.text('now()'))
|
| 493 |
+
op.alter_column('tenants', 'booking_settings',
|
| 494 |
+
existing_type=sa.JSON(),
|
| 495 |
+
type_=postgresql.JSONB(astext_type=sa.Text()),
|
| 496 |
+
existing_nullable=True)
|
| 497 |
+
op.alter_column('tenants', 'banned_words',
|
| 498 |
+
existing_type=sa.JSON(),
|
| 499 |
+
type_=postgresql.JSONB(astext_type=sa.Text()),
|
| 500 |
+
comment='Array of words/phrases AI must avoid',
|
| 501 |
+
existing_nullable=True,
|
| 502 |
+
existing_server_default=sa.text("'[]'::jsonb"))
|
| 503 |
+
op.alter_column('tenants', 'custom_instructions',
|
| 504 |
+
existing_type=sqlmodel.sql.sqltypes.AutoString(),
|
| 505 |
+
type_=sa.TEXT(),
|
| 506 |
+
comment='User-defined global rules for AI behavior',
|
| 507 |
+
existing_nullable=True,
|
| 508 |
+
existing_server_default=sa.text("''::text"))
|
| 509 |
+
op.alter_column('tenants', 'sales_methodology',
|
| 510 |
+
existing_type=sa.VARCHAR(length=50),
|
| 511 |
+
comment='Sales framework: SPIN, Sandler, Challenger, Consultative, MEDDIC',
|
| 512 |
+
existing_nullable=True,
|
| 513 |
+
existing_server_default=sa.text("'Consultative'::character varying"))
|
| 514 |
+
op.alter_column('tenants', 'tone_of_voice',
|
| 515 |
+
existing_type=sa.VARCHAR(length=50),
|
| 516 |
+
comment='AI communication tone: Professional, Friendly, Empathetic, Bold',
|
| 517 |
+
existing_nullable=True,
|
| 518 |
+
existing_server_default=sa.text("'Professional'::character varying"))
|
| 519 |
+
op.alter_column('tenants', 'ai_settings',
|
| 520 |
+
existing_type=sa.JSON(),
|
| 521 |
+
type_=postgresql.JSONB(astext_type=sa.Text()),
|
| 522 |
+
comment='AI Brain configuration: business description, selling style, custom qualification fields, and ideal customer profile',
|
| 523 |
+
existing_nullable=True,
|
| 524 |
+
existing_server_default=sa.text('\'{"custom_fields": ["Бюджет", "Срочность", "Статус решения"], "selling_style": "Consultative", "business_description": "Мы продаем услуги и товары", "ideal_customer_profile": "Целевой клиент с реальной потребностью"}\'::jsonb'))
|
| 525 |
+
op.alter_column('tenants', 'whatsapp_config',
|
| 526 |
+
existing_type=sa.JSON(),
|
| 527 |
+
type_=postgresql.JSONB(astext_type=sa.Text()),
|
| 528 |
+
comment='WhatsApp Business API configuration: { access_token, phone_number_id, verify_token }',
|
| 529 |
+
existing_nullable=True)
|
| 530 |
+
op.alter_column('tenants', 'business_type',
|
| 531 |
+
existing_type=sa.VARCHAR(length=50),
|
| 532 |
+
nullable=True,
|
| 533 |
+
existing_server_default=sa.text("'hybrid'::character varying"))
|
| 534 |
+
op.alter_column('tenants', 'business_name',
|
| 535 |
+
existing_type=sqlmodel.sql.sqltypes.AutoString(),
|
| 536 |
+
type_=sa.TEXT(),
|
| 537 |
+
existing_nullable=False)
|
| 538 |
+
op.alter_column('tenants', 'overage_charges',
|
| 539 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 540 |
+
nullable=True,
|
| 541 |
+
existing_server_default=sa.text('0.0'))
|
| 542 |
+
op.alter_column('tenants', 'leads_this_month',
|
| 543 |
+
existing_type=sa.INTEGER(),
|
| 544 |
+
nullable=True,
|
| 545 |
+
existing_server_default=sa.text('0'))
|
| 546 |
+
op.alter_column('tenants', 'subscription_end',
|
| 547 |
+
existing_type=sa.DateTime(),
|
| 548 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 549 |
+
existing_nullable=True)
|
| 550 |
+
op.alter_column('tenants', 'subscription_start',
|
| 551 |
+
existing_type=sa.DateTime(),
|
| 552 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 553 |
+
existing_nullable=False,
|
| 554 |
+
existing_server_default=sa.text('now()'))
|
| 555 |
+
op.alter_column('tenants', 'subscription_status',
|
| 556 |
+
existing_type=sa.VARCHAR(length=20),
|
| 557 |
+
nullable=True,
|
| 558 |
+
existing_server_default=sa.text("'trial'::character varying"))
|
| 559 |
+
op.alter_column('tenants', 'subscription_plan',
|
| 560 |
+
existing_type=sa.Enum('TRIAL', 'START', 'GROWTH', 'UNLIMITED', name='subscriptionplan'),
|
| 561 |
+
type_=sa.VARCHAR(),
|
| 562 |
+
existing_nullable=False,
|
| 563 |
+
existing_server_default=sa.text("'start'::character varying"))
|
| 564 |
+
op.alter_column('tenants', 'name',
|
| 565 |
+
existing_type=sqlmodel.sql.sqltypes.AutoString(),
|
| 566 |
+
type_=sa.TEXT(),
|
| 567 |
+
existing_nullable=False)
|
| 568 |
+
op.drop_column('tenants', 'google_calendar_config')
|
| 569 |
+
op.drop_column('tenants', 'meta_ig_config')
|
| 570 |
+
op.drop_column('tenants', 'meta_wa_config')
|
| 571 |
+
op.drop_column('tenants', 'stripe_subscription_id')
|
| 572 |
+
op.drop_column('tenants', 'stripe_customer_id')
|
| 573 |
+
op.alter_column('sales_scripts', 'updated_at',
|
| 574 |
+
existing_type=sa.DateTime(),
|
| 575 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 576 |
+
existing_nullable=False,
|
| 577 |
+
existing_server_default=sa.text('now()'))
|
| 578 |
+
op.alter_column('sales_scripts', 'created_at',
|
| 579 |
+
existing_type=sa.DateTime(),
|
| 580 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 581 |
+
existing_nullable=False,
|
| 582 |
+
existing_server_default=sa.text('now()'))
|
| 583 |
+
op.drop_constraint(None, 'products', type_='foreignkey')
|
| 584 |
+
op.create_foreign_key('products_tenant_id_fkey', 'products', 'tenants', ['tenant_id'], ['id'], ondelete='CASCADE')
|
| 585 |
+
op.create_index('idx_products_tenant_id', 'products', ['tenant_id'], unique=False)
|
| 586 |
+
op.create_index('idx_products_sku', 'products', ['sku'], unique=False)
|
| 587 |
+
op.create_index('idx_products_name', 'products', ['name'], unique=False)
|
| 588 |
+
op.create_index('idx_products_category', 'products', ['category'], unique=False)
|
| 589 |
+
op.alter_column('products', 'updated_at',
|
| 590 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 591 |
+
nullable=True,
|
| 592 |
+
existing_server_default=sa.text("(now() AT TIME ZONE 'utc'::text)"))
|
| 593 |
+
op.alter_column('products', 'created_at',
|
| 594 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 595 |
+
nullable=True,
|
| 596 |
+
existing_server_default=sa.text("(now() AT TIME ZONE 'utc'::text)"))
|
| 597 |
+
op.alter_column('products', 'is_active',
|
| 598 |
+
existing_type=sa.BOOLEAN(),
|
| 599 |
+
nullable=True,
|
| 600 |
+
existing_server_default=sa.text('true'))
|
| 601 |
+
op.alter_column('products', 'in_stock',
|
| 602 |
+
existing_type=sa.BOOLEAN(),
|
| 603 |
+
nullable=True,
|
| 604 |
+
existing_server_default=sa.text('true'))
|
| 605 |
+
op.alter_column('products', 'currency',
|
| 606 |
+
existing_type=sa.VARCHAR(),
|
| 607 |
+
nullable=True,
|
| 608 |
+
existing_server_default=sa.text("'USD'::character varying"))
|
| 609 |
+
op.alter_column('products', 'price',
|
| 610 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 611 |
+
nullable=True,
|
| 612 |
+
existing_server_default=sa.text('0.0'))
|
| 613 |
+
op.alter_column('products', 'description',
|
| 614 |
+
existing_type=sqlmodel.sql.sqltypes.AutoString(),
|
| 615 |
+
type_=sa.TEXT(),
|
| 616 |
+
existing_nullable=True)
|
| 617 |
+
op.create_index('idx_partners_status', 'partners', ['status'], unique=False)
|
| 618 |
+
op.alter_column('partners', 'status',
|
| 619 |
+
existing_type=sa.Enum('PENDING', 'ACTIVE', 'BANNED', name='partnerstatus'),
|
| 620 |
+
type_=postgresql.ENUM('PENDING', 'ACTIVE', 'BANNED', name='partner_status'),
|
| 621 |
+
nullable=True,
|
| 622 |
+
comment='Partner franchise status: PENDING (not paid), ACTIVE (paid $500), BANNED (suspended)',
|
| 623 |
+
existing_server_default=sa.text("'PENDING'::partner_status"))
|
| 624 |
+
op.drop_constraint(None, 'partner_earnings', type_='foreignkey')
|
| 625 |
+
op.drop_constraint(None, 'notifications', type_='foreignkey')
|
| 626 |
+
op.drop_constraint(None, 'notifications', type_='foreignkey')
|
| 627 |
+
op.create_foreign_key('notifications_tenant_id_fkey', 'notifications', 'tenants', ['tenant_id'], ['id'], ondelete='CASCADE')
|
| 628 |
+
op.create_foreign_key('notifications_lead_id_fkey', 'notifications', 'leads', ['lead_id'], ['id'], ondelete='CASCADE')
|
| 629 |
+
op.drop_index(op.f('ix_notifications_type'), table_name='notifications')
|
| 630 |
+
op.drop_index(op.f('ix_notifications_tenant_id'), table_name='notifications')
|
| 631 |
+
op.drop_index(op.f('ix_notifications_is_read'), table_name='notifications')
|
| 632 |
+
op.drop_index(op.f('ix_notifications_created_at'), table_name='notifications')
|
| 633 |
+
op.create_index('idx_notifications_type', 'notifications', ['type'], unique=False)
|
| 634 |
+
op.create_index('idx_notifications_tenant_id', 'notifications', ['tenant_id'], unique=False)
|
| 635 |
+
op.create_index('idx_notifications_is_read', 'notifications', ['is_read'], unique=False)
|
| 636 |
+
op.create_index('idx_notifications_created_at', 'notifications', [sa.text('created_at DESC')], unique=False)
|
| 637 |
+
op.alter_column('notifications', 'created_at',
|
| 638 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 639 |
+
nullable=True,
|
| 640 |
+
existing_server_default=sa.text('CURRENT_TIMESTAMP'))
|
| 641 |
+
op.alter_column('notifications', 'sent_dashboard',
|
| 642 |
+
existing_type=sa.BOOLEAN(),
|
| 643 |
+
nullable=True,
|
| 644 |
+
existing_server_default=sa.text('true'))
|
| 645 |
+
op.alter_column('notifications', 'sent_telegram',
|
| 646 |
+
existing_type=sa.BOOLEAN(),
|
| 647 |
+
nullable=True,
|
| 648 |
+
existing_server_default=sa.text('false'))
|
| 649 |
+
op.alter_column('notifications', 'is_read',
|
| 650 |
+
existing_type=sa.BOOLEAN(),
|
| 651 |
+
nullable=True,
|
| 652 |
+
existing_server_default=sa.text('false'))
|
| 653 |
+
op.alter_column('notifications', 'message',
|
| 654 |
+
existing_type=sqlmodel.sql.sqltypes.AutoString(),
|
| 655 |
+
type_=sa.TEXT(),
|
| 656 |
+
existing_nullable=False)
|
| 657 |
+
op.drop_constraint(None, 'notification_settings', type_='foreignkey')
|
| 658 |
+
op.create_foreign_key('notification_settings_tenant_id_fkey', 'notification_settings', 'tenants', ['tenant_id'], ['id'], ondelete='CASCADE')
|
| 659 |
+
op.drop_index(op.f('ix_notification_settings_tenant_id'), table_name='notification_settings')
|
| 660 |
+
op.create_unique_constraint('notification_settings_tenant_id_key', 'notification_settings', ['tenant_id'], postgresql_nulls_not_distinct=False)
|
| 661 |
+
op.create_index('idx_notification_settings_tenant_id', 'notification_settings', ['tenant_id'], unique=False)
|
| 662 |
+
op.alter_column('notification_settings', 'updated_at',
|
| 663 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 664 |
+
nullable=True,
|
| 665 |
+
existing_server_default=sa.text('CURRENT_TIMESTAMP'))
|
| 666 |
+
op.alter_column('notification_settings', 'created_at',
|
| 667 |
+
existing_type=postgresql.TIMESTAMP(),
|
| 668 |
+
nullable=True,
|
| 669 |
+
existing_server_default=sa.text('CURRENT_TIMESTAMP'))
|
| 670 |
+
op.alter_column('notification_settings', 'notify_new_leads',
|
| 671 |
+
existing_type=sa.BOOLEAN(),
|
| 672 |
+
nullable=True,
|
| 673 |
+
existing_server_default=sa.text('false'))
|
| 674 |
+
op.alter_column('notification_settings', 'notify_inactive_leads',
|
| 675 |
+
existing_type=sa.BOOLEAN(),
|
| 676 |
+
nullable=True,
|
| 677 |
+
existing_server_default=sa.text('false'))
|
| 678 |
+
op.alter_column('notification_settings', 'notify_hot_leads',
|
| 679 |
+
existing_type=sa.BOOLEAN(),
|
| 680 |
+
nullable=True,
|
| 681 |
+
existing_server_default=sa.text('true'))
|
| 682 |
+
op.alter_column('notification_settings', 'email_enabled',
|
| 683 |
+
existing_type=sa.BOOLEAN(),
|
| 684 |
+
nullable=True,
|
| 685 |
+
existing_server_default=sa.text('false'))
|
| 686 |
+
op.alter_column('notification_settings', 'dashboard_enabled',
|
| 687 |
+
existing_type=sa.BOOLEAN(),
|
| 688 |
+
nullable=True,
|
| 689 |
+
existing_server_default=sa.text('true'))
|
| 690 |
+
op.alter_column('notification_settings', 'telegram_enabled',
|
| 691 |
+
existing_type=sa.BOOLEAN(),
|
| 692 |
+
nullable=True,
|
| 693 |
+
existing_server_default=sa.text('true'))
|
| 694 |
+
op.alter_column('messages', 'created_at',
|
| 695 |
+
existing_type=sa.DateTime(),
|
| 696 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 697 |
+
existing_nullable=False,
|
| 698 |
+
existing_server_default=sa.text('now()'))
|
| 699 |
+
op.alter_column('messages', 'content',
|
| 700 |
+
existing_type=sqlmodel.sql.sqltypes.AutoString(),
|
| 701 |
+
type_=sa.TEXT(),
|
| 702 |
+
existing_nullable=False)
|
| 703 |
+
op.add_column('leads', sa.Column('crm_id', sa.VARCHAR(length=255), server_default=sa.text('NULL::character varying'), autoincrement=False, nullable=True))
|
| 704 |
+
op.add_column('leads', sa.Column('crm_sync_status', sa.VARCHAR(length=20), server_default=sa.text('NULL::character varying'), autoincrement=False, nullable=True))
|
| 705 |
+
op.drop_constraint(None, 'leads', type_='foreignkey')
|
| 706 |
+
op.create_foreign_key('leads_current_stage_id_fkey', 'leads', 'sales_stages', ['current_stage_id'], ['id'], ondelete='SET NULL')
|
| 707 |
+
op.drop_index(op.f('ix_leads_linkedin_urn'), table_name='leads')
|
| 708 |
+
op.create_index('ix_leads_qualified_at', 'leads', ['qualified_at'], unique=False)
|
| 709 |
+
op.create_index('ix_leads_ever_qualified', 'leads', ['ever_qualified'], unique=False)
|
| 710 |
+
op.create_index('idx_leads_processing_status', 'leads', ['processing_status'], unique=False)
|
| 711 |
+
op.create_index('idx_leads_current_stage', 'leads', ['current_stage_id'], unique=False)
|
| 712 |
+
op.create_index('idx_leads_crm_sync', 'leads', ['crm_sync_status'], unique=False, postgresql_where='(crm_sync_status IS NOT NULL)')
|
| 713 |
+
op.create_index('idx_leads_crm_id', 'leads', ['crm_id'], unique=False, postgresql_where='(crm_id IS NOT NULL)')
|
| 714 |
+
op.alter_column('leads', 'updated_at',
|
| 715 |
+
existing_type=sa.DateTime(),
|
| 716 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 717 |
+
existing_nullable=False,
|
| 718 |
+
existing_server_default=sa.text('now()'))
|
| 719 |
+
op.alter_column('leads', 'created_at',
|
| 720 |
+
existing_type=sa.DateTime(),
|
| 721 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 722 |
+
existing_nullable=False,
|
| 723 |
+
existing_server_default=sa.text('now()'))
|
| 724 |
+
op.alter_column('leads', 'assigned_at',
|
| 725 |
+
existing_type=sa.DateTime(),
|
| 726 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 727 |
+
existing_nullable=True)
|
| 728 |
+
op.alter_column('leads', 'last_activity_at',
|
| 729 |
+
existing_type=sa.DateTime(),
|
| 730 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 731 |
+
existing_nullable=False,
|
| 732 |
+
existing_server_default=sa.text('now()'))
|
| 733 |
+
op.alter_column('leads', 'last_message_at',
|
| 734 |
+
existing_type=sa.DateTime(),
|
| 735 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 736 |
+
existing_nullable=False,
|
| 737 |
+
existing_server_default=sa.text('now()'))
|
| 738 |
+
op.alter_column('leads', 'first_message_at',
|
| 739 |
+
existing_type=sa.DateTime(),
|
| 740 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 741 |
+
existing_nullable=False,
|
| 742 |
+
existing_server_default=sa.text('now()'))
|
| 743 |
+
op.alter_column('leads', 'current_stage_id',
|
| 744 |
+
existing_type=sa.UUID(),
|
| 745 |
+
comment='Current stage in the sales playbook workflow',
|
| 746 |
+
existing_nullable=True)
|
| 747 |
+
op.alter_column('leads', 'ai_summary_json',
|
| 748 |
+
existing_type=sa.JSON(),
|
| 749 |
+
type_=postgresql.JSONB(astext_type=sa.Text()),
|
| 750 |
+
nullable=False,
|
| 751 |
+
existing_server_default=sa.text("'{}'::jsonb"))
|
| 752 |
+
op.alter_column('leads', 'psychotype',
|
| 753 |
+
existing_type=sa.Enum('DOMINANT', 'INFLUENTIAL', 'STEADY', 'CONSCIENTIOUS', 'UNKNOWN', name='psychotype'),
|
| 754 |
+
type_=sa.VARCHAR(),
|
| 755 |
+
existing_nullable=False,
|
| 756 |
+
existing_server_default=sa.text("'unknown'::character varying"))
|
| 757 |
+
op.alter_column('leads', 'heat_level',
|
| 758 |
+
existing_type=sa.Enum('HOT', 'WARM', 'COLD', 'JUNK', name='leadheat'),
|
| 759 |
+
type_=sa.VARCHAR(),
|
| 760 |
+
existing_nullable=False,
|
| 761 |
+
existing_server_default=sa.text("'cold'::character varying"))
|
| 762 |
+
op.alter_column('leads', 'status',
|
| 763 |
+
existing_type=sa.Enum('NEW', 'QUALIFIED', 'IN_PROGRESS', 'CLOSED_WON', 'CLOSED_LOST', 'JUNK', name='leadstatus'),
|
| 764 |
+
type_=sa.VARCHAR(),
|
| 765 |
+
existing_nullable=False,
|
| 766 |
+
existing_server_default=sa.text("'new'::character varying"))
|
| 767 |
+
op.create_table_comment(
|
| 768 |
+
'lead_crm_links',
|
| 769 |
+
'Links between MicroFunnel leads and external CRM records',
|
| 770 |
+
existing_comment=None,
|
| 771 |
+
schema=None
|
| 772 |
+
)
|
| 773 |
+
op.create_index('idx_lead_crm_links_tenant', 'lead_crm_links', ['tenant_id'], unique=False)
|
| 774 |
+
op.create_index('idx_lead_crm_links_lead', 'lead_crm_links', ['lead_id'], unique=False)
|
| 775 |
+
op.create_index('idx_lead_crm_links_integration', 'lead_crm_links', ['integration_id'], unique=False)
|
| 776 |
+
op.create_index('idx_lead_crm_links_crm_lead', 'lead_crm_links', ['crm_lead_id'], unique=False)
|
| 777 |
+
op.create_index('idx_lead_crm_links_crm_contact', 'lead_crm_links', ['crm_contact_id'], unique=False)
|
| 778 |
+
op.alter_column('lead_crm_links', 'sync_hash',
|
| 779 |
+
existing_type=sa.VARCHAR(),
|
| 780 |
+
comment='MD5 hash of lead data to detect changes',
|
| 781 |
+
existing_nullable=True)
|
| 782 |
+
op.alter_column('knowledge_base', 'updated_at',
|
| 783 |
+
existing_type=sa.DateTime(),
|
| 784 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 785 |
+
existing_nullable=False,
|
| 786 |
+
existing_server_default=sa.text('now()'))
|
| 787 |
+
op.alter_column('knowledge_base', 'created_at',
|
| 788 |
+
existing_type=sa.DateTime(),
|
| 789 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 790 |
+
existing_nullable=False,
|
| 791 |
+
existing_server_default=sa.text('now()'))
|
| 792 |
+
op.create_table_comment(
|
| 793 |
+
'crm_sync_logs',
|
| 794 |
+
'Log of all CRM synchronization operations',
|
| 795 |
+
existing_comment=None,
|
| 796 |
+
schema=None
|
| 797 |
+
)
|
| 798 |
+
op.create_index('idx_crm_sync_logs_tenant', 'crm_sync_logs', ['tenant_id'], unique=False)
|
| 799 |
+
op.create_index('idx_crm_sync_logs_success', 'crm_sync_logs', ['success'], unique=False)
|
| 800 |
+
op.create_index('idx_crm_sync_logs_lead', 'crm_sync_logs', ['lead_id'], unique=False)
|
| 801 |
+
op.create_index('idx_crm_sync_logs_integration', 'crm_sync_logs', ['integration_id'], unique=False)
|
| 802 |
+
op.create_index('idx_crm_sync_logs_created', 'crm_sync_logs', [sa.text('created_at DESC')], unique=False)
|
| 803 |
+
op.alter_column('crm_sync_logs', 'duration_ms',
|
| 804 |
+
existing_type=sa.INTEGER(),
|
| 805 |
+
comment='API call duration in milliseconds',
|
| 806 |
+
existing_nullable=True)
|
| 807 |
+
op.create_table_comment(
|
| 808 |
+
'crm_integrations',
|
| 809 |
+
'CRM integration configurations for tenants',
|
| 810 |
+
existing_comment=None,
|
| 811 |
+
schema=None
|
| 812 |
+
)
|
| 813 |
+
op.create_index('idx_crm_integrations_type', 'crm_integrations', ['crm_type'], unique=False)
|
| 814 |
+
op.create_index('idx_crm_integrations_tenant', 'crm_integrations', ['tenant_id'], unique=False)
|
| 815 |
+
op.alter_column('crm_integrations', 'sync_only_hot_leads',
|
| 816 |
+
existing_type=sa.BOOLEAN(),
|
| 817 |
+
comment='Only sync leads with heat_score >= 70',
|
| 818 |
+
existing_nullable=False)
|
| 819 |
+
op.alter_column('crm_integrations', 'field_mapping',
|
| 820 |
+
existing_type=postgresql.JSON(astext_type=sa.Text()),
|
| 821 |
+
comment='JSON mapping: MicroFunnel field → CRM field',
|
| 822 |
+
existing_nullable=True)
|
| 823 |
+
op.alter_column('crm_integrations', 'auto_sync',
|
| 824 |
+
existing_type=sa.BOOLEAN(),
|
| 825 |
+
comment='Automatically sync on lead updates',
|
| 826 |
+
existing_nullable=False)
|
| 827 |
+
op.create_table_comment(
|
| 828 |
+
'crm_field_mappings',
|
| 829 |
+
'Field mapping templates for different CRM systems',
|
| 830 |
+
existing_comment=None,
|
| 831 |
+
schema=None
|
| 832 |
+
)
|
| 833 |
+
op.create_index('idx_crm_field_mappings_type', 'crm_field_mappings', ['crm_type'], unique=False)
|
| 834 |
+
op.create_index('idx_crm_field_mappings_default', 'crm_field_mappings', ['is_default'], unique=False, postgresql_where='(is_default = true)')
|
| 835 |
+
op.drop_index(op.f('ix_conversations_is_active'), table_name='conversations')
|
| 836 |
+
op.alter_column('conversations', 'ended_at',
|
| 837 |
+
existing_type=sa.DateTime(),
|
| 838 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 839 |
+
existing_nullable=True)
|
| 840 |
+
op.alter_column('conversations', 'started_at',
|
| 841 |
+
existing_type=sa.DateTime(),
|
| 842 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 843 |
+
existing_nullable=False,
|
| 844 |
+
existing_server_default=sa.text('now()'))
|
| 845 |
+
op.alter_column('conversations', 'taken_over_at',
|
| 846 |
+
existing_type=sa.DateTime(),
|
| 847 |
+
type_=postgresql.TIMESTAMP(timezone=True),
|
| 848 |
+
existing_nullable=True)
|
| 849 |
+
op.create_table_comment(
|
| 850 |
+
'ai_training_examples',
|
| 851 |
+
'Few-shot learning examples for personalized AI',
|
| 852 |
+
existing_comment=None,
|
| 853 |
+
schema=None
|
| 854 |
+
)
|
| 855 |
+
op.create_index('idx_ai_training_weight', 'ai_training_examples', [sa.text('weight DESC')], unique=False)
|
| 856 |
+
op.create_index('idx_ai_training_tenant', 'ai_training_examples', ['tenant_id'], unique=False)
|
| 857 |
+
op.create_index('idx_ai_training_status', 'ai_training_examples', ['status'], unique=False)
|
| 858 |
+
op.create_index('idx_ai_training_category', 'ai_training_examples', ['category'], unique=False)
|
| 859 |
+
op.create_index('idx_ai_training_active', 'ai_training_examples', ['is_active'], unique=False, postgresql_where='(is_active = true)')
|
| 860 |
+
op.alter_column('ai_training_examples', 'success_rate',
|
| 861 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 862 |
+
comment='Success rate when this example is used',
|
| 863 |
+
existing_nullable=False)
|
| 864 |
+
op.alter_column('ai_training_examples', 'weight',
|
| 865 |
+
existing_type=sa.DOUBLE_PRECISION(precision=53),
|
| 866 |
+
comment='Importance weight (0.0-2.0), higher = more important',
|
| 867 |
+
existing_nullable=False)
|
| 868 |
+
op.create_table_comment(
|
| 869 |
+
'ai_learning_rules',
|
| 870 |
+
'Custom learned rules from user feedback',
|
| 871 |
+
existing_comment=None,
|
| 872 |
+
schema=None
|
| 873 |
+
)
|
| 874 |
+
op.create_index('idx_ai_rules_tenant', 'ai_learning_rules', ['tenant_id'], unique=False)
|
| 875 |
+
op.create_index('idx_ai_rules_priority', 'ai_learning_rules', [sa.text('priority DESC')], unique=False)
|
| 876 |
+
op.create_index('idx_ai_rules_category', 'ai_learning_rules', ['apply_to_category'], unique=False)
|
| 877 |
+
op.create_index('idx_ai_rules_active', 'ai_learning_rules', ['is_active'], unique=False, postgresql_where='(is_active = true)')
|
| 878 |
+
op.alter_column('ai_learning_rules', 'priority',
|
| 879 |
+
existing_type=sa.INTEGER(),
|
| 880 |
+
comment='Priority 1-10, higher number = higher priority',
|
| 881 |
+
existing_nullable=False)
|
| 882 |
+
op.create_table_comment(
|
| 883 |
+
'ai_feedback',
|
| 884 |
+
'User feedback on AI responses for continuous learning',
|
| 885 |
+
existing_comment=None,
|
| 886 |
+
schema=None
|
| 887 |
+
)
|
| 888 |
+
op.create_index('idx_ai_feedback_type', 'ai_feedback', ['feedback_type'], unique=False)
|
| 889 |
+
op.create_index('idx_ai_feedback_tenant', 'ai_feedback', ['tenant_id'], unique=False)
|
| 890 |
+
op.create_index('idx_ai_feedback_status', 'ai_feedback', ['status'], unique=False)
|
| 891 |
+
op.create_index('idx_ai_feedback_created', 'ai_feedback', [sa.text('created_at DESC')], unique=False)
|
| 892 |
+
op.create_index('idx_ai_feedback_conversation', 'ai_feedback', ['conversation_id'], unique=False)
|
| 893 |
+
op.alter_column('ai_feedback', 'is_applied',
|
| 894 |
+
existing_type=sa.BOOLEAN(),
|
| 895 |
+
comment='Whether feedback was converted to training example',
|
| 896 |
+
existing_nullable=False)
|
| 897 |
+
op.alter_column('ai_feedback', 'feedback_type',
|
| 898 |
+
existing_type=postgresql.ENUM('POSITIVE', 'NEGATIVE', 'CORRECTION', 'INSTRUCTION', name='feedbacktype'),
|
| 899 |
+
comment='Type: positive, negative, correction, instruction',
|
| 900 |
+
existing_nullable=False)
|
| 901 |
+
op.create_table('system_announcements',
|
| 902 |
+
sa.Column('id', sa.UUID(), autoincrement=False, nullable=False),
|
| 903 |
+
sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=False),
|
| 904 |
+
sa.Column('message', sa.VARCHAR(), autoincrement=False, nullable=False),
|
| 905 |
+
sa.Column('type', sa.VARCHAR(), autoincrement=False, nullable=False),
|
| 906 |
+
sa.Column('is_active', sa.BOOLEAN(), autoincrement=False, nullable=False),
|
| 907 |
+
sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
|
| 908 |
+
sa.Column('expires_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),
|
| 909 |
+
sa.Column('created_by', sa.UUID(), autoincrement=False, nullable=True),
|
| 910 |
+
sa.PrimaryKeyConstraint('id', name='system_announcements_pkey')
|
| 911 |
+
)
|
| 912 |
+
# ### end Alembic commands ###
|
backend/app/api/billing.py
CHANGED
|
@@ -1,1008 +1,189 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 6 |
-
from sqlalchemy import select
|
| 7 |
-
from uuid import UUID
|
| 8 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
| 9 |
from pydantic import BaseModel
|
| 10 |
-
from typing import Optional
|
| 11 |
-
|
| 12 |
-
from app.core.database import get_async_session
|
| 13 |
-
from app.core.logging import get_logger
|
| 14 |
-
from app.models.partner import Partner, PartnerStatus, PartnerEarning
|
| 15 |
-
from app.models.tenant import Tenant, SubscriptionPlan
|
| 16 |
-
from app.models.user import User
|
| 17 |
-
from app.api.deps import get_current_user
|
| 18 |
-
|
| 19 |
-
logger = get_logger(__name__)
|
| 20 |
-
|
| 21 |
|
| 22 |
router = APIRouter(prefix="/billing", tags=["Billing"])
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
class SubscriptionUpgradeResponse(BaseModel):
|
| 39 |
-
"""Response after subscription upgrade."""
|
| 40 |
-
success: bool
|
| 41 |
-
message: str
|
| 42 |
-
plan: str
|
| 43 |
-
amount_paid: float
|
| 44 |
-
partner_commission: float
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
class TrialConversionRequest(BaseModel):
|
| 48 |
-
"""Request to convert trial to paid."""
|
| 49 |
-
plan_id: str # "START", "GROWTH", "SCALE"
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
class CancellationRequest(BaseModel):
|
| 53 |
-
"""Request to cancel subscription."""
|
| 54 |
-
reason: Optional[str] = None
|
| 55 |
-
feedback: Optional[str] = None
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
class DowngradeRequest(BaseModel):
|
| 59 |
-
"""Request to downgrade subscription."""
|
| 60 |
-
plan_id: str
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
class OverageChargeResponse(BaseModel):
|
| 64 |
-
"""Response for overage charges."""
|
| 65 |
-
leads_used: int
|
| 66 |
-
plan_limit: int
|
| 67 |
-
overage_count: int
|
| 68 |
-
overage_cost: float
|
| 69 |
-
partner_commission: float
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
@router.post("/buy-franchise", response_model=FranchisePurchaseResponse)
|
| 73 |
-
async def buy_franchise(
|
| 74 |
-
current_user: User = Depends(get_current_user),
|
| 75 |
-
session: AsyncSession = Depends(get_async_session)
|
| 76 |
-
):
|
| 77 |
-
"""
|
| 78 |
-
Purchase Partner Franchise ($500 one-time fee).
|
| 79 |
-
|
| 80 |
-
Mock Payment: Simulates charge and unlocks partner portal.
|
| 81 |
-
|
| 82 |
-
Steps:
|
| 83 |
-
1. Find user's Partner record
|
| 84 |
-
2. Verify not already ACTIVE
|
| 85 |
-
3. Log franchise fee transaction ($500)
|
| 86 |
-
4. Unlock partner status to ACTIVE
|
| 87 |
-
"""
|
| 88 |
-
|
| 89 |
-
logger.info("Franchise purchase request", user_id=str(current_user.id))
|
| 90 |
-
|
| 91 |
-
# 1. Find Partner record
|
| 92 |
-
stmt = select(Partner).where(Partner.user_id == current_user.id)
|
| 93 |
-
result = await session.execute(stmt)
|
| 94 |
-
partner = result.scalar_one_or_none()
|
| 95 |
-
|
| 96 |
-
if not partner:
|
| 97 |
-
raise HTTPException(
|
| 98 |
-
status_code=status.HTTP_404_NOT_FOUND,
|
| 99 |
-
detail="Партнерская запись не найдена. Обратитесь в поддержку."
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
# 2. Check if already ACTIVE
|
| 103 |
-
if partner.status == PartnerStatus.ACTIVE:
|
| 104 |
-
return FranchisePurchaseResponse(
|
| 105 |
-
success=True,
|
| 106 |
-
status="ACTIVE",
|
| 107 |
-
message="Франшиза уже активна",
|
| 108 |
-
partner_id=str(partner.id)
|
| 109 |
-
)
|
| 110 |
-
|
| 111 |
-
# 3. Check if BANNED
|
| 112 |
-
if partner.status == PartnerStatus.BANNED:
|
| 113 |
-
raise HTTPException(
|
| 114 |
-
status_code=status.HTTP_403_FORBIDDEN,
|
| 115 |
-
detail="Ваша партнерская учетная запись заблокирована. Обратитесь в поддержку."
|
| 116 |
-
)
|
| 117 |
-
|
| 118 |
-
# 4. MOCK PAYMENT: Log franchise fee transaction
|
| 119 |
-
FRANCHISE_FEE = 500.0
|
| 120 |
-
|
| 121 |
-
franchise_transaction = PartnerEarning(
|
| 122 |
-
partner_id=partner.id,
|
| 123 |
-
tenant_id=partner.id, # Using partner.id as placeholder (no specific tenant)
|
| 124 |
-
amount_usd=-FRANCHISE_FEE, # Negative = expense/payment
|
| 125 |
-
transaction_type="FRANCHISE_FEE",
|
| 126 |
-
description=f"Franchise fee payment - Partner activation"
|
| 127 |
-
)
|
| 128 |
-
|
| 129 |
-
session.add(franchise_transaction)
|
| 130 |
-
|
| 131 |
-
logger.info("Logged franchise fee", amount=FRANCHISE_FEE)
|
| 132 |
-
|
| 133 |
-
# 5. Unlock Partner Status
|
| 134 |
-
partner.status = PartnerStatus.ACTIVE
|
| 135 |
-
partner.updated_at = datetime.utcnow()
|
| 136 |
-
|
| 137 |
-
session.add(partner)
|
| 138 |
-
await session.commit()
|
| 139 |
-
await session.refresh(partner)
|
| 140 |
-
|
| 141 |
-
logger.info("Partner activated", partner_id=str(partner.id), status=partner.status)
|
| 142 |
-
|
| 143 |
-
return FranchisePurchaseResponse(
|
| 144 |
-
success=True,
|
| 145 |
-
status="ACTIVE",
|
| 146 |
-
message="Франшиза успешно куплена! Добро пожаловать в партнерскую программу.",
|
| 147 |
-
partner_id=str(partner.id)
|
| 148 |
-
)
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
@router.get("/franchise-status")
|
| 152 |
-
async def get_franchise_status(
|
| 153 |
-
current_user: User = Depends(get_current_user),
|
| 154 |
-
session: AsyncSession = Depends(get_async_session)
|
| 155 |
-
):
|
| 156 |
-
"""
|
| 157 |
-
Get current franchise status for logged-in user.
|
| 158 |
-
|
| 159 |
-
Returns partner status: PENDING, ACTIVE, or BANNED.
|
| 160 |
-
"""
|
| 161 |
-
|
| 162 |
-
# Find Partner record
|
| 163 |
-
stmt = select(Partner).where(Partner.user_id == current_user.id)
|
| 164 |
-
result = await session.execute(stmt)
|
| 165 |
-
partner = result.scalar_one_or_none()
|
| 166 |
-
|
| 167 |
-
if not partner:
|
| 168 |
-
raise HTTPException(
|
| 169 |
-
status_code=status.HTTP_404_NOT_FOUND,
|
| 170 |
-
detail="Партнерская запись не найдена"
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
return {
|
| 174 |
-
"partner_id": str(partner.id),
|
| 175 |
-
"status": partner.status,
|
| 176 |
-
"company_name": partner.company_name,
|
| 177 |
-
"referral_code": partner.referral_code,
|
| 178 |
-
"balance_usd": partner.balance_usd,
|
| 179 |
-
"total_earned": partner.total_earned,
|
| 180 |
-
"is_active": partner.is_active
|
| 181 |
-
}
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
@router.get("/referral-link")
|
| 185 |
-
async def get_referral_link(
|
| 186 |
-
current_user: User = Depends(get_current_user),
|
| 187 |
-
session: AsyncSession = Depends(get_async_session)
|
| 188 |
-
):
|
| 189 |
-
"""
|
| 190 |
-
Получить реферальную ссылку для привлечения клиентов.
|
| 191 |
-
|
| 192 |
-
Доступно ТОЛЬКО для АКТИВНЫХ партнёров (купивших франшизу).
|
| 193 |
-
"""
|
| 194 |
-
|
| 195 |
-
# Find Partner record
|
| 196 |
-
stmt = select(Partner).where(Partner.user_id == current_user.id)
|
| 197 |
-
result = await session.execute(stmt)
|
| 198 |
-
partner = result.scalar_one_or_none()
|
| 199 |
-
|
| 200 |
-
if not partner:
|
| 201 |
-
raise HTTPException(
|
| 202 |
-
status_code=status.HTTP_404_NOT_FOUND,
|
| 203 |
-
detail="Партнерская запись не найдена"
|
| 204 |
-
)
|
| 205 |
-
|
| 206 |
-
# ПРОВЕРКА: Только ACTIVE партнёры могут получить реферальную ссылку
|
| 207 |
-
if partner.status != PartnerStatus.ACTIVE:
|
| 208 |
-
raise HTTPException(
|
| 209 |
-
status_code=status.HTTP_403_FORBIDDEN,
|
| 210 |
-
detail=f"Реферальные ссылки доступны только для активных партнёров. Ваш статус: {partner.status.value}. Купите франшизу за $500, чтобы получить доступ."
|
| 211 |
-
)
|
| 212 |
-
|
| 213 |
-
# Генерируем реферальную ссылку
|
| 214 |
-
referral_link = f"{settings.FRONTEND_URL}/register?ref={partner.referral_code}"
|
| 215 |
-
|
| 216 |
-
# ✅ Подсчёт количества клиентов
|
| 217 |
-
stmt_count = select(Tenant).where(Tenant.partner_ref_id == partner.id)
|
| 218 |
-
result_count = await session.execute(stmt_count)
|
| 219 |
-
all_tenants = result_count.scalars().all()
|
| 220 |
-
|
| 221 |
-
referred_count = len(all_tenants)
|
| 222 |
-
active_count = len([t for t in all_tenants if t.subscription_status == "active"])
|
| 223 |
-
|
| 224 |
-
logger.info(
|
| 225 |
-
"Реферальная ссылка сгенерирована",
|
| 226 |
-
partner_id=str(partner.id),
|
| 227 |
-
company=partner.company_name,
|
| 228 |
-
referral_code=partner.referral_code
|
| 229 |
-
)
|
| 230 |
-
|
| 231 |
-
return {
|
| 232 |
-
"referral_link": referral_link,
|
| 233 |
-
"referral_code": partner.referral_code,
|
| 234 |
-
"partner_status": partner.status,
|
| 235 |
-
"commission_rate": partner.commission_rate,
|
| 236 |
-
"total_earned": partner.total_earned,
|
| 237 |
-
"company_name": partner.company_name,
|
| 238 |
-
"partner_id": str(partner.id),
|
| 239 |
-
"balance_usd": partner.balance_usd,
|
| 240 |
-
"referred_tenants_count": referred_count,
|
| 241 |
-
"active_tenants_count": active_count
|
| 242 |
-
}
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
@router.get("/partner/clients")
|
| 246 |
-
async def get_partner_clients(
|
| 247 |
-
current_user: User = Depends(get_current_user),
|
| 248 |
-
session: AsyncSession = Depends(get_async_session)
|
| 249 |
-
):
|
| 250 |
-
"""
|
| 251 |
-
Получить список клиентов, привлечённых партнёром.
|
| 252 |
-
|
| 253 |
-
Только для ACTIVE партнёров.
|
| 254 |
-
"""
|
| 255 |
-
|
| 256 |
-
# Get partner record
|
| 257 |
-
stmt = select(Partner).where(Partner.user_id == current_user.id)
|
| 258 |
-
result = await session.execute(stmt)
|
| 259 |
-
partner = result.scalar_one_or_none()
|
| 260 |
-
|
| 261 |
-
if not partner:
|
| 262 |
-
raise HTTPException(
|
| 263 |
-
status_code=status.HTTP_404_NOT_FOUND,
|
| 264 |
-
detail="Партнерская запись не найдена"
|
| 265 |
-
)
|
| 266 |
-
|
| 267 |
-
if partner.status != PartnerStatus.ACTIVE:
|
| 268 |
-
raise HTTPException(
|
| 269 |
-
status_code=status.HTTP_403_FORBIDDEN,
|
| 270 |
-
detail="Доступ только для активных партнёров"
|
| 271 |
-
)
|
| 272 |
-
|
| 273 |
-
# Get all tenants referred by this partner
|
| 274 |
-
stmt = select(Tenant, User).join(
|
| 275 |
-
User, Tenant.id == User.tenant_id
|
| 276 |
-
).where(
|
| 277 |
-
Tenant.partner_ref_id == partner.id,
|
| 278 |
-
User.role == "OWNER" # Get owner email
|
| 279 |
-
).order_by(Tenant.created_at.desc())
|
| 280 |
-
|
| 281 |
-
result = await session.execute(stmt)
|
| 282 |
-
rows = result.all()
|
| 283 |
-
|
| 284 |
-
# Calculate commissions for each tenant
|
| 285 |
-
clients_data = []
|
| 286 |
-
|
| 287 |
-
for tenant, owner in rows:
|
| 288 |
-
# Get total paid by this tenant (sum of all SUBSCRIPTION transactions)
|
| 289 |
-
stmt_earnings = select(PartnerEarning).where(
|
| 290 |
-
PartnerEarning.tenant_id == tenant.id,
|
| 291 |
-
PartnerEarning.transaction_type.in_(["SUBSCRIPTION", "TRIAL_CONVERSION"])
|
| 292 |
-
)
|
| 293 |
-
result_earnings = await session.execute(stmt_earnings)
|
| 294 |
-
transactions = result_earnings.scalars().all()
|
| 295 |
-
|
| 296 |
-
total_paid = sum(t.amount_usd for t in transactions)
|
| 297 |
-
|
| 298 |
-
# Get commission earned from this tenant
|
| 299 |
-
stmt_commission = select(PartnerEarning).where(
|
| 300 |
-
PartnerEarning.partner_id == partner.id,
|
| 301 |
-
PartnerEarning.tenant_id == tenant.id,
|
| 302 |
-
PartnerEarning.transaction_type == "COMMISSION"
|
| 303 |
-
)
|
| 304 |
-
result_commission = await session.execute(stmt_commission)
|
| 305 |
-
commission_transactions = result_commission.scalars().all()
|
| 306 |
-
|
| 307 |
-
commission_earned = sum(t.amount_usd for t in commission_transactions)
|
| 308 |
-
|
| 309 |
-
clients_data.append({
|
| 310 |
-
"id": str(tenant.id),
|
| 311 |
-
"name": tenant.name,
|
| 312 |
-
"business_name": tenant.business_name,
|
| 313 |
-
"email": owner.email,
|
| 314 |
-
"subscription_plan": tenant.subscription_plan,
|
| 315 |
-
"subscription_status": tenant.subscription_status,
|
| 316 |
-
"created_at": tenant.created_at.isoformat(),
|
| 317 |
-
"total_paid": round(total_paid, 2),
|
| 318 |
-
"commission_earned": round(commission_earned, 2)
|
| 319 |
-
})
|
| 320 |
-
|
| 321 |
-
# Count active tenants
|
| 322 |
-
active_count = len([c for c in clients_data if c["subscription_status"] == "active"])
|
| 323 |
-
|
| 324 |
-
return {
|
| 325 |
-
"clients": clients_data,
|
| 326 |
-
"total_clients": len(clients_data),
|
| 327 |
-
"active_clients": active_count
|
| 328 |
-
}
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
@router.post("/subscription/upgrade", response_model=SubscriptionUpgradeResponse)
|
| 332 |
-
async def upgrade_subscription(
|
| 333 |
-
request: SubscriptionUpgradeRequest,
|
| 334 |
-
current_user: User = Depends(get_current_user),
|
| 335 |
-
session: AsyncSession = Depends(get_async_session)
|
| 336 |
-
):
|
| 337 |
-
"""
|
| 338 |
-
Upgrade tenant subscription plan.
|
| 339 |
-
|
| 340 |
-
Mock Payment: Simulates charge and credits 50% commission to referring partner.
|
| 341 |
-
|
| 342 |
-
Pricing:
|
| 343 |
-
- GROWTH: $199/month
|
| 344 |
-
- SCALE: $499/month
|
| 345 |
-
|
| 346 |
-
Steps:
|
| 347 |
-
1. Validate plan and price
|
| 348 |
-
2. Get current tenant
|
| 349 |
-
3. Update subscription (plan, status, end_date)
|
| 350 |
-
4. Log payment transaction
|
| 351 |
-
5. Calculate & credit partner commission (if referred)
|
| 352 |
-
6. Update partner balance and total_earned
|
| 353 |
-
"""
|
| 354 |
-
|
| 355 |
-
logger.info(
|
| 356 |
-
"Subscription upgrade request",
|
| 357 |
-
user_id=str(current_user.id),
|
| 358 |
-
plan=request.plan_id
|
| 359 |
-
)
|
| 360 |
-
|
| 361 |
-
# 1. Validate plan and get price
|
| 362 |
-
PRICING = {
|
| 363 |
-
"GROWTH": 199.0,
|
| 364 |
-
"SCALE": 499.0
|
| 365 |
-
}
|
| 366 |
-
|
| 367 |
-
plan_upper = request.plan_id.upper()
|
| 368 |
-
if plan_upper not in PRICING:
|
| 369 |
-
raise HTTPException(
|
| 370 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 371 |
-
detail=f"Invalid plan: {request.plan_id}. Must be GROWTH or SCALE."
|
| 372 |
-
)
|
| 373 |
-
|
| 374 |
-
price = PRICING[plan_upper]
|
| 375 |
-
logger.info("Subscription price calculated", price=price)
|
| 376 |
-
|
| 377 |
-
# 2. Get current tenant
|
| 378 |
-
stmt = select(Tenant).where(Tenant.id == current_user.tenant_id)
|
| 379 |
-
result = await session.execute(stmt)
|
| 380 |
-
tenant = result.scalar_one_or_none()
|
| 381 |
-
|
| 382 |
-
if not tenant:
|
| 383 |
-
raise HTTPException(
|
| 384 |
-
status_code=status.HTTP_404_NOT_FOUND,
|
| 385 |
-
detail="Tenant not found"
|
| 386 |
-
)
|
| 387 |
-
|
| 388 |
-
logger.info(
|
| 389 |
-
"Processing subscription for tenant",
|
| 390 |
-
tenant_name=tenant.name,
|
| 391 |
-
tenant_id=str(tenant.id)
|
| 392 |
-
)
|
| 393 |
-
|
| 394 |
-
# 3. Update tenant subscription
|
| 395 |
-
from datetime import timedelta
|
| 396 |
-
|
| 397 |
-
tenant.subscription_plan = plan_upper.lower() # "growth" or "scale"
|
| 398 |
-
tenant.subscription_status = "active"
|
| 399 |
-
tenant.subscription_start = datetime.utcnow()
|
| 400 |
-
tenant.subscription_end = datetime.utcnow() + timedelta(days=30) # +30 days
|
| 401 |
-
tenant.updated_at = datetime.utcnow()
|
| 402 |
-
|
| 403 |
-
# ✅ СБРОС СЧЁТЧИКА ДИАЛОГОВ ПРИ АПГРЕЙДЕ
|
| 404 |
-
tenant.leads_this_month = 0
|
| 405 |
-
|
| 406 |
-
session.add(tenant)
|
| 407 |
-
|
| 408 |
-
logger.info(
|
| 409 |
-
"Subscription updated",
|
| 410 |
-
plan=tenant.subscription_plan,
|
| 411 |
-
active_until=tenant.subscription_end.date().isoformat()
|
| 412 |
-
)
|
| 413 |
-
|
| 414 |
-
# 4. Log payment transaction (using PartnerEarning as general transaction log)
|
| 415 |
-
payment_transaction = PartnerEarning(
|
| 416 |
-
partner_id=tenant.partner_ref_id or tenant.id, # Use partner_ref_id if exists
|
| 417 |
-
tenant_id=tenant.id,
|
| 418 |
-
amount_usd=price,
|
| 419 |
-
transaction_type="SUBSCRIPTION",
|
| 420 |
-
description=f"Subscription payment - {plan_upper} plan"
|
| 421 |
-
)
|
| 422 |
-
|
| 423 |
-
session.add(payment_transaction)
|
| 424 |
-
logger.info("Payment logged", amount=price, transaction_type="SUBSCRIPTION")
|
| 425 |
-
|
| 426 |
-
# 5. COMMISSION LOGIC: If tenant was referred, credit 50% to partner
|
| 427 |
-
partner_commission = 0.0
|
| 428 |
-
|
| 429 |
-
if tenant.partner_ref_id:
|
| 430 |
-
logger.info("Tenant has referring partner", partner_id=str(tenant.partner_ref_id))
|
| 431 |
-
|
| 432 |
-
# Fetch the referring partner
|
| 433 |
-
stmt = select(Partner).where(Partner.id == tenant.partner_ref_id)
|
| 434 |
-
result = await session.execute(stmt)
|
| 435 |
-
referring_partner = result.scalar_one_or_none()
|
| 436 |
-
|
| 437 |
-
if referring_partner:
|
| 438 |
-
# Calculate 50% commission
|
| 439 |
-
partner_commission = price * referring_partner.commission_rate # 0.5 = 50%
|
| 440 |
-
|
| 441 |
-
logger.info(
|
| 442 |
-
"Calculating partner commission",
|
| 443 |
-
partner_company=referring_partner.company_name,
|
| 444 |
-
commission_rate=referring_partner.commission_rate,
|
| 445 |
-
commission_amount=partner_commission
|
| 446 |
-
)
|
| 447 |
-
|
| 448 |
-
# Update partner balance and total earned
|
| 449 |
-
referring_partner.balance_usd += partner_commission
|
| 450 |
-
referring_partner.total_earned += partner_commission
|
| 451 |
-
referring_partner.updated_at = datetime.utcnow()
|
| 452 |
-
|
| 453 |
-
session.add(referring_partner)
|
| 454 |
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
partner_commission=partner_commission
|
| 485 |
-
)
|
| 486 |
-
|
| 487 |
-
return SubscriptionUpgradeResponse(
|
| 488 |
-
success=True,
|
| 489 |
-
message=f"Подписка успешно обновлена до плана {plan_upper}!",
|
| 490 |
-
plan=tenant.subscription_plan,
|
| 491 |
-
amount_paid=price,
|
| 492 |
-
partner_commission=partner_commission
|
| 493 |
-
)
|
| 494 |
-
|
| 495 |
|
| 496 |
-
@router.post("/
|
| 497 |
-
async def
|
| 498 |
-
request:
|
| 499 |
-
current_user: User = Depends(
|
| 500 |
session: AsyncSession = Depends(get_async_session)
|
| 501 |
):
|
| 502 |
"""
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
Mock Payment: Charge first month + credit partner commission.
|
| 506 |
-
|
| 507 |
-
Steps:
|
| 508 |
-
1. Verify current status is TRIAL
|
| 509 |
-
2. Charge subscription fee
|
| 510 |
-
3. Update status to ACTIVE
|
| 511 |
-
4. Set billing dates
|
| 512 |
-
5. Credit partner commission
|
| 513 |
"""
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
)
|
| 520 |
-
|
| 521 |
-
# Pricing
|
| 522 |
-
PRICING = {
|
| 523 |
-
"START": 99.0,
|
| 524 |
-
"GROWTH": 199.0,
|
| 525 |
-
"SCALE": 499.0
|
| 526 |
-
}
|
| 527 |
-
|
| 528 |
-
plan_upper = request.plan_id.upper()
|
| 529 |
-
if plan_upper not in PRICING:
|
| 530 |
-
raise HTTPException(
|
| 531 |
-
status_code=status.HTTP_400_BAD_REQUEST,
|
| 532 |
-
detail=f"Invalid plan: {request.plan_id}"
|
| 533 |
-
)
|
| 534 |
-
|
| 535 |
-
price = PRICING[plan_upper]
|
| 536 |
-
|
| 537 |
-
# Get tenant
|
| 538 |
-
stmt = select(Tenant).where(Tenant.id == current_user.tenant_id)
|
| 539 |
-
result = await session.execute(stmt)
|
| 540 |
-
tenant = result.scalar_one_or_none()
|
| 541 |
-
|
| 542 |
-
if not tenant:
|
| 543 |
-
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 544 |
-
|
| 545 |
-
# Verify TRIAL status
|
| 546 |
-
if tenant.subscription_status != "trial":
|
| 547 |
-
raise HTTPException(
|
| 548 |
-
status_code=400,
|
| 549 |
-
detail=f"Cannot convert. Current status: {tenant.subscription_status}"
|
| 550 |
-
)
|
| 551 |
-
|
| 552 |
-
# Update subscription
|
| 553 |
-
from datetime import timedelta
|
| 554 |
-
|
| 555 |
-
tenant.subscription_plan = plan_upper.lower()
|
| 556 |
-
tenant.subscription_status = "active"
|
| 557 |
-
tenant.subscription_start = datetime.utcnow()
|
| 558 |
-
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
|
| 559 |
-
tenant.last_billing_date = datetime.utcnow()
|
| 560 |
-
tenant.next_billing_date = datetime.utcnow() + timedelta(days=30)
|
| 561 |
-
tenant.updated_at = datetime.utcnow()
|
| 562 |
-
|
| 563 |
-
# ✅ СБРОС СЧЁТЧИКА ДИАЛОГОВ ПРИ КОНВЕРСИИ TRIAL
|
| 564 |
-
tenant.leads_this_month = 0
|
| 565 |
-
|
| 566 |
-
session.add(tenant)
|
| 567 |
-
|
| 568 |
-
# Log payment
|
| 569 |
-
payment_transaction = PartnerEarning(
|
| 570 |
-
partner_id=tenant.partner_ref_id or tenant.id,
|
| 571 |
-
tenant_id=tenant.id,
|
| 572 |
-
amount_usd=price,
|
| 573 |
-
transaction_type="TRIAL_CONVERSION",
|
| 574 |
-
description=f"Trial conversion - {plan_upper} plan (First payment)"
|
| 575 |
-
)
|
| 576 |
-
session.add(payment_transaction)
|
| 577 |
-
|
| 578 |
-
# Partner commission
|
| 579 |
-
partner_commission = 0.0
|
| 580 |
-
|
| 581 |
-
if tenant.partner_ref_id:
|
| 582 |
-
stmt = select(Partner).where(Partner.id == tenant.partner_ref_id)
|
| 583 |
-
result = await session.execute(stmt)
|
| 584 |
-
referring_partner = result.scalar_one_or_none()
|
| 585 |
-
|
| 586 |
-
if referring_partner:
|
| 587 |
-
partner_commission = price * referring_partner.commission_rate
|
| 588 |
-
|
| 589 |
-
referring_partner.balance_usd += partner_commission
|
| 590 |
-
referring_partner.total_earned += partner_commission
|
| 591 |
-
referring_partner.updated_at = datetime.utcnow()
|
| 592 |
-
session.add(referring_partner)
|
| 593 |
-
|
| 594 |
-
commission_transaction = PartnerEarning(
|
| 595 |
-
partner_id=referring_partner.id,
|
| 596 |
-
tenant_id=tenant.id,
|
| 597 |
-
amount_usd=partner_commission,
|
| 598 |
-
transaction_type="COMMISSION",
|
| 599 |
-
description=f"Trial conversion commission - {plan_upper} plan"
|
| 600 |
-
)
|
| 601 |
-
session.add(commission_transaction)
|
| 602 |
-
|
| 603 |
-
print(f"✅ Partner commission: ${partner_commission}")
|
| 604 |
-
|
| 605 |
-
await session.commit()
|
| 606 |
-
await session.refresh(tenant)
|
| 607 |
-
|
| 608 |
-
print(f"🎉 Trial converted to PAID! Plan: {tenant.subscription_plan}")
|
| 609 |
-
|
| 610 |
-
return SubscriptionUpgradeResponse(
|
| 611 |
-
success=True,
|
| 612 |
-
message=f"Пробный период завершён! Добро пожаловать в {plan_upper}!",
|
| 613 |
-
plan=tenant.subscription_plan,
|
| 614 |
-
amount_paid=price,
|
| 615 |
-
partner_commission=partner_commission
|
| 616 |
)
|
|
|
|
| 617 |
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
request: DowngradeRequest,
|
| 622 |
-
current_user: User = Depends(get_current_user),
|
| 623 |
session: AsyncSession = Depends(get_async_session)
|
| 624 |
):
|
| 625 |
"""
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
Example: SCALE ($499) → GROWTH ($199)
|
| 629 |
-
- Days remaining: 20/30
|
| 630 |
-
- Unused SCALE: $499 * (20/30) = $332.67
|
| 631 |
-
- New GROWTH charge: $199
|
| 632 |
-
- Credit to account: $133.67
|
| 633 |
"""
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
print(f" Target Plan: {request.plan_id}")
|
| 637 |
-
|
| 638 |
-
PRICING = {
|
| 639 |
-
"START": 99.0,
|
| 640 |
-
"GROWTH": 199.0,
|
| 641 |
-
"SCALE": 499.0
|
| 642 |
-
}
|
| 643 |
-
|
| 644 |
-
PLAN_HIERARCHY = {"START": 1, "GROWTH": 2, "SCALE": 3}
|
| 645 |
-
|
| 646 |
-
plan_upper = request.plan_id.upper()
|
| 647 |
-
if plan_upper not in PRICING:
|
| 648 |
-
raise HTTPException(status_code=400, detail="Invalid plan")
|
| 649 |
-
|
| 650 |
-
# Get tenant
|
| 651 |
-
stmt = select(Tenant).where(Tenant.id == current_user.tenant_id)
|
| 652 |
-
result = await session.execute(stmt)
|
| 653 |
-
tenant = result.scalar_one_or_none()
|
| 654 |
-
|
| 655 |
-
if not tenant:
|
| 656 |
-
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 657 |
-
|
| 658 |
-
current_plan = tenant.subscription_plan.upper()
|
| 659 |
-
|
| 660 |
-
# Verify it's a downgrade
|
| 661 |
-
if PLAN_HIERARCHY[plan_upper] >= PLAN_HIERARCHY[current_plan]:
|
| 662 |
-
raise HTTPException(
|
| 663 |
-
status_code=400,
|
| 664 |
-
detail="This is not a downgrade. Use /upgrade endpoint."
|
| 665 |
-
)
|
| 666 |
-
|
| 667 |
-
# Calculate prorated refund
|
| 668 |
-
from datetime import timedelta
|
| 669 |
-
|
| 670 |
-
if tenant.subscription_end:
|
| 671 |
-
days_remaining = (tenant.subscription_end - datetime.utcnow()).days
|
| 672 |
-
if days_remaining < 0:
|
| 673 |
-
days_remaining = 0
|
| 674 |
-
else:
|
| 675 |
-
days_remaining = 0
|
| 676 |
-
|
| 677 |
-
current_price = PRICING[current_plan]
|
| 678 |
-
new_price = PRICING[plan_upper]
|
| 679 |
-
|
| 680 |
-
# Prorated refund
|
| 681 |
-
unused_amount = (current_price / 30) * days_remaining
|
| 682 |
-
credit = unused_amount - new_price
|
| 683 |
-
|
| 684 |
-
print(f" Current Plan: {current_plan} (${current_price})")
|
| 685 |
-
print(f" New Plan: {plan_upper} (${new_price})")
|
| 686 |
-
print(f" Days Remaining: {days_remaining}")
|
| 687 |
-
print(f" Unused Amount: ${unused_amount:.2f}")
|
| 688 |
-
print(f" Credit: ${credit:.2f}")
|
| 689 |
-
|
| 690 |
-
# Update subscription
|
| 691 |
-
tenant.subscription_plan = plan_upper.lower()
|
| 692 |
-
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
|
| 693 |
-
tenant.next_billing_date = datetime.utcnow() + timedelta(days=30)
|
| 694 |
-
tenant.updated_at = datetime.utcnow()
|
| 695 |
-
|
| 696 |
-
# ✅ СБРОС СЧЁТЧИКА ДИАЛОГОВ ПРИ DOWNGRADE
|
| 697 |
-
# Клиент получает свежий лимит нового плана
|
| 698 |
-
tenant.leads_this_month = 0
|
| 699 |
-
|
| 700 |
-
session.add(tenant)
|
| 701 |
-
|
| 702 |
-
# Log downgrade transaction
|
| 703 |
-
downgrade_transaction = PartnerEarning(
|
| 704 |
-
partner_id=tenant.partner_ref_id or tenant.id,
|
| 705 |
-
tenant_id=tenant.id,
|
| 706 |
-
amount_usd=-new_price, # Charge new plan
|
| 707 |
-
transaction_type="DOWNGRADE",
|
| 708 |
-
description=f"Downgrade from {current_plan} to {plan_upper} (Credit: ${credit:.2f})"
|
| 709 |
)
|
| 710 |
-
session.add(downgrade_transaction)
|
| 711 |
-
|
| 712 |
-
# Notify partner (no commission on downgrade, loss of future commission)
|
| 713 |
-
if tenant.partner_ref_id and credit > 0:
|
| 714 |
-
credit_transaction = PartnerEarning(
|
| 715 |
-
partner_id=tenant.partner_ref_id,
|
| 716 |
-
tenant_id=tenant.id,
|
| 717 |
-
amount_usd=credit,
|
| 718 |
-
transaction_type="REFUND_CREDIT",
|
| 719 |
-
description=f"Prorated credit for downgrade"
|
| 720 |
-
)
|
| 721 |
-
session.add(credit_transaction)
|
| 722 |
-
|
| 723 |
-
await session.commit()
|
| 724 |
-
await session.refresh(tenant)
|
| 725 |
-
|
| 726 |
-
print(f"✅ Downgraded to {plan_upper}")
|
| 727 |
-
|
| 728 |
-
return {
|
| 729 |
-
"success": True,
|
| 730 |
-
"message": f"План понижен до {plan_upper}",
|
| 731 |
-
"plan": tenant.subscription_plan,
|
| 732 |
-
"credit_applied": round(credit, 2) if credit > 0 else 0,
|
| 733 |
-
"next_billing_date": tenant.next_billing_date.isoformat() if tenant.next_billing_date else None
|
| 734 |
-
}
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
@router.post("/subscription/cancel")
|
| 738 |
-
async def cancel_subscription(
|
| 739 |
-
request: CancellationRequest,
|
| 740 |
-
current_user: User = Depends(get_current_user),
|
| 741 |
-
session: AsyncSession = Depends(get_async_session)
|
| 742 |
-
):
|
| 743 |
-
"""
|
| 744 |
-
Cancel subscription (immediate or end of period).
|
| 745 |
-
|
| 746 |
-
Options:
|
| 747 |
-
- Immediate: Cancel now, prorated refund
|
| 748 |
-
- End of period: Keep access until subscription_end
|
| 749 |
-
"""
|
| 750 |
-
|
| 751 |
-
print(f"\n❌ Cancellation request from user: {current_user.id}")
|
| 752 |
-
print(f" Reason: {request.reason or 'Not provided'}")
|
| 753 |
-
print(f" Feedback: {request.feedback or 'None'}")
|
| 754 |
-
|
| 755 |
-
# Get tenant
|
| 756 |
-
stmt = select(Tenant).where(Tenant.id == current_user.tenant_id)
|
| 757 |
-
result = await session.execute(stmt)
|
| 758 |
tenant = result.scalar_one_or_none()
|
| 759 |
|
| 760 |
-
if not tenant:
|
| 761 |
-
|
|
|
|
| 762 |
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
# Cancel at end of period (keep access until subscription_end)
|
| 767 |
-
tenant.subscription_status = "cancelled"
|
| 768 |
-
tenant.updated_at = datetime.utcnow()
|
| 769 |
-
|
| 770 |
-
session.add(tenant)
|
| 771 |
-
|
| 772 |
-
# Log cancellation
|
| 773 |
-
cancellation_transaction = PartnerEarning(
|
| 774 |
-
partner_id=tenant.partner_ref_id or tenant.id,
|
| 775 |
-
tenant_id=tenant.id,
|
| 776 |
-
amount_usd=0.0,
|
| 777 |
-
transaction_type="CANCELLATION",
|
| 778 |
-
description=f"Subscription cancelled. Reason: {request.reason or 'Not specified'}"
|
| 779 |
-
)
|
| 780 |
-
session.add(cancellation_transaction)
|
| 781 |
-
|
| 782 |
-
# Notify partner about churn
|
| 783 |
-
if tenant.partner_ref_id:
|
| 784 |
-
stmt = select(Partner).where(Partner.id == tenant.partner_ref_id)
|
| 785 |
-
result = await session.execute(stmt)
|
| 786 |
-
partner = result.scalar_one_or_none()
|
| 787 |
-
|
| 788 |
-
if partner:
|
| 789 |
-
# Log churn notification for partner
|
| 790 |
-
churn_notification = PartnerEarning(
|
| 791 |
-
partner_id=partner.id,
|
| 792 |
-
tenant_id=tenant.id,
|
| 793 |
-
amount_usd=0.0,
|
| 794 |
-
transaction_type="CHURN_ALERT",
|
| 795 |
-
description=f"Client churned: {tenant.name} ({tenant.subscription_plan.upper()}). Reason: {request.reason or 'Unknown'}"
|
| 796 |
-
)
|
| 797 |
-
session.add(churn_notification)
|
| 798 |
-
|
| 799 |
-
await session.commit()
|
| 800 |
-
await session.refresh(tenant)
|
| 801 |
-
|
| 802 |
-
print(f"✅ Subscription cancelled (access until {tenant.subscription_end})")
|
| 803 |
-
|
| 804 |
-
return {
|
| 805 |
-
"success": True,
|
| 806 |
-
"message": "Подписка отменена. Доступ сохранится до конца оплаченного периода.",
|
| 807 |
-
"access_until": tenant.subscription_end.isoformat() if tenant.subscription_end else None
|
| 808 |
-
}
|
| 809 |
-
|
| 810 |
|
| 811 |
-
@router.
|
| 812 |
-
async def
|
| 813 |
-
|
|
|
|
| 814 |
session: AsyncSession = Depends(get_async_session)
|
| 815 |
):
|
| 816 |
"""
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
Pricing:
|
| 820 |
-
- START: 1,000 leads/month → $0.15 per extra lead
|
| 821 |
-
- GROWTH: 10,000 leads/month → $0.10 per extra lead
|
| 822 |
-
- SCALE: Unlimited
|
| 823 |
"""
|
|
|
|
| 824 |
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
raise HTTPException(status_code=
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
"start": 1000,
|
| 836 |
-
"growth": 10000,
|
| 837 |
-
"scale": 999999999 # Unlimited
|
| 838 |
-
}
|
| 839 |
-
|
| 840 |
-
OVERAGE_RATES = {
|
| 841 |
-
"start": 0.15,
|
| 842 |
-
"growth": 0.10,
|
| 843 |
-
"scale": 0.00
|
| 844 |
-
}
|
| 845 |
-
|
| 846 |
-
plan = tenant.subscription_plan.lower()
|
| 847 |
-
limit = PLAN_LIMITS.get(plan, 1000)
|
| 848 |
-
rate = OVERAGE_RATES.get(plan, 0.15)
|
| 849 |
-
|
| 850 |
-
leads_used = tenant.leads_this_month
|
| 851 |
-
overage_count = max(0, leads_used - limit)
|
| 852 |
-
overage_cost = overage_count * rate
|
| 853 |
-
|
| 854 |
-
# Partner commission on overage
|
| 855 |
-
partner_commission = 0.0
|
| 856 |
-
if tenant.partner_ref_id and overage_cost > 0:
|
| 857 |
-
stmt = select(Partner).where(Partner.id == tenant.partner_ref_id)
|
| 858 |
-
result = await session.execute(stmt)
|
| 859 |
-
partner = result.scalar_one_or_none()
|
| 860 |
-
|
| 861 |
-
if partner:
|
| 862 |
-
partner_commission = overage_cost * partner.commission_rate
|
| 863 |
|
| 864 |
-
|
| 865 |
-
"leads_used": leads_used,
|
| 866 |
-
"plan_limit": limit,
|
| 867 |
-
"overage_count": overage_count,
|
| 868 |
-
"overage_cost": round(overage_cost, 2),
|
| 869 |
-
"partner_commission": round(partner_commission, 2),
|
| 870 |
-
"plan": plan.upper()
|
| 871 |
-
}
|
| 872 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 873 |
|
| 874 |
-
@router.post("/
|
| 875 |
-
async def
|
|
|
|
|
|
|
| 876 |
session: AsyncSession = Depends(get_async_session)
|
| 877 |
):
|
| 878 |
"""
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
Tenant.subscription_status == "active",
|
| 900 |
-
Tenant.next_billing_date <= datetime.utcnow()
|
| 901 |
-
)
|
| 902 |
-
result = await session.execute(stmt)
|
| 903 |
-
tenants = result.scalars().all()
|
| 904 |
-
|
| 905 |
-
print(f" Found {len(tenants)} tenants to renew")
|
| 906 |
-
|
| 907 |
-
PRICING = {
|
| 908 |
-
"start": 99.0,
|
| 909 |
-
"growth": 199.0,
|
| 910 |
-
"scale": 499.0
|
| 911 |
-
}
|
| 912 |
-
|
| 913 |
-
OVERAGE_RATES = {
|
| 914 |
-
"start": 0.15,
|
| 915 |
-
"growth": 0.10,
|
| 916 |
-
"scale": 0.00
|
| 917 |
-
}
|
| 918 |
-
|
| 919 |
-
PLAN_LIMITS = {
|
| 920 |
-
"start": 1000,
|
| 921 |
-
"growth": 10000,
|
| 922 |
-
"scale": 999999999
|
| 923 |
-
}
|
| 924 |
-
|
| 925 |
-
renewed_count = 0
|
| 926 |
-
total_revenue = 0.0
|
| 927 |
-
total_commission = 0.0
|
| 928 |
-
|
| 929 |
-
for tenant in tenants:
|
| 930 |
-
plan = tenant.subscription_plan.lower()
|
| 931 |
-
base_price = PRICING.get(plan, 99.0)
|
| 932 |
-
|
| 933 |
-
# Calculate overage
|
| 934 |
-
limit = PLAN_LIMITS.get(plan, 1000)
|
| 935 |
-
overage_count = max(0, tenant.leads_this_month - limit)
|
| 936 |
-
overage_cost = overage_count * OVERAGE_RATES.get(plan, 0.15)
|
| 937 |
-
|
| 938 |
-
total_charge = base_price + overage_cost
|
| 939 |
-
|
| 940 |
-
print(f"\n Renewing: {tenant.name}")
|
| 941 |
-
print(f" Plan: {plan.upper()} (${base_price})")
|
| 942 |
-
print(f" Leads: {tenant.leads_this_month}/{limit}")
|
| 943 |
-
print(f" Overage: {overage_count} × ${OVERAGE_RATES.get(plan, 0)} = ${overage_cost:.2f}")
|
| 944 |
-
print(f" Total: ${total_charge:.2f}")
|
| 945 |
-
|
| 946 |
-
# Log payment
|
| 947 |
-
payment_transaction = PartnerEarning(
|
| 948 |
-
partner_id=tenant.partner_ref_id or tenant.id,
|
| 949 |
-
tenant_id=tenant.id,
|
| 950 |
-
amount_usd=total_charge,
|
| 951 |
-
transaction_type="RECURRING_PAYMENT",
|
| 952 |
-
description=f"Monthly renewal - {plan.upper()} (Overage: ${overage_cost:.2f})"
|
| 953 |
-
)
|
| 954 |
-
session.add(payment_transaction)
|
| 955 |
-
|
| 956 |
-
# Partner commission
|
| 957 |
-
if tenant.partner_ref_id:
|
| 958 |
-
stmt = select(Partner).where(Partner.id == tenant.partner_ref_id)
|
| 959 |
-
result = await session.execute(stmt)
|
| 960 |
-
partner = result.scalar_one_or_none()
|
| 961 |
-
|
| 962 |
-
if partner:
|
| 963 |
-
commission = total_charge * partner.commission_rate
|
| 964 |
-
|
| 965 |
-
partner.balance_usd += commission
|
| 966 |
-
partner.total_earned += commission
|
| 967 |
-
partner.updated_at = datetime.utcnow()
|
| 968 |
-
session.add(partner)
|
| 969 |
-
|
| 970 |
-
# Log commission
|
| 971 |
-
commission_transaction = PartnerEarning(
|
| 972 |
-
partner_id=partner.id,
|
| 973 |
-
tenant_id=tenant.id,
|
| 974 |
-
amount_usd=commission,
|
| 975 |
-
transaction_type="RECURRING_COMMISSION",
|
| 976 |
-
description=f"Monthly commission - {plan.upper()} + overage (${overage_cost:.2f})"
|
| 977 |
-
)
|
| 978 |
-
session.add(commission_transaction)
|
| 979 |
-
|
| 980 |
-
total_commission += commission
|
| 981 |
-
print(f" Partner Commission: ${commission:.2f}")
|
| 982 |
-
|
| 983 |
-
# Update tenant
|
| 984 |
-
tenant.last_billing_date = datetime.utcnow()
|
| 985 |
-
tenant.next_billing_date = datetime.utcnow() + timedelta(days=30)
|
| 986 |
-
tenant.subscription_end = datetime.utcnow() + timedelta(days=30)
|
| 987 |
-
tenant.leads_this_month = 0 # Reset counter
|
| 988 |
-
tenant.overage_charges = 0.0
|
| 989 |
-
tenant.updated_at = datetime.utcnow()
|
| 990 |
-
|
| 991 |
-
session.add(tenant)
|
| 992 |
-
|
| 993 |
-
renewed_count += 1
|
| 994 |
-
total_revenue += total_charge
|
| 995 |
-
|
| 996 |
-
await session.commit()
|
| 997 |
-
|
| 998 |
-
print(f"\n✅ CRON Complete:")
|
| 999 |
-
print(f" Renewed: {renewed_count} tenants")
|
| 1000 |
-
print(f" Revenue: ${total_revenue:.2f}")
|
| 1001 |
-
print(f" Partner Commissions: ${total_commission:.2f}\n")
|
| 1002 |
-
|
| 1003 |
-
return {
|
| 1004 |
-
"success": True,
|
| 1005 |
-
"renewed_count": renewed_count,
|
| 1006 |
-
"total_revenue": round(total_revenue, 2),
|
| 1007 |
-
"total_commission": round(total_commission, 2)
|
| 1008 |
-
}
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, Request, Header
|
| 2 |
+
from typing import Optional
|
| 3 |
+
from app.api.deps import get_current_active_user
|
| 4 |
+
from app.models.user import User
|
| 5 |
+
from app.core.database import get_async_session
|
| 6 |
+
from app.services.stripe_service import stripe_service
|
| 7 |
+
from app.models.tenant import Tenant
|
| 8 |
+
from sqlmodel import select
|
| 9 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
|
| 10 |
from datetime import datetime
|
| 11 |
+
import logging
|
| 12 |
+
import stripe
|
| 13 |
+
from app.core.config import settings
|
| 14 |
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
router = APIRouter(prefix="/billing", tags=["Billing"])
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
async def _handle_checkout_completed(session: AsyncSession, data):
|
| 20 |
+
client_reference_id = data.get('client_reference_id') # Tenant ID
|
| 21 |
+
customer_id = data.get('customer')
|
| 22 |
+
subscription_id = data.get('subscription')
|
| 23 |
+
metadata = data.get('metadata', {})
|
| 24 |
+
plan_name = metadata.get('plan', 'start')
|
| 25 |
+
|
| 26 |
+
if client_reference_id:
|
| 27 |
+
try:
|
| 28 |
+
from uuid import UUID
|
| 29 |
+
tenant_id = UUID(client_reference_id)
|
| 30 |
+
result = await session.execute(select(Tenant).where(Tenant.id == tenant_id))
|
| 31 |
+
tenant = result.scalar_one_or_none()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
if tenant:
|
| 34 |
+
# Store Stripe IDs (assuming fields exist or we add them)
|
| 35 |
+
# For now using dynamic attribution if fields missing in model definition
|
| 36 |
+
# But better to have them. I will assume they are added or I use existing fields.
|
| 37 |
+
# Tenant model usually has 'subscription_status'.
|
| 38 |
+
# We need to ensure we can save customer_id.
|
| 39 |
+
# If model is strict, we might need migration.
|
| 40 |
+
# For this step, I will try to set them.
|
| 41 |
+
|
| 42 |
+
tenant.stripe_customer_id = customer_id
|
| 43 |
+
tenant.stripe_subscription_id = subscription_id
|
| 44 |
+
tenant.subscription_plan = plan_name.lower()
|
| 45 |
+
tenant.subscription_status = "active"
|
| 46 |
+
|
| 47 |
+
# Default exp to 30 days if not present (will be updated by invoice.paid)
|
| 48 |
+
tenant.subscription_end = datetime.fromtimestamp(datetime.utcnow().timestamp() + 30*24*3600)
|
| 49 |
+
|
| 50 |
+
tenant.updated_at = datetime.utcnow()
|
| 51 |
+
session.add(tenant)
|
| 52 |
+
await session.commit()
|
| 53 |
+
logger.info(f"✅ Subscription activated for Tenant {tenant.id} (Plan: {plan_name})")
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"Failed to activate subscription: {e}")
|
| 56 |
+
|
| 57 |
+
async def _handle_payment_succeeded(session: AsyncSession, data):
|
| 58 |
+
customer_id = data.get('customer')
|
| 59 |
+
if customer_id:
|
| 60 |
+
# We need to find tenant by stripe_customer_id
|
| 61 |
+
# This requires querying a JSON field or a new column.
|
| 62 |
+
# Assuming we added the column or we scan.
|
| 63 |
+
# Scan is bad. We need a column.
|
| 64 |
+
# For this implementation, I assume we adding the column in next step or it exists.
|
| 65 |
+
|
| 66 |
+
result = await session.execute(select(Tenant).where(Tenant.stripe_customer_id == customer_id))
|
| 67 |
+
tenant = result.scalar_one_or_none()
|
| 68 |
+
|
| 69 |
+
if tenant:
|
| 70 |
+
period_end = data.get('lines', {}).get('data', [{}])[0].get('period', {}).get('end')
|
| 71 |
+
if period_end:
|
| 72 |
+
tenant.subscription_end = datetime.fromtimestamp(period_end)
|
| 73 |
|
| 74 |
+
tenant.subscription_status = "active"
|
| 75 |
+
session.add(tenant)
|
| 76 |
+
await session.commit()
|
| 77 |
+
logger.info(f"💰 Payment succeeded for Tenant {tenant.id}, extended to {tenant.subscription_end}")
|
| 78 |
+
|
| 79 |
+
async def _handle_subscription_deleted(session: AsyncSession, data):
|
| 80 |
+
customer_id = data.get('customer')
|
| 81 |
+
if customer_id:
|
| 82 |
+
result = await session.execute(select(Tenant).where(Tenant.stripe_customer_id == customer_id))
|
| 83 |
+
tenant = result.scalar_one_or_none()
|
| 84 |
+
if tenant:
|
| 85 |
+
tenant.subscription_status = "canceled"
|
| 86 |
+
session.add(tenant)
|
| 87 |
+
await session.commit()
|
| 88 |
+
|
| 89 |
+
@router.post("/checkout")
|
| 90 |
+
class CheckoutRequest(BaseModel):
|
| 91 |
+
plan: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
@router.post("/checkout")
|
| 94 |
+
async def create_checkout(
|
| 95 |
+
request: CheckoutRequest,
|
| 96 |
+
current_user: User = Depends(get_current_active_user),
|
| 97 |
session: AsyncSession = Depends(get_async_session)
|
| 98 |
):
|
| 99 |
"""
|
| 100 |
+
Create a Stripe Checkout Session for subscription.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
"""
|
| 102 |
+
tenant_id = str(current_user.tenant_id)
|
| 103 |
+
url = await stripe_service.create_checkout_session(
|
| 104 |
+
tenant_id=tenant_id,
|
| 105 |
+
plan=request.plan,
|
| 106 |
+
email=current_user.email
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
)
|
| 108 |
+
return {"url": url}
|
| 109 |
|
| 110 |
+
@router.post("/portal")
|
| 111 |
+
async def create_portal(
|
| 112 |
+
current_user: User = Depends(get_current_active_user),
|
|
|
|
|
|
|
| 113 |
session: AsyncSession = Depends(get_async_session)
|
| 114 |
):
|
| 115 |
"""
|
| 116 |
+
Create a Stripe Billing Portal Session.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
"""
|
| 118 |
+
result = await session.execute(
|
| 119 |
+
select(Tenant).where(Tenant.id == current_user.tenant_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
tenant = result.scalar_one_or_none()
|
| 122 |
|
| 123 |
+
if not tenant or not getattr(tenant, "stripe_customer_id", None):
|
| 124 |
+
# Fallback logic if needed, or error
|
| 125 |
+
raise HTTPException(status_code=400, detail="No active billing account found")
|
| 126 |
|
| 127 |
+
url = await stripe_service.create_portal_session(tenant.stripe_customer_id)
|
| 128 |
+
return {"url": url}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
@router.post("/webhook")
|
| 131 |
+
async def stripe_webhook(
|
| 132 |
+
request: Request,
|
| 133 |
+
stripe_signature: str = Header(None),
|
| 134 |
session: AsyncSession = Depends(get_async_session)
|
| 135 |
):
|
| 136 |
"""
|
| 137 |
+
Handle Stripe Webhooks.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
"""
|
| 139 |
+
payload = await request.body()
|
| 140 |
|
| 141 |
+
try:
|
| 142 |
+
event = stripe_service.construct_event(payload, stripe_signature)
|
| 143 |
+
except HTTPException as e:
|
| 144 |
+
raise e
|
| 145 |
+
except Exception as e:
|
| 146 |
+
logger.error(f"Webhook error: {e}")
|
| 147 |
+
raise HTTPException(status_code=400, detail="Webhook Error")
|
| 148 |
+
|
| 149 |
+
event_type = event['type']
|
| 150 |
+
data = event['data']['object']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
logger.info(f"🔔 Stripe Event: {event_type}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
if event_type == 'checkout.session.completed':
|
| 155 |
+
await _handle_checkout_completed(session, data)
|
| 156 |
+
|
| 157 |
+
elif event_type == 'invoice.payment_succeeded':
|
| 158 |
+
await _handle_payment_succeeded(session, data)
|
| 159 |
+
|
| 160 |
+
elif event_type == 'customer.subscription.deleted':
|
| 161 |
+
await _handle_subscription_deleted(session, data)
|
| 162 |
|
| 163 |
+
@router.post("/mock-success")
|
| 164 |
+
async def mock_success(
|
| 165 |
+
plan: str,
|
| 166 |
+
current_user: User = Depends(get_current_active_user),
|
| 167 |
session: AsyncSession = Depends(get_async_session)
|
| 168 |
):
|
| 169 |
"""
|
| 170 |
+
Simulate successful payment for Dev/Mock mode.
|
| 171 |
+
Only works if Stripe is in mock mode (checked via service logic or environment).
|
| 172 |
+
"""
|
| 173 |
+
# Security check: Ensure we are in mock mode
|
| 174 |
+
if stripe_service.is_mock_mode:
|
| 175 |
+
# Simulate the logic from _handle_checkout_completed
|
| 176 |
+
tenant_id = current_user.tenant_id
|
| 177 |
+
result = await session.execute(select(Tenant).where(Tenant.id == tenant_id))
|
| 178 |
+
tenant = result.scalar_one_or_none()
|
| 179 |
+
|
| 180 |
+
if tenant:
|
| 181 |
+
tenant.subscription_plan = plan.lower()
|
| 182 |
+
tenant.subscription_status = "active"
|
| 183 |
+
tenant.subscription_end = datetime.fromtimestamp(datetime.utcnow().timestamp() + 30*24*3600)
|
| 184 |
+
tenant.updated_at = datetime.utcnow()
|
| 185 |
+
session.add(tenant)
|
| 186 |
+
await session.commit()
|
| 187 |
+
return {"status": "success", "message": f"Plan {plan} activated (MOCK)"}
|
| 188 |
+
|
| 189 |
+
raise HTTPException(status_code=400, detail="Mock mode not enabled or critical error")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/api/deps.py
CHANGED
|
@@ -43,6 +43,20 @@ async def get_current_user(
|
|
| 43 |
headers={"WWW-Authenticate": "Bearer"},
|
| 44 |
)
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
result = await session.execute(
|
| 47 |
select(User).where(User.id == UUID(user_id))
|
| 48 |
)
|
|
@@ -62,6 +76,13 @@ async def get_current_user(
|
|
| 62 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 63 |
detail="Inactive user"
|
| 64 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
# logger.info(f"Auth success: {user.email} ({user.role})") # Too noisy for prod, but good for debug
|
| 67 |
return user
|
|
|
|
| 43 |
headers={"WWW-Authenticate": "Bearer"},
|
| 44 |
)
|
| 45 |
|
| 46 |
+
# Check Cache
|
| 47 |
+
from app.services.cache_service import cache_service
|
| 48 |
+
cache_key = f"user:{user_id}"
|
| 49 |
+
cached_data = await cache_service.get(cache_key)
|
| 50 |
+
if cached_data:
|
| 51 |
+
try:
|
| 52 |
+
# Reconstruct User from cache
|
| 53 |
+
# User is a SQLModel, which is Pydantic v2 compatible
|
| 54 |
+
user = User.model_validate(cached_data)
|
| 55 |
+
return user
|
| 56 |
+
except Exception as e:
|
| 57 |
+
logger.warning(f"Failed to validate cached user: {e}")
|
| 58 |
+
# Fallback to DB
|
| 59 |
+
|
| 60 |
result = await session.execute(
|
| 61 |
select(User).where(User.id == UUID(user_id))
|
| 62 |
)
|
|
|
|
| 76 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 77 |
detail="Inactive user"
|
| 78 |
)
|
| 79 |
+
|
| 80 |
+
# Cache the user (5 minutes)
|
| 81 |
+
try:
|
| 82 |
+
# model_dump(mode='json') serializes datetimes to iso strings
|
| 83 |
+
await cache_service.set(cache_key, user.model_dump(mode='json'), ttl=300)
|
| 84 |
+
except Exception as e:
|
| 85 |
+
logger.error(f"Failed to cache user: {e}")
|
| 86 |
|
| 87 |
# logger.info(f"Auth success: {user.email} ({user.role})") # Too noisy for prod, but good for debug
|
| 88 |
return user
|
backend/app/api/google_calendar.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, Request
|
| 2 |
+
from sqlalchemy.orm import Session
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from app.api.deps import get_db, get_current_user
|
| 7 |
+
from app.services.google_calendar import get_google_calendar_service
|
| 8 |
+
from app.models.tenant import Tenant
|
| 9 |
+
from app.models.user import User
|
| 10 |
+
|
| 11 |
+
router = APIRouter()
|
| 12 |
+
|
| 13 |
+
@router.get("/connect")
|
| 14 |
+
def connect_calendar(
|
| 15 |
+
request: Request,
|
| 16 |
+
db: Session = Depends(get_db),
|
| 17 |
+
current_user: User = Depends(get_current_user),
|
| 18 |
+
redirect_uri: str = None
|
| 19 |
+
):
|
| 20 |
+
"""
|
| 21 |
+
Start the OAuth flow for the current user's tenant.
|
| 22 |
+
Returns the Google Auth URL.
|
| 23 |
+
"""
|
| 24 |
+
if current_user.role != "OWNER":
|
| 25 |
+
raise HTTPException(status_code=403, detail="Only owners can connect calendar")
|
| 26 |
+
|
| 27 |
+
tenant_id = current_user.tenant_id
|
| 28 |
+
service = get_google_calendar_service()
|
| 29 |
+
|
| 30 |
+
# We pass tenant_id as state
|
| 31 |
+
auth_url = service.get_auth_url(tenant_id, redirect_uri)
|
| 32 |
+
return {"url": auth_url}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@router.get("/callback")
|
| 36 |
+
async def callback(
|
| 37 |
+
code: str,
|
| 38 |
+
state: str,
|
| 39 |
+
request: Request,
|
| 40 |
+
db: Session = Depends(get_db)
|
| 41 |
+
# Note: No user auth here usually, as it's a redirect from Google.
|
| 42 |
+
# State contains tenant_id.
|
| 43 |
+
):
|
| 44 |
+
"""
|
| 45 |
+
Handle Google OAuth callback.
|
| 46 |
+
Exchange code for tokens and store in Tenant.
|
| 47 |
+
"""
|
| 48 |
+
try:
|
| 49 |
+
tenant_id = UUID(state)
|
| 50 |
+
except ValueError:
|
| 51 |
+
raise HTTPException(status_code=400, detail="Invalid state parameter")
|
| 52 |
+
|
| 53 |
+
tenant = db.get(Tenant, tenant_id)
|
| 54 |
+
if not tenant:
|
| 55 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 56 |
+
|
| 57 |
+
service = get_google_calendar_service()
|
| 58 |
+
|
| 59 |
+
# The pure redirect_uri used in the flow must match exactly.
|
| 60 |
+
# If frontend sent a custom one, we need to know it here too?
|
| 61 |
+
# Usually we use a fixed config one or extract from request base url.
|
| 62 |
+
# For now, let's assume default from service.
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
tokens = await service.authenticate(code)
|
| 66 |
+
|
| 67 |
+
# Merge with existing config or create new
|
| 68 |
+
# We store the whole token dict
|
| 69 |
+
tenant.google_calendar_config = tokens
|
| 70 |
+
db.add(tenant)
|
| 71 |
+
db.commit()
|
| 72 |
+
db.refresh(tenant)
|
| 73 |
+
|
| 74 |
+
return {"status": "success", "message": "Google Calendar connected"}
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@router.get("/availability")
|
| 81 |
+
async def check_availability(
|
| 82 |
+
start_time: datetime,
|
| 83 |
+
end_time: datetime,
|
| 84 |
+
current_user: User = Depends(get_current_user),
|
| 85 |
+
db: Session = Depends(get_db)
|
| 86 |
+
):
|
| 87 |
+
"""
|
| 88 |
+
Check availability directly from Google Calendar for debugging.
|
| 89 |
+
"""
|
| 90 |
+
tenant = db.get(Tenant, current_user.tenant_id)
|
| 91 |
+
service = get_google_calendar_service()
|
| 92 |
+
|
| 93 |
+
slots = await service.list_free_slots(tenant, start_time, end_time)
|
| 94 |
+
return {"busy": slots}
|
backend/app/api/meta_webhooks.py
CHANGED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Meta Official Webhook Handler (WhatsApp & Instagram).
|
| 3 |
+
Handles verification (GET) and event notifications (POST).
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends, Query
|
| 7 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 8 |
+
from sqlalchemy import select
|
| 9 |
+
from uuid import UUID
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
import httpx
|
| 12 |
+
import logging
|
| 13 |
+
|
| 14 |
+
from app.core.database import get_async_session, async_session_maker
|
| 15 |
+
from app.models.tenant import Tenant
|
| 16 |
+
from app.models.lead import Lead, Message, Conversation, MessageStatus
|
| 17 |
+
from app.services.ai_core import get_ai_core
|
| 18 |
+
from app.core.config import settings
|
| 19 |
+
|
| 20 |
+
# Services
|
| 21 |
+
from app.services.meta_whatsapp import get_whatsapp_cloud_service
|
| 22 |
+
from app.services.meta_instagram import get_instagram_graph_service
|
| 23 |
+
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
router = APIRouter(prefix="/webhook/meta", tags=["Meta Webhooks"])
|
| 26 |
+
|
| 27 |
+
# -------------------------------------------------------------------------
|
| 28 |
+
# VERIFICATION (GET)
|
| 29 |
+
# -------------------------------------------------------------------------
|
| 30 |
+
@router.get("/{tenant_id}")
|
| 31 |
+
async def verify_webhook(
|
| 32 |
+
tenant_id: UUID,
|
| 33 |
+
mode: str = Query(alias="hub.mode"),
|
| 34 |
+
token: str = Query(alias="hub.verify_token"),
|
| 35 |
+
challenge: str = Query(alias="hub.challenge"),
|
| 36 |
+
session: AsyncSession = Depends(get_async_session)
|
| 37 |
+
):
|
| 38 |
+
"""
|
| 39 |
+
Handle Meta Webhook Verification Challenge.
|
| 40 |
+
Meta sends this to verify we own the endpoint.
|
| 41 |
+
"""
|
| 42 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 43 |
+
if not tenant:
|
| 44 |
+
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 45 |
+
|
| 46 |
+
# Check WhatsApp Config first, then Instagram
|
| 47 |
+
wa_verify = tenant.meta_wa_config.get("verify_token") if tenant.meta_wa_config else None
|
| 48 |
+
|
| 49 |
+
# If using same token for both, or checking just one
|
| 50 |
+
# Ideally we match against the configured token
|
| 51 |
+
|
| 52 |
+
if mode == "subscribe" and token == wa_verify:
|
| 53 |
+
logger.info(f"✅ Webhook Verified for Tenant {tenant_id}")
|
| 54 |
+
return int(challenge)
|
| 55 |
+
|
| 56 |
+
raise HTTPException(status_code=403, detail="Verification failed")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# -------------------------------------------------------------------------
|
| 60 |
+
# EVENT NOTIFICATION (POST)
|
| 61 |
+
# -------------------------------------------------------------------------
|
| 62 |
+
@router.post("/{tenant_id}")
|
| 63 |
+
async def handle_meta_webhook(
|
| 64 |
+
tenant_id: UUID,
|
| 65 |
+
request: Request,
|
| 66 |
+
background_tasks: BackgroundTasks,
|
| 67 |
+
session: AsyncSession = Depends(get_async_session)
|
| 68 |
+
):
|
| 69 |
+
"""
|
| 70 |
+
Handle incoming events from Meta (WhatsApp & Instagram).
|
| 71 |
+
"""
|
| 72 |
+
try:
|
| 73 |
+
data = await request.json()
|
| 74 |
+
except Exception as e:
|
| 75 |
+
raise HTTPException(status_code=400, detail="Invalid JSON")
|
| 76 |
+
|
| 77 |
+
# Log incoming (debug)
|
| 78 |
+
# logger.info(f"📩 Meta Webhook for {tenant_id}: {data}")
|
| 79 |
+
|
| 80 |
+
# Determine validation
|
| 81 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 82 |
+
if not tenant:
|
| 83 |
+
return {"status": "ignored", "reason": "tenant_not_found"}
|
| 84 |
+
|
| 85 |
+
# Process in background
|
| 86 |
+
background_tasks.add_task(
|
| 87 |
+
process_meta_event,
|
| 88 |
+
tenant_id=tenant.id,
|
| 89 |
+
payload=data
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
return {"status": "ok"}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
async def process_meta_event(tenant_id: UUID, payload: dict):
|
| 96 |
+
"""
|
| 97 |
+
Parse and process the Meta event payload.
|
| 98 |
+
Identifies if it's WhatsApp or Instagram and routes accordingly.
|
| 99 |
+
"""
|
| 100 |
+
object_type = payload.get("object") # 'whatsapp_business' or 'instagram'
|
| 101 |
+
|
| 102 |
+
if object_type == "whatsapp_business":
|
| 103 |
+
await process_whatsapp_event(tenant_id, payload)
|
| 104 |
+
elif object_type == "instagram":
|
| 105 |
+
# await process_instagram_event(tenant_id, payload)
|
| 106 |
+
pass # TODO: Implement IG
|
| 107 |
+
else:
|
| 108 |
+
logger.warning(f"Unknown Meta object type: {object_type}")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
async def process_whatsapp_event(tenant_id: UUID, payload: dict):
|
| 112 |
+
"""
|
| 113 |
+
Process WhatsApp Business API specific structure.
|
| 114 |
+
"""
|
| 115 |
+
try:
|
| 116 |
+
entry = payload.get("entry", [])[0]
|
| 117 |
+
changes = entry.get("changes", [])[0]
|
| 118 |
+
value = changes.get("value", {})
|
| 119 |
+
|
| 120 |
+
# Check for messages
|
| 121 |
+
if "messages" not in value:
|
| 122 |
+
return # Status update or other event
|
| 123 |
+
|
| 124 |
+
message = value["messages"][0]
|
| 125 |
+
contact = value.get("contacts", [])[0] if "contacts" in value else {}
|
| 126 |
+
|
| 127 |
+
sender_id = message.get("from") # Phone number
|
| 128 |
+
sender_name = contact.get("profile", {}).get("name", f"User {sender_id}")
|
| 129 |
+
|
| 130 |
+
msg_type = message.get("type")
|
| 131 |
+
text_body = ""
|
| 132 |
+
media_url = None
|
| 133 |
+
|
| 134 |
+
if msg_type == "text":
|
| 135 |
+
text_body = message["text"]["body"]
|
| 136 |
+
elif msg_type == "audio":
|
| 137 |
+
# TODO: Handle media ID download/transcription
|
| 138 |
+
text_body = "[Voice Message]"
|
| 139 |
+
else:
|
| 140 |
+
text_body = f"[{msg_type} message]"
|
| 141 |
+
|
| 142 |
+
# Call generic processor
|
| 143 |
+
await process_incoming_message(
|
| 144 |
+
tenant_id=tenant_id,
|
| 145 |
+
channel="whatsapp",
|
| 146 |
+
sender_id=sender_id,
|
| 147 |
+
sender_name=sender_name,
|
| 148 |
+
text=text_body,
|
| 149 |
+
media_url=media_url,
|
| 150 |
+
is_voice=(msg_type == "audio")
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
except (IndexError, KeyError) as e:
|
| 154 |
+
logger.error(f"Error parsing WhatsApp payload: {e}")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
async def process_incoming_message(
|
| 158 |
+
tenant_id: UUID,
|
| 159 |
+
channel: str,
|
| 160 |
+
sender_id: str,
|
| 161 |
+
sender_name: str,
|
| 162 |
+
text: str,
|
| 163 |
+
media_url: str = None,
|
| 164 |
+
is_voice: bool = False
|
| 165 |
+
):
|
| 166 |
+
"""
|
| 167 |
+
Generic logic to save message -> Generate AI Response -> Send back.
|
| 168 |
+
(Merged logic from old evolution_webhook)
|
| 169 |
+
"""
|
| 170 |
+
from app.services.llm_client import get_llm_client
|
| 171 |
+
|
| 172 |
+
logger.info(f"🔄 Processing {channel} message from {sender_id}: {text[:50]}...")
|
| 173 |
+
|
| 174 |
+
async with async_session_maker() as session:
|
| 175 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 176 |
+
if not tenant:
|
| 177 |
+
return
|
| 178 |
+
|
| 179 |
+
# 1. FIND/CREATE LEAD
|
| 180 |
+
stmt = select(Lead).where(Lead.tenant_id == tenant.id, Lead.whatsapp_id == sender_id)
|
| 181 |
+
result = await session.execute(stmt)
|
| 182 |
+
lead = result.scalar_one_or_none()
|
| 183 |
+
|
| 184 |
+
if not lead:
|
| 185 |
+
lead = Lead(
|
| 186 |
+
tenant_id=tenant.id,
|
| 187 |
+
name=sender_name,
|
| 188 |
+
whatsapp_id=sender_id,
|
| 189 |
+
status="NEW",
|
| 190 |
+
processing_status="idle"
|
| 191 |
+
)
|
| 192 |
+
session.add(lead)
|
| 193 |
+
await session.flush()
|
| 194 |
+
|
| 195 |
+
lead.last_message_at = datetime.utcnow()
|
| 196 |
+
lead.processing_status = "analyzing"
|
| 197 |
+
session.add(lead)
|
| 198 |
+
|
| 199 |
+
# 2. FIND/CREATE CONVERSATION
|
| 200 |
+
stmt = select(Conversation).where(
|
| 201 |
+
Conversation.tenant_id == tenant.id,
|
| 202 |
+
Conversation.lead_id == lead.id
|
| 203 |
+
)
|
| 204 |
+
result = await session.execute(stmt)
|
| 205 |
+
conversation = result.scalar_one_or_none() # Assuming 1 active check logic simplified
|
| 206 |
+
|
| 207 |
+
if not conversation:
|
| 208 |
+
conversation = Conversation(
|
| 209 |
+
tenant_id=tenant.id,
|
| 210 |
+
lead_id=lead.id,
|
| 211 |
+
channel=channel,
|
| 212 |
+
is_active=True
|
| 213 |
+
)
|
| 214 |
+
session.add(conversation)
|
| 215 |
+
await session.flush()
|
| 216 |
+
|
| 217 |
+
# 3. SAVE USER MESSAGE
|
| 218 |
+
user_msg = Message(
|
| 219 |
+
tenant_id=tenant.id,
|
| 220 |
+
conversation_id=conversation.id,
|
| 221 |
+
sender_type="user",
|
| 222 |
+
content=text
|
| 223 |
+
)
|
| 224 |
+
session.add(user_msg)
|
| 225 |
+
await session.commit()
|
| 226 |
+
|
| 227 |
+
# 4. GENERATE AI RESPONSE
|
| 228 |
+
ai_core = get_ai_core()
|
| 229 |
+
|
| 230 |
+
# Fetch history
|
| 231 |
+
stmt = select(Message).where(Message.conversation_id == conversation.id).order_by(Message.created_at)
|
| 232 |
+
history = (await session.execute(stmt)).scalars().all()
|
| 233 |
+
|
| 234 |
+
response = await ai_core.generate_sales_response(
|
| 235 |
+
session=session,
|
| 236 |
+
tenant=tenant,
|
| 237 |
+
lead=lead,
|
| 238 |
+
user_message=text,
|
| 239 |
+
conversation_history=list(history)
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
response_text = response["text"]
|
| 243 |
+
|
| 244 |
+
# Parse Booking/Images (simplified for now)
|
| 245 |
+
# TODO: Add the Visual Commerce logic back
|
| 246 |
+
|
| 247 |
+
# 5. SAVE AI MESSAGE
|
| 248 |
+
ai_msg = Message(
|
| 249 |
+
tenant_id=tenant.id,
|
| 250 |
+
conversation_id=conversation.id,
|
| 251 |
+
sender_type="ai",
|
| 252 |
+
content=response_text,
|
| 253 |
+
status=MessageStatus.PENDING,
|
| 254 |
+
model_used=settings.GEMINI_MODEL
|
| 255 |
+
)
|
| 256 |
+
session.add(ai_msg)
|
| 257 |
+
await session.commit()
|
| 258 |
+
|
| 259 |
+
# 6. SEND RESPONSE VIA OFFICIAL API
|
| 260 |
+
success = False
|
| 261 |
+
try:
|
| 262 |
+
wa_service = get_whatsapp_cloud_service()
|
| 263 |
+
|
| 264 |
+
# DECIDE: SEND VOICE OR TEXT?
|
| 265 |
+
# Trigger voice if user sent voice, OR if specific keyword in text?
|
| 266 |
+
# For now: purely reactive. If input was voice -> output is voice.
|
| 267 |
+
should_send_voice = is_voice and settings.OPENAI_API_KEY
|
| 268 |
+
|
| 269 |
+
if channel == "whatsapp":
|
| 270 |
+
if should_send_voice:
|
| 271 |
+
try:
|
| 272 |
+
# 1. Generate Audio
|
| 273 |
+
llm_client = get_llm_client()
|
| 274 |
+
audio_bytes = await llm_client.generate_speech(response_text)
|
| 275 |
+
|
| 276 |
+
# 2. Upload to WhatsApp
|
| 277 |
+
media_id = await wa_service.upload_media(tenant, audio_bytes)
|
| 278 |
+
|
| 279 |
+
# 3. Send
|
| 280 |
+
await wa_service.send_audio_message(tenant, sender_id, media_id)
|
| 281 |
+
logger.info(f"🗣️ Sent Voice Reply to {sender_id}")
|
| 282 |
+
success = True
|
| 283 |
+
except Exception as ve:
|
| 284 |
+
logger.error(f"Voice generation/send failed: {ve}. Falling back to text.")
|
| 285 |
+
# Fallback to text
|
| 286 |
+
await wa_service.send_text_message(tenant, sender_id, response_text)
|
| 287 |
+
success = True
|
| 288 |
+
else:
|
| 289 |
+
await wa_service.send_text_message(
|
| 290 |
+
tenant=tenant,
|
| 291 |
+
to_phone=sender_id,
|
| 292 |
+
text=response_text
|
| 293 |
+
)
|
| 294 |
+
success = True
|
| 295 |
+
|
| 296 |
+
# elif channel == "instagram": ...
|
| 297 |
+
|
| 298 |
+
ai_msg.status = MessageStatus.SENT if success else MessageStatus.FAILED
|
| 299 |
+
lead.processing_status = "idle"
|
| 300 |
+
session.add(ai_msg)
|
| 301 |
+
session.add(lead)
|
| 302 |
+
await session.commit()
|
| 303 |
+
|
| 304 |
+
except Exception as e:
|
| 305 |
+
logger.error(f"❌ Failed to send reply: {e}")
|
| 306 |
+
ai_msg.status = MessageStatus.FAILED
|
| 307 |
+
session.add(ai_msg)
|
| 308 |
+
await session.commit()
|
backend/app/api/voice.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, Response
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from app.services.voice_service import voice_service
|
| 4 |
+
from app.api.deps import get_current_user
|
| 5 |
+
from app.models.user import User
|
| 6 |
+
|
| 7 |
+
router = APIRouter()
|
| 8 |
+
|
| 9 |
+
class VoiceRequest(BaseModel):
|
| 10 |
+
text: str
|
| 11 |
+
voice: str = "onyx"
|
| 12 |
+
|
| 13 |
+
@router.post("/speak")
|
| 14 |
+
async def generate_speech(
|
| 15 |
+
request: VoiceRequest,
|
| 16 |
+
current_user: User = Depends(get_current_user)
|
| 17 |
+
):
|
| 18 |
+
"""
|
| 19 |
+
Generate audio speech from text.
|
| 20 |
+
Returns an audio/mpeg stream.
|
| 21 |
+
"""
|
| 22 |
+
audio_content = await voice_service.generate_audio(request.text, request.voice)
|
| 23 |
+
|
| 24 |
+
return Response(
|
| 25 |
+
content=audio_content,
|
| 26 |
+
media_type="audio/mpeg",
|
| 27 |
+
headers={
|
| 28 |
+
"Content-Disposition": "attachment; filename=speech.mp3"
|
| 29 |
+
}
|
| 30 |
+
)
|
backend/app/api/websocket_voice.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends, Query
|
| 2 |
+
from app.api.deps import get_current_user
|
| 3 |
+
from app.core.security import decode_access_token
|
| 4 |
+
from app.services.voice_manager import voice_manager, VoiceSession
|
| 5 |
+
from uuid import uuid4
|
| 6 |
+
import logging
|
| 7 |
+
import json
|
| 8 |
+
|
| 9 |
+
router = APIRouter()
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
@router.websocket("/stream")
|
| 13 |
+
async def voice_stream(
|
| 14 |
+
websocket: WebSocket,
|
| 15 |
+
token: str = Query(...)
|
| 16 |
+
):
|
| 17 |
+
"""
|
| 18 |
+
Real-time voice streaming endpoint.
|
| 19 |
+
Client sends audio chunks (binary).
|
| 20 |
+
Server sends audio chunks (binary) + metadata (text).
|
| 21 |
+
"""
|
| 22 |
+
await websocket.accept()
|
| 23 |
+
|
| 24 |
+
# Authenticate via Token (since WS headers are hard in standard JS WebSocket)
|
| 25 |
+
try:
|
| 26 |
+
payload = decode_access_token(token)
|
| 27 |
+
user_id = payload.get("sub")
|
| 28 |
+
# In a real app we'd fetch the user and tenant object here.
|
| 29 |
+
# For speed: decode tenant_id if available or assume 'default' for now.
|
| 30 |
+
# But we need tenant_id for context.
|
| 31 |
+
# For MVP: Use a dummy tenant or extract from token if custom claim.
|
| 32 |
+
session_id = str(uuid4())
|
| 33 |
+
# Mock tenant ID - assume single tenant demo or extracted properly
|
| 34 |
+
tenant_id = "demo-tenant"
|
| 35 |
+
|
| 36 |
+
session = VoiceSession(session_id, tenant_id)
|
| 37 |
+
logger.info(f"🔌 WS Connected: {user_id} (Session {session_id})")
|
| 38 |
+
|
| 39 |
+
await websocket.send_text(json.dumps({"status": "connected", "session_id": session_id}))
|
| 40 |
+
|
| 41 |
+
except Exception as e:
|
| 42 |
+
logger.error(f"WS Auth failed: {e}")
|
| 43 |
+
await websocket.close(code=4003)
|
| 44 |
+
return
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
while True:
|
| 48 |
+
# Receive message (can be bytes or text)
|
| 49 |
+
message = await websocket.receive()
|
| 50 |
+
|
| 51 |
+
if "bytes" in message:
|
| 52 |
+
chunk = message["bytes"]
|
| 53 |
+
# Process audio chunk (VAD, buffer)
|
| 54 |
+
# Currently returns None until turn complete (mock VAD)
|
| 55 |
+
|
| 56 |
+
# If we want streaming VAD, we'd check here.
|
| 57 |
+
# For MVP, assume client sends small chunks.
|
| 58 |
+
# VoiceManager currently adds to buffer.
|
| 59 |
+
await voice_manager.process_audio_chunk(session, chunk)
|
| 60 |
+
|
| 61 |
+
elif "text" in message:
|
| 62 |
+
data = json.loads(message["text"])
|
| 63 |
+
msg_type = data.get("type")
|
| 64 |
+
|
| 65 |
+
# Explicit "Turn Finished" signal from client VAD
|
| 66 |
+
if msg_type == "commit":
|
| 67 |
+
logger.info("🎤 Client committed turn.")
|
| 68 |
+
# Force process
|
| 69 |
+
await websocket.send_text(json.dumps({"status": "thinking"}))
|
| 70 |
+
|
| 71 |
+
audio_response = await voice_manager.process_turn(session)
|
| 72 |
+
|
| 73 |
+
if audio_response:
|
| 74 |
+
await websocket.send_text(json.dumps({"status": "speaking"}))
|
| 75 |
+
# Send audio as binary
|
| 76 |
+
await websocket.send_bytes(audio_response)
|
| 77 |
+
await websocket.send_text(json.dumps({"status": "listening"}))
|
| 78 |
+
else:
|
| 79 |
+
await websocket.send_text(json.dumps({"status": "error", "message": "No response"}))
|
| 80 |
+
await websocket.send_text(json.dumps({"status": "listening"}))
|
| 81 |
+
|
| 82 |
+
elif msg_type == "ping":
|
| 83 |
+
await websocket.send_text(json.dumps({"type": "pong"}))
|
| 84 |
+
|
| 85 |
+
except WebSocketDisconnect:
|
| 86 |
+
logger.info(f"🔌 WS Disconnected: {session_id}")
|
| 87 |
+
except Exception as e:
|
| 88 |
+
logger.error(f"WS Error: {e}")
|
| 89 |
+
try:
|
| 90 |
+
await websocket.close()
|
| 91 |
+
except:
|
| 92 |
+
pass
|
backend/app/core/config.py
CHANGED
|
@@ -97,6 +97,13 @@ class Settings(BaseSettings):
|
|
| 97 |
LINKEDIN_API_KEY: Optional[str] = None
|
| 98 |
LINKEDIN_EMAIL: Optional[str] = None
|
| 99 |
LINKEDIN_PASSWORD: Optional[str] = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
def get_allowed_origins(self) -> List[str]:
|
| 102 |
"""Parse ALLOWED_ORIGINS from comma-separated string."""
|
|
|
|
| 97 |
LINKEDIN_API_KEY: Optional[str] = None
|
| 98 |
LINKEDIN_EMAIL: Optional[str] = None
|
| 99 |
LINKEDIN_PASSWORD: Optional[str] = None
|
| 100 |
+
|
| 101 |
+
# Stripe (Payments)
|
| 102 |
+
STRIPE_SECRET_KEY: Optional[str] = None
|
| 103 |
+
STRIPE_WEBHOOK_SECRET: Optional[str] = None
|
| 104 |
+
STRIPE_PRICE_START: Optional[str] = "price_start_month"
|
| 105 |
+
STRIPE_PRICE_GROWTH: Optional[str] = "price_growth_month"
|
| 106 |
+
STRIPE_PRICE_UNLIMITED: Optional[str] = "price_unlimited_month"
|
| 107 |
|
| 108 |
def get_allowed_origins(self) -> List[str]:
|
| 109 |
"""Parse ALLOWED_ORIGINS from comma-separated string."""
|
backend/app/core/redis.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import redis.asyncio as redis
|
| 2 |
+
from app.core.config import settings
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
logger = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
class RedisClient:
|
| 8 |
+
_instance: redis.Redis = None
|
| 9 |
+
|
| 10 |
+
@classmethod
|
| 11 |
+
def get_instance(cls) -> redis.Redis:
|
| 12 |
+
if cls._instance is None:
|
| 13 |
+
# Create connection pool
|
| 14 |
+
pool = redis.ConnectionPool.from_url(
|
| 15 |
+
settings.REDIS_URL,
|
| 16 |
+
encoding="utf-8",
|
| 17 |
+
decode_responses=True
|
| 18 |
+
)
|
| 19 |
+
cls._instance = redis.Redis(connection_pool=pool)
|
| 20 |
+
logger.info("Redis client initialized.")
|
| 21 |
+
return cls._instance
|
| 22 |
+
|
| 23 |
+
@classmethod
|
| 24 |
+
async def close(cls):
|
| 25 |
+
if cls._instance:
|
| 26 |
+
await cls._instance.close()
|
| 27 |
+
logger.info("Redis client closed.")
|
| 28 |
+
|
| 29 |
+
def get_redis() -> redis.Redis:
|
| 30 |
+
return RedisClient.get_instance()
|
backend/app/main.py
CHANGED
|
@@ -7,7 +7,7 @@ from app.core.config import settings
|
|
| 7 |
from app.core.database import init_pgvector
|
| 8 |
from app.core.logging import configure_logging, get_logger
|
| 9 |
from app.middleware.request_id import RequestIDMiddleware
|
| 10 |
-
from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, evolution_webhook, telegram_webhook, partners, notifications, products, bookings, jobs, system
|
| 11 |
|
| 12 |
# ... (omitted lines)
|
| 13 |
|
|
@@ -167,7 +167,8 @@ app.add_middleware(RequestIDMiddleware)
|
|
| 167 |
# Include API routers with /api/v1 prefix
|
| 168 |
app.include_router(auth.router, prefix="/api/v1")
|
| 169 |
app.include_router(webhook.router, prefix="/api/v1") # Email webhook
|
| 170 |
-
app.include_router(
|
|
|
|
| 171 |
app.include_router(telegram_webhook.router, prefix="/api/v1") # Telegram webhook
|
| 172 |
# app.include_router(linkedin_webhook.router, prefix="/api/v1") # LinkedIn webhook (TODO: Implement)
|
| 173 |
app.include_router(leads.router, prefix="/api/v1")
|
|
@@ -190,6 +191,9 @@ app.include_router(bookings.router, prefix="/api/v1") # Products & Catalog Mana
|
|
| 190 |
app.include_router(jobs.router, prefix="/api/v1")
|
| 191 |
app.include_router(system.router, prefix="/api/v1") # System Announcements
|
| 192 |
# app.include_router(oauth.router, prefix="/api/v1") # OAuth removed
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
|
| 195 |
@app.on_event("startup")
|
|
|
|
| 7 |
from app.core.database import init_pgvector
|
| 8 |
from app.core.logging import configure_logging, get_logger
|
| 9 |
from app.middleware.request_id import RequestIDMiddleware
|
| 10 |
+
from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, evolution_webhook, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice
|
| 11 |
|
| 12 |
# ... (omitted lines)
|
| 13 |
|
|
|
|
| 167 |
# Include API routers with /api/v1 prefix
|
| 168 |
app.include_router(auth.router, prefix="/api/v1")
|
| 169 |
app.include_router(webhook.router, prefix="/api/v1") # Email webhook
|
| 170 |
+
app.include_router(meta_webhooks.router, prefix="/api/v1") # Official Meta API (WA/IG)
|
| 171 |
+
# app.include_router(evolution_webhook.router, prefix="/api/v1") # DEPRECATED: Evolution API
|
| 172 |
app.include_router(telegram_webhook.router, prefix="/api/v1") # Telegram webhook
|
| 173 |
# app.include_router(linkedin_webhook.router, prefix="/api/v1") # LinkedIn webhook (TODO: Implement)
|
| 174 |
app.include_router(leads.router, prefix="/api/v1")
|
|
|
|
| 191 |
app.include_router(jobs.router, prefix="/api/v1")
|
| 192 |
app.include_router(system.router, prefix="/api/v1") # System Announcements
|
| 193 |
# app.include_router(oauth.router, prefix="/api/v1") # OAuth removed
|
| 194 |
+
app.include_router(voice.router, prefix="/api/v1/voice", tags=["Voice"])
|
| 195 |
+
app.include_router(websocket_voice.router, prefix="/ws/voice", tags=["Voice Stream"])
|
| 196 |
+
app.include_router(google_calendar.router, prefix="/api/v1/google-calendar", tags=["Google Calendar"])
|
| 197 |
|
| 198 |
|
| 199 |
@app.on_event("startup")
|
backend/app/models/knowledge.py
CHANGED
|
@@ -28,7 +28,7 @@ class KnowledgeBase(SQLModel, table=True):
|
|
| 28 |
# pgvector operators will work when we cast in SQL
|
| 29 |
embedding: Optional[str] = Field(
|
| 30 |
default=None,
|
| 31 |
-
sa_column=Column(TEXT) if not PGVECTOR_AVAILABLE else Column(Vector(
|
| 32 |
)
|
| 33 |
|
| 34 |
# Metadata
|
|
|
|
| 28 |
# pgvector operators will work when we cast in SQL
|
| 29 |
embedding: Optional[str] = Field(
|
| 30 |
default=None,
|
| 31 |
+
sa_column=Column(TEXT) if not PGVECTOR_AVAILABLE else Column(Vector(1536))
|
| 32 |
)
|
| 33 |
|
| 34 |
# Metadata
|
backend/app/models/tenant.py
CHANGED
|
@@ -39,6 +39,11 @@ class Tenant(SQLModel, table=True):
|
|
| 39 |
subscription_start: datetime = Field(default_factory=datetime.utcnow)
|
| 40 |
subscription_end: Optional[datetime] = None
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
# Partner relationship
|
| 43 |
partner_ref_id: Optional[UUID] = Field(default=None, foreign_key="partners.id")
|
| 44 |
|
|
@@ -71,6 +76,13 @@ class Tenant(SQLModel, table=True):
|
|
| 71 |
|
| 72 |
# AI Persona (New)
|
| 73 |
ai_identity: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {name, role, tone, intro}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
# AI Brain Settings (from migrations)
|
| 76 |
ai_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
|
|
|
| 39 |
subscription_start: datetime = Field(default_factory=datetime.utcnow)
|
| 40 |
subscription_end: Optional[datetime] = None
|
| 41 |
|
| 42 |
+
# Stripe
|
| 43 |
+
stripe_customer_id: Optional[str] = Field(default=None, index=True)
|
| 44 |
+
stripe_subscription_id: Optional[str] = Field(default=None)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
# Partner relationship
|
| 48 |
partner_ref_id: Optional[UUID] = Field(default=None, foreign_key="partners.id")
|
| 49 |
|
|
|
|
| 76 |
|
| 77 |
# AI Persona (New)
|
| 78 |
ai_identity: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {name, role, tone, intro}
|
| 79 |
+
|
| 80 |
+
# Meta Official API Configs (New)
|
| 81 |
+
meta_wa_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {phone_number_id, waba_id, access_token, verify_token}
|
| 82 |
+
meta_ig_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {page_id, ig_user_id, access_token}
|
| 83 |
+
|
| 84 |
+
# Google Calendar Config
|
| 85 |
+
google_calendar_config: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON)) # {refresh_token, access_token, token_expiry, calendar_id}
|
| 86 |
|
| 87 |
# AI Brain Settings (from migrations)
|
| 88 |
ai_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
backend/app/services/ai_memory_manager.py
CHANGED
|
@@ -81,6 +81,12 @@ class AIMemoryManager:
|
|
| 81 |
token_count = len(system_instruction) // 4 # Rough estimate
|
| 82 |
logger.info(f"📄 Compiled Context Size: ~{len(system_instruction)} chars (~{token_count} tokens)")
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
# 3. UPLOAD TO GOOGLE CACHE
|
| 85 |
# TTL: 1 hour (standard). We will refresh it on activity.
|
| 86 |
# Using gemini-2.5-flash (requires billing enabled)
|
|
|
|
| 81 |
token_count = len(system_instruction) // 4 # Rough estimate
|
| 82 |
logger.info(f"📄 Compiled Context Size: ~{len(system_instruction)} chars (~{token_count} tokens)")
|
| 83 |
|
| 84 |
+
# CHECK: Minimum token count for caching is ~1000 (varies by model, but usually 1024 or 32k min)
|
| 85 |
+
# If too small, we skip caching and let AI Core inject it manually (Standard RAG).
|
| 86 |
+
if token_count < 1000:
|
| 87 |
+
logger.warning(f"⚠️ Content too small for caching ({token_count} < 1000 tokens). Skipping memory creation.")
|
| 88 |
+
return None
|
| 89 |
+
|
| 90 |
# 3. UPLOAD TO GOOGLE CACHE
|
| 91 |
# TTL: 1 hour (standard). We will refresh it on activity.
|
| 92 |
# Using gemini-2.5-flash (requires billing enabled)
|
backend/app/services/booking_service.py
CHANGED
|
@@ -64,7 +64,16 @@ class BookingService:
|
|
| 64 |
Checks:
|
| 65 |
1. Defined Availability rules (day of week)
|
| 66 |
2. Existing Appointments (conflicts)
|
|
|
|
| 67 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
# 1. Get Availability Rule for this day of week
|
| 69 |
day_of_week = target_date.weekday()
|
| 70 |
stmt = select(Availability).where(
|
|
@@ -78,10 +87,9 @@ class BookingService:
|
|
| 78 |
if not rules:
|
| 79 |
return []
|
| 80 |
|
| 81 |
-
service = await session.get(Service, service_id)
|
| 82 |
duration = timedelta(minutes=service.duration_minutes)
|
| 83 |
|
| 84 |
-
# 2. Get Existing Appointments
|
| 85 |
start_of_day = datetime.combine(target_date, time.min)
|
| 86 |
end_of_day = datetime.combine(target_date, time.max)
|
| 87 |
|
|
@@ -94,7 +102,33 @@ class BookingService:
|
|
| 94 |
result_apps = await session.execute(stmt_apps)
|
| 95 |
appointments = result_apps.scalars().all()
|
| 96 |
|
| 97 |
-
# 3.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
slots = []
|
| 99 |
for rule in rules:
|
| 100 |
current_time = datetime.combine(target_date, rule.start_time)
|
|
@@ -105,12 +139,19 @@ class BookingService:
|
|
| 105 |
slot_end = current_time + duration
|
| 106 |
is_free = True
|
| 107 |
|
|
|
|
| 108 |
for app in appointments:
|
| 109 |
-
# Overlap check
|
| 110 |
if not (slot_end <= app.start_time or current_time >= app.end_time):
|
| 111 |
is_free = False
|
| 112 |
break
|
| 113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
if is_free:
|
| 115 |
# Don't return slots in the past
|
| 116 |
if current_time > datetime.utcnow():
|
|
@@ -128,15 +169,19 @@ class BookingService:
|
|
| 128 |
start_time: datetime
|
| 129 |
) -> Appointment:
|
| 130 |
"""
|
| 131 |
-
Book a slot.
|
| 132 |
"""
|
|
|
|
| 133 |
service = await session.get(Service, service_id)
|
| 134 |
if not service:
|
| 135 |
raise ValueError("Service not found")
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
| 137 |
end_time = start_time + timedelta(minutes=service.duration_minutes)
|
| 138 |
|
| 139 |
-
# Double check conflict
|
| 140 |
stmt = select(Appointment).where(
|
| 141 |
Appointment.service_id == service_id,
|
| 142 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
|
@@ -145,8 +190,9 @@ class BookingService:
|
|
| 145 |
)
|
| 146 |
result = await session.execute(stmt)
|
| 147 |
if result.first():
|
| 148 |
-
raise ValueError("Slot already taken")
|
| 149 |
|
|
|
|
| 150 |
appointment = Appointment(
|
| 151 |
tenant_id=service.tenant_id,
|
| 152 |
service_id=service_id,
|
|
@@ -160,6 +206,35 @@ class BookingService:
|
|
| 160 |
await session.commit()
|
| 161 |
await session.refresh(appointment)
|
| 162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
return appointment
|
| 164 |
|
| 165 |
# Singleton
|
|
|
|
| 64 |
Checks:
|
| 65 |
1. Defined Availability rules (day of week)
|
| 66 |
2. Existing Appointments (conflicts)
|
| 67 |
+
3. Google Calendar Busy Slots (if connected)
|
| 68 |
"""
|
| 69 |
+
# 0. Get Service & Tenant
|
| 70 |
+
service = await session.get(Service, service_id)
|
| 71 |
+
if not service:
|
| 72 |
+
return []
|
| 73 |
+
|
| 74 |
+
from app.models.tenant import Tenant
|
| 75 |
+
tenant = await session.get(Tenant, service.tenant_id)
|
| 76 |
+
|
| 77 |
# 1. Get Availability Rule for this day of week
|
| 78 |
day_of_week = target_date.weekday()
|
| 79 |
stmt = select(Availability).where(
|
|
|
|
| 87 |
if not rules:
|
| 88 |
return []
|
| 89 |
|
|
|
|
| 90 |
duration = timedelta(minutes=service.duration_minutes)
|
| 91 |
|
| 92 |
+
# 2. Get Existing Internal Appointments
|
| 93 |
start_of_day = datetime.combine(target_date, time.min)
|
| 94 |
end_of_day = datetime.combine(target_date, time.max)
|
| 95 |
|
|
|
|
| 102 |
result_apps = await session.execute(stmt_apps)
|
| 103 |
appointments = result_apps.scalars().all()
|
| 104 |
|
| 105 |
+
# 3. Get Google Calendar Busy Slots
|
| 106 |
+
google_busy_intervals = []
|
| 107 |
+
try:
|
| 108 |
+
from app.services.google_calendar import get_google_calendar_service
|
| 109 |
+
gc_service = get_google_calendar_service()
|
| 110 |
+
# Only if configured
|
| 111 |
+
if tenant.google_calendar_config:
|
| 112 |
+
busy_data = await gc_service.list_free_slots(tenant, start_of_day, end_of_day)
|
| 113 |
+
# Format: [{'start': '2023-10-27T10:00:00Z', 'end': '...'}]
|
| 114 |
+
for item in busy_data:
|
| 115 |
+
# Convert to datetime (simplified, assuming ISO/UTC)
|
| 116 |
+
# Use fromisoformat which handles "Z" if py3.11+, otherwise replace Z
|
| 117 |
+
start_str = item['start'].replace('Z', '+00:00')
|
| 118 |
+
end_str = item['end'].replace('Z', '+00:00')
|
| 119 |
+
b_start = datetime.fromisoformat(start_str)
|
| 120 |
+
b_end = datetime.fromisoformat(end_str)
|
| 121 |
+
# Convert to naive if internal app uses naive UTC (MicroFunnel seems to usage naive UTC)
|
| 122 |
+
# Or ensure comparison is timezone-aware.
|
| 123 |
+
# Best practice: make everything offset-naive UTC for comparison if app uses naive.
|
| 124 |
+
# App uses `datetime.utcnow()` which is naive.
|
| 125 |
+
b_start = b_start.replace(tzinfo=None)
|
| 126 |
+
b_end = b_end.replace(tzinfo=None)
|
| 127 |
+
google_busy_intervals.append((b_start, b_end))
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.error(f"Failed to sync Google Calendar availability: {e}")
|
| 130 |
+
|
| 131 |
+
# 4. Generate Slots
|
| 132 |
slots = []
|
| 133 |
for rule in rules:
|
| 134 |
current_time = datetime.combine(target_date, rule.start_time)
|
|
|
|
| 139 |
slot_end = current_time + duration
|
| 140 |
is_free = True
|
| 141 |
|
| 142 |
+
# Check Internal Apps
|
| 143 |
for app in appointments:
|
|
|
|
| 144 |
if not (slot_end <= app.start_time or current_time >= app.end_time):
|
| 145 |
is_free = False
|
| 146 |
break
|
| 147 |
|
| 148 |
+
# Check Google Calendar
|
| 149 |
+
if is_free:
|
| 150 |
+
for g_start, g_end in google_busy_intervals:
|
| 151 |
+
if not (slot_end <= g_start or current_time >= g_end):
|
| 152 |
+
is_free = False
|
| 153 |
+
break
|
| 154 |
+
|
| 155 |
if is_free:
|
| 156 |
# Don't return slots in the past
|
| 157 |
if current_time > datetime.utcnow():
|
|
|
|
| 169 |
start_time: datetime
|
| 170 |
) -> Appointment:
|
| 171 |
"""
|
| 172 |
+
Book a slot. Syncs to Google Calendar.
|
| 173 |
"""
|
| 174 |
+
# Get Service & Tenant
|
| 175 |
service = await session.get(Service, service_id)
|
| 176 |
if not service:
|
| 177 |
raise ValueError("Service not found")
|
| 178 |
+
|
| 179 |
+
from app.models.tenant import Tenant
|
| 180 |
+
tenant = await session.get(Tenant, service.tenant_id)
|
| 181 |
+
|
| 182 |
end_time = start_time + timedelta(minutes=service.duration_minutes)
|
| 183 |
|
| 184 |
+
# Double check conflict (Internal)
|
| 185 |
stmt = select(Appointment).where(
|
| 186 |
Appointment.service_id == service_id,
|
| 187 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
|
|
|
| 190 |
)
|
| 191 |
result = await session.execute(stmt)
|
| 192 |
if result.first():
|
| 193 |
+
raise ValueError("Slot already taken (Internal)")
|
| 194 |
|
| 195 |
+
# Create Internal Appointment
|
| 196 |
appointment = Appointment(
|
| 197 |
tenant_id=service.tenant_id,
|
| 198 |
service_id=service_id,
|
|
|
|
| 206 |
await session.commit()
|
| 207 |
await session.refresh(appointment)
|
| 208 |
|
| 209 |
+
# Sync to Google Calendar
|
| 210 |
+
try:
|
| 211 |
+
if tenant.google_calendar_config:
|
| 212 |
+
from app.services.google_calendar import get_google_calendar_service
|
| 213 |
+
gc_service = get_google_calendar_service()
|
| 214 |
+
|
| 215 |
+
# Fetch lead details
|
| 216 |
+
lead = await session.get(Lead, lead_id)
|
| 217 |
+
summary = f"Meeting with {lead.name} ({service.name})"
|
| 218 |
+
description = f"MicroFunnel Booking\nLead: {lead.name}\nPhone: {lead.whatsapp_id}\nService: {service.name}"
|
| 219 |
+
|
| 220 |
+
# TODO: If lead has email, add as attendee?
|
| 221 |
+
# attendees = [lead.email] if lead.email else []
|
| 222 |
+
|
| 223 |
+
event_id = await gc_service.create_event(
|
| 224 |
+
tenant=tenant,
|
| 225 |
+
start_dt=appointment.start_time,
|
| 226 |
+
end_dt=appointment.end_time,
|
| 227 |
+
summary=summary,
|
| 228 |
+
description=description
|
| 229 |
+
)
|
| 230 |
+
logger.info(f"Synced appointment {appointment.id} to Google Calendar: {event_id}")
|
| 231 |
+
|
| 232 |
+
except Exception as e:
|
| 233 |
+
logger.error(f"Failed to sync booking to Google Calendar: {e}")
|
| 234 |
+
# We don't rollback the internal booking?
|
| 235 |
+
# Ideally we warn, or maybe we should rollback?
|
| 236 |
+
# For now, keep internal booking but log error.
|
| 237 |
+
|
| 238 |
return appointment
|
| 239 |
|
| 240 |
# Singleton
|
backend/app/services/cache_service.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from typing import Any, Optional, Union
|
| 3 |
+
import logging
|
| 4 |
+
from app.core.redis import get_redis
|
| 5 |
+
from redis.exceptions import ConnectionError, TimeoutError
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
class CacheService:
|
| 10 |
+
def __init__(self):
|
| 11 |
+
self.use_redis = True
|
| 12 |
+
self._memory_cache = {} # Fallback
|
| 13 |
+
|
| 14 |
+
async def get(self, key: str) -> Optional[Any]:
|
| 15 |
+
if self.use_redis:
|
| 16 |
+
try:
|
| 17 |
+
redis = get_redis()
|
| 18 |
+
val = await redis.get(key)
|
| 19 |
+
if val:
|
| 20 |
+
try:
|
| 21 |
+
return json.loads(val)
|
| 22 |
+
except json.JSONDecodeError:
|
| 23 |
+
return val
|
| 24 |
+
return None
|
| 25 |
+
except (ConnectionError, TimeoutError, OSError):
|
| 26 |
+
logger.warning("Redis connection failed. Switch to memory fallback (temporary).")
|
| 27 |
+
self.use_redis = False
|
| 28 |
+
return self._memory_cache.get(key)
|
| 29 |
+
except Exception as e:
|
| 30 |
+
logger.error(f"Cache get error: {e}")
|
| 31 |
+
return None
|
| 32 |
+
else:
|
| 33 |
+
return self._memory_cache.get(key)
|
| 34 |
+
|
| 35 |
+
async def set(self, key: str, value: Any, ttl: int = 3600):
|
| 36 |
+
"""
|
| 37 |
+
Set key with TTL (seconds). Default 1 hour.
|
| 38 |
+
"""
|
| 39 |
+
# Serialize if dict/list
|
| 40 |
+
str_val = value
|
| 41 |
+
if isinstance(value, (dict, list)):
|
| 42 |
+
str_val = json.dumps(value, default=str) # handle datetimes properly in real implementation
|
| 43 |
+
|
| 44 |
+
if self.use_redis:
|
| 45 |
+
try:
|
| 46 |
+
redis = get_redis()
|
| 47 |
+
await redis.set(key, str_val, ex=ttl)
|
| 48 |
+
except (ConnectionError, TimeoutError, OSError):
|
| 49 |
+
self.use_redis = False
|
| 50 |
+
self._memory_cache[key] = value # No TTL support in simple dict fallback
|
| 51 |
+
except Exception as e:
|
| 52 |
+
logger.error(f"Cache set error: {e}")
|
| 53 |
+
else:
|
| 54 |
+
self._memory_cache[key] = value
|
| 55 |
+
|
| 56 |
+
async def delete(self, key: str):
|
| 57 |
+
if self.use_redis:
|
| 58 |
+
try:
|
| 59 |
+
redis = get_redis()
|
| 60 |
+
await redis.delete(key)
|
| 61 |
+
except Exception:
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
if key in self._memory_cache:
|
| 65 |
+
del self._memory_cache[key]
|
| 66 |
+
|
| 67 |
+
async def clear_prefix(self, prefix: str):
|
| 68 |
+
"""Clear all keys starting with prefix."""
|
| 69 |
+
if self.use_redis:
|
| 70 |
+
try:
|
| 71 |
+
redis = get_redis()
|
| 72 |
+
keys = await redis.keys(f"{prefix}*")
|
| 73 |
+
if keys:
|
| 74 |
+
await redis.delete(*keys)
|
| 75 |
+
except Exception as e:
|
| 76 |
+
logger.error(f"Cache clear error: {e}")
|
| 77 |
+
|
| 78 |
+
cache_service = CacheService()
|
backend/app/services/google_calendar.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from typing import Dict, Any, List, Optional
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
+
import urllib.parse
|
| 6 |
+
from sqlmodel import select
|
| 7 |
+
|
| 8 |
+
from app.core.config import settings
|
| 9 |
+
from app.models.tenant import Tenant
|
| 10 |
+
# We'll use google-auth-library and google-api-python-client
|
| 11 |
+
# but for now, raw HTTP is also an option if we want to minimize deps.
|
| 12 |
+
# However, standard libraries are safer.
|
| 13 |
+
# Dependencies: google-auth, google-auth-oauthlib, google-api-python-client
|
| 14 |
+
|
| 15 |
+
from google.oauth2.credentials import Credentials
|
| 16 |
+
from google_auth_oauthlib.flow import Flow
|
| 17 |
+
from google.auth.transport.requests import Request
|
| 18 |
+
from googleapiclient.discovery import build
|
| 19 |
+
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
SCOPES = ['https://www.googleapis.com/auth/calendar.events']
|
| 23 |
+
|
| 24 |
+
class GoogleCalendarService:
|
| 25 |
+
def __init__(self):
|
| 26 |
+
# We assume settings are loaded.
|
| 27 |
+
# For a real multi-tenant app, we need dynamic redirect_uris usually,
|
| 28 |
+
# but here we might fix it to one callback.
|
| 29 |
+
self.client_id = settings.GOOGLE_CLIENT_ID
|
| 30 |
+
self.client_secret = settings.GOOGLE_CLIENT_SECRET
|
| 31 |
+
# This redirect_uri must match what's in Google Console
|
| 32 |
+
self.redirect_uri = "http://localhost:3000/api/auth/google/callback" # Frontend URL? Or backend?
|
| 33 |
+
# Typically backend handles exchange.
|
| 34 |
+
|
| 35 |
+
def get_auth_url(self, tenant_id: UUID, redirect_uri: str = None) -> str:
|
| 36 |
+
"""Generate the OAuth2 consent URL."""
|
| 37 |
+
if not self.client_id or not self.client_secret:
|
| 38 |
+
raise ValueError("Google Client ID/Secret not configured.")
|
| 39 |
+
|
| 40 |
+
flow = Flow.from_client_config(
|
| 41 |
+
{
|
| 42 |
+
"web": {
|
| 43 |
+
"client_id": self.client_id,
|
| 44 |
+
"client_secret": self.client_secret,
|
| 45 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 46 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 47 |
+
}
|
| 48 |
+
},
|
| 49 |
+
scopes=SCOPES,
|
| 50 |
+
redirect_uri=redirect_uri or self.redirect_uri
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Access type offline to get refresh token
|
| 54 |
+
auth_url, _ = flow.authorization_url(
|
| 55 |
+
access_type='offline',
|
| 56 |
+
include_granted_scopes='true',
|
| 57 |
+
state=str(tenant_id)
|
| 58 |
+
)
|
| 59 |
+
return auth_url
|
| 60 |
+
|
| 61 |
+
async def authenticate(self, code: str, redirect_uri: str = None) -> Dict[str, Any]:
|
| 62 |
+
"""Exchange auth code for tokens."""
|
| 63 |
+
flow = Flow.from_client_config(
|
| 64 |
+
{
|
| 65 |
+
"web": {
|
| 66 |
+
"client_id": self.client_id,
|
| 67 |
+
"client_secret": self.client_secret,
|
| 68 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 69 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 70 |
+
}
|
| 71 |
+
},
|
| 72 |
+
scopes=SCOPES,
|
| 73 |
+
redirect_uri=redirect_uri or self.redirect_uri
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
flow.fetch_token(code=code)
|
| 77 |
+
creds = flow.credentials
|
| 78 |
+
|
| 79 |
+
return {
|
| 80 |
+
"token": creds.token,
|
| 81 |
+
"refresh_token": creds.refresh_token,
|
| 82 |
+
"token_uri": creds.token_uri,
|
| 83 |
+
"client_id": creds.client_id,
|
| 84 |
+
"client_secret": creds.client_secret,
|
| 85 |
+
"scopes": creds.scopes,
|
| 86 |
+
"expiry": creds.expiry.isoformat() if creds.expiry else None
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def _get_credentials(self, tenant: Tenant) -> Optional[Credentials]:
|
| 90 |
+
"""Reconstruct Credentials object from stored config."""
|
| 91 |
+
if not tenant.google_calendar_config:
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
+
config = tenant.google_calendar_config
|
| 95 |
+
|
| 96 |
+
# If we have a refresh token, we can refresh.
|
| 97 |
+
creds = Credentials(
|
| 98 |
+
token=config.get("token"),
|
| 99 |
+
refresh_token=config.get("refresh_token"),
|
| 100 |
+
token_uri="https://oauth2.googleapis.com/token",
|
| 101 |
+
client_id=self.client_id,
|
| 102 |
+
client_secret=self.client_secret,
|
| 103 |
+
scopes=SCOPES
|
| 104 |
+
)
|
| 105 |
+
return creds
|
| 106 |
+
|
| 107 |
+
async def list_free_slots(self, tenant: Tenant, start_time: datetime, end_time: datetime) -> List[Dict]:
|
| 108 |
+
"""
|
| 109 |
+
Check Google Calendar for busy times and invert them to find free slots.
|
| 110 |
+
Actually, simplified: Return BUSY slots, so the BookingService can subtract them.
|
| 111 |
+
"""
|
| 112 |
+
creds = self._get_credentials(tenant)
|
| 113 |
+
if not creds:
|
| 114 |
+
logger.warning("No Google Calendar credentials for tenant.")
|
| 115 |
+
return []
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
service = build('calendar', 'v3', credentials=creds)
|
| 119 |
+
|
| 120 |
+
# Call freebusy
|
| 121 |
+
body = {
|
| 122 |
+
"timeMin": start_time.isoformat() + "Z",
|
| 123 |
+
"timeMax": end_time.isoformat() + "Z",
|
| 124 |
+
"timeZone": "UTC",
|
| 125 |
+
"items": [{"id": "primary"}]
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
events_result = service.freebusy().query(body=body).execute()
|
| 129 |
+
calendars = events_result.get('calendars', {})
|
| 130 |
+
primary = calendars.get('primary', {})
|
| 131 |
+
busy_slots = primary.get('busy', [])
|
| 132 |
+
|
| 133 |
+
# Format: [{'start': '...', 'end': '...'}]
|
| 134 |
+
return busy_slots
|
| 135 |
+
|
| 136 |
+
except Exception as e:
|
| 137 |
+
logger.error(f"Google Calendar API Error: {e}")
|
| 138 |
+
return []
|
| 139 |
+
|
| 140 |
+
async def create_event(self, tenant: Tenant, start_dt: datetime, end_dt: datetime, summary: str, description: str = "", attendees: List[str] = []) -> str:
|
| 141 |
+
"""Create a new event in the calendar."""
|
| 142 |
+
creds = self._get_credentials(tenant)
|
| 143 |
+
if not creds:
|
| 144 |
+
raise ValueError("Tenant not connected to Google Calendar")
|
| 145 |
+
|
| 146 |
+
try:
|
| 147 |
+
service = build('calendar', 'v3', credentials=creds)
|
| 148 |
+
|
| 149 |
+
event = {
|
| 150 |
+
'summary': summary,
|
| 151 |
+
'description': description,
|
| 152 |
+
'start': {
|
| 153 |
+
'dateTime': start_dt.isoformat(),
|
| 154 |
+
'timeZone': 'UTC',
|
| 155 |
+
},
|
| 156 |
+
'end': {
|
| 157 |
+
'dateTime': end_dt.isoformat(),
|
| 158 |
+
'timeZone': 'UTC',
|
| 159 |
+
},
|
| 160 |
+
'attendees': [{'email': email} for email in attendees],
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
event = service.events().insert(calendarId='primary', body=event).execute()
|
| 164 |
+
logger.info(f"Event created: {event.get('htmlLink')}")
|
| 165 |
+
return event.get('id')
|
| 166 |
+
|
| 167 |
+
except Exception as e:
|
| 168 |
+
logger.error(f"Failed to create event: {e}")
|
| 169 |
+
raise
|
| 170 |
+
|
| 171 |
+
_google_calendar_service = None
|
| 172 |
+
|
| 173 |
+
def get_google_calendar_service() -> GoogleCalendarService:
|
| 174 |
+
global _google_calendar_service
|
| 175 |
+
if not _google_calendar_service:
|
| 176 |
+
_google_calendar_service = GoogleCalendarService()
|
| 177 |
+
return _google_calendar_service
|
backend/app/services/llm_client.py
CHANGED
|
@@ -11,6 +11,7 @@ from app.services.ai_queue import get_ai_queue
|
|
| 11 |
import os
|
| 12 |
import json
|
| 13 |
import re
|
|
|
|
| 14 |
|
| 15 |
logger = logging.getLogger(__name__)
|
| 16 |
|
|
@@ -41,6 +42,11 @@ class GeminiLLMClient:
|
|
| 41 |
|
| 42 |
logger.info(f"✅ Gemini LLM client initialized (model: {self.default_model_name})")
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
async def generate_response(
|
| 45 |
self,
|
| 46 |
prompt: str,
|
|
@@ -274,6 +280,19 @@ class GeminiLLMClient:
|
|
| 274 |
logger.error(f"Transcription failed: {e}")
|
| 275 |
raise LLMAPIError(f"Transcription failed: {e}")
|
| 276 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
@lru_cache()
|
| 278 |
def get_llm_client():
|
| 279 |
return GeminiLLMClient()
|
|
|
|
| 11 |
import os
|
| 12 |
import json
|
| 13 |
import re
|
| 14 |
+
from app.services.voice_service import voice_service
|
| 15 |
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
|
|
|
| 42 |
|
| 43 |
logger.info(f"✅ Gemini LLM client initialized (model: {self.default_model_name})")
|
| 44 |
|
| 45 |
+
async def generate_text(self, prompt: str) -> str:
|
| 46 |
+
"""Convenience method for text-only response."""
|
| 47 |
+
resp = await self.generate_response(prompt)
|
| 48 |
+
return resp["text"]
|
| 49 |
+
|
| 50 |
async def generate_response(
|
| 51 |
self,
|
| 52 |
prompt: str,
|
|
|
|
| 280 |
logger.error(f"Transcription failed: {e}")
|
| 281 |
raise LLMAPIError(f"Transcription failed: {e}")
|
| 282 |
|
| 283 |
+
async def generate_speech(self, text: str, voice: str = "onyx") -> bytes:
|
| 284 |
+
"""
|
| 285 |
+
Generate audio from text using configured VoiceService (OpenAI TTS).
|
| 286 |
+
|
| 287 |
+
Args:
|
| 288 |
+
text: Text to speak
|
| 289 |
+
voice: Voice ID (default: 'onyx')
|
| 290 |
+
|
| 291 |
+
Returns:
|
| 292 |
+
bytes: Audio content (MP3)
|
| 293 |
+
"""
|
| 294 |
+
return await voice_service.generate_audio(text, voice)
|
| 295 |
+
|
| 296 |
@lru_cache()
|
| 297 |
def get_llm_client():
|
| 298 |
return GeminiLLMClient()
|
backend/app/services/meta_instagram.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Meta Instagram Graph API Service.
|
| 3 |
+
Handles official API interactions for sending Direct Messages.
|
| 4 |
+
"""
|
| 5 |
+
import httpx
|
| 6 |
+
from typing import Optional, Dict, Any, List
|
| 7 |
+
from app.core.config import settings
|
| 8 |
+
from app.core.logging import get_logger
|
| 9 |
+
from app.models.tenant import Tenant
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
class InstagramGraphService:
|
| 14 |
+
"""Service for Instagram Graph API."""
|
| 15 |
+
|
| 16 |
+
BASE_URL = "https://graph.facebook.com/v18.0"
|
| 17 |
+
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.timeout = 30.0
|
| 20 |
+
|
| 21 |
+
def _get_headers(self, token: str) -> Dict[str, str]:
|
| 22 |
+
return {
|
| 23 |
+
"Authorization": f"Bearer {token}",
|
| 24 |
+
"Content-Type": "application/json"
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
async def send_message(
|
| 28 |
+
self,
|
| 29 |
+
tenant: Tenant,
|
| 30 |
+
recipient_id: str,
|
| 31 |
+
text: str
|
| 32 |
+
) -> Dict[str, Any]:
|
| 33 |
+
"""
|
| 34 |
+
Send a text message via Instagram Graph API.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
tenant: Tenant model with meta_ig_config
|
| 38 |
+
recipient_id: PSID (Page Scoped ID) of the Instagram user
|
| 39 |
+
text: Message text
|
| 40 |
+
"""
|
| 41 |
+
if not tenant.meta_ig_config:
|
| 42 |
+
raise ValueError("Tenant has no Meta Instagram configuration")
|
| 43 |
+
|
| 44 |
+
# For IG, we send request to 'me/messages' or '{dma_page_id}/messages'
|
| 45 |
+
# Usually it is POST /{page_id}/messages
|
| 46 |
+
page_id = tenant.meta_ig_config.get("page_id")
|
| 47 |
+
token = tenant.meta_ig_config.get("access_token")
|
| 48 |
+
|
| 49 |
+
if not page_id or not token:
|
| 50 |
+
raise ValueError("Invalid Meta Instagram configuration (missing page_id or token)")
|
| 51 |
+
|
| 52 |
+
url = f"{self.BASE_URL}/{page_id}/messages"
|
| 53 |
+
|
| 54 |
+
payload = {
|
| 55 |
+
"recipient": {"id": recipient_id},
|
| 56 |
+
"message": {"text": text}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 60 |
+
response = await client.post(
|
| 61 |
+
url,
|
| 62 |
+
json=payload,
|
| 63 |
+
headers=self._get_headers(token)
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if response.status_code not in [200, 201]:
|
| 67 |
+
logger.error(f"Instagram API Error: {response.text}")
|
| 68 |
+
|
| 69 |
+
response.raise_for_status()
|
| 70 |
+
return response.json()
|
| 71 |
+
|
| 72 |
+
async def send_media(
|
| 73 |
+
self,
|
| 74 |
+
tenant: Tenant,
|
| 75 |
+
recipient_id: str,
|
| 76 |
+
media_url: str,
|
| 77 |
+
media_type: str = "image"
|
| 78 |
+
) -> Dict[str, Any]:
|
| 79 |
+
"""Send media (image/video)."""
|
| 80 |
+
if not tenant.meta_ig_config:
|
| 81 |
+
raise ValueError("Tenant has no Meta Instagram configuration")
|
| 82 |
+
|
| 83 |
+
page_id = tenant.meta_ig_config.get("page_id")
|
| 84 |
+
token = tenant.meta_ig_config.get("access_token")
|
| 85 |
+
|
| 86 |
+
url = f"{self.BASE_URL}/{page_id}/messages"
|
| 87 |
+
|
| 88 |
+
# attachment type: 'image' or 'video'
|
| 89 |
+
payload = {
|
| 90 |
+
"recipient": {"id": recipient_id},
|
| 91 |
+
"message": {
|
| 92 |
+
"attachment": {
|
| 93 |
+
"type": media_type,
|
| 94 |
+
"payload": {
|
| 95 |
+
"url": media_url,
|
| 96 |
+
"is_reusable": True
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 103 |
+
response = await client.post(
|
| 104 |
+
url,
|
| 105 |
+
json=payload,
|
| 106 |
+
headers=self._get_headers(token)
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
if response.status_code not in [200, 201]:
|
| 110 |
+
logger.error(f"Instagram API Error: {response.text}")
|
| 111 |
+
|
| 112 |
+
response.raise_for_status()
|
| 113 |
+
return response.json()
|
| 114 |
+
|
| 115 |
+
# Singleton
|
| 116 |
+
instagram_graph_service = InstagramGraphService()
|
| 117 |
+
def get_instagram_graph_service() -> InstagramGraphService:
|
| 118 |
+
return instagram_graph_service
|
backend/app/services/meta_whatsapp.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Meta WhatsApp Cloud API Service.
|
| 3 |
+
Handles official API interactions for sending messages and media.
|
| 4 |
+
"""
|
| 5 |
+
import httpx
|
| 6 |
+
from typing import Optional, Dict, Any, List
|
| 7 |
+
from app.core.config import settings
|
| 8 |
+
from app.core.logging import get_logger
|
| 9 |
+
from app.models.tenant import Tenant
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
class WhatsAppCloudService:
|
| 14 |
+
"""Service for WhatsApp Cloud API."""
|
| 15 |
+
|
| 16 |
+
BASE_URL = "https://graph.facebook.com/v18.0"
|
| 17 |
+
|
| 18 |
+
def __init__(self):
|
| 19 |
+
self.timeout = 30.0
|
| 20 |
+
|
| 21 |
+
def _get_headers(self, token: str) -> Dict[str, str]:
|
| 22 |
+
return {
|
| 23 |
+
"Authorization": f"Bearer {token}",
|
| 24 |
+
"Content-Type": "application/json"
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
async def send_text_message(
|
| 28 |
+
self,
|
| 29 |
+
tenant: Tenant,
|
| 30 |
+
to_phone: str,
|
| 31 |
+
text: str,
|
| 32 |
+
preview_url: bool = False
|
| 33 |
+
) -> Dict[str, Any]:
|
| 34 |
+
"""
|
| 35 |
+
Send a text message via Cloud API.
|
| 36 |
+
"""
|
| 37 |
+
if not tenant.meta_wa_config:
|
| 38 |
+
raise ValueError("Tenant has no Meta WhatsApp configuration")
|
| 39 |
+
|
| 40 |
+
phone_id = tenant.meta_wa_config.get("phone_number_id")
|
| 41 |
+
token = tenant.meta_wa_config.get("access_token")
|
| 42 |
+
|
| 43 |
+
if not phone_id or not token:
|
| 44 |
+
raise ValueError("Invalid Meta WhatsApp configuration (missing phone_id or token)")
|
| 45 |
+
|
| 46 |
+
url = f"{self.BASE_URL}/{phone_id}/messages"
|
| 47 |
+
|
| 48 |
+
payload = {
|
| 49 |
+
"messaging_product": "whatsapp",
|
| 50 |
+
"recipient_type": "individual",
|
| 51 |
+
"to": to_phone,
|
| 52 |
+
"type": "text",
|
| 53 |
+
"text": {
|
| 54 |
+
"preview_url": preview_url,
|
| 55 |
+
"body": text
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 60 |
+
response = await client.post(
|
| 61 |
+
url,
|
| 62 |
+
json=payload,
|
| 63 |
+
headers=self._get_headers(token)
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
if response.status_code not in [200, 201]:
|
| 67 |
+
logger.error(f"Meta API Error: {response.text}")
|
| 68 |
+
|
| 69 |
+
response.raise_for_status()
|
| 70 |
+
return response.json()
|
| 71 |
+
|
| 72 |
+
async def upload_media(
|
| 73 |
+
self,
|
| 74 |
+
tenant: Tenant,
|
| 75 |
+
data: bytes,
|
| 76 |
+
mime_type: str = "audio/mpeg"
|
| 77 |
+
) -> str:
|
| 78 |
+
"""
|
| 79 |
+
Upload media to WhatsApp Cloud API and return Media ID.
|
| 80 |
+
"""
|
| 81 |
+
if not tenant.meta_wa_config:
|
| 82 |
+
raise ValueError("Tenant has no Meta WhatsApp configuration")
|
| 83 |
+
|
| 84 |
+
phone_id = tenant.meta_wa_config.get("phone_number_id")
|
| 85 |
+
token = tenant.meta_wa_config.get("access_token")
|
| 86 |
+
|
| 87 |
+
url = f"{self.BASE_URL}/{phone_id}/media"
|
| 88 |
+
|
| 89 |
+
files = {
|
| 90 |
+
"file": ("voice_message.mp3", data, mime_type)
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
data_payload = {
|
| 94 |
+
"messaging_product": "whatsapp"
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
async with httpx.AsyncClient(timeout=60.0) as client:
|
| 98 |
+
response = await client.post(
|
| 99 |
+
url,
|
| 100 |
+
data=data_payload,
|
| 101 |
+
files=files,
|
| 102 |
+
headers={"Authorization": f"Bearer {token}"} # Do not set Content-Type, httpx handles multipart
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
if response.status_code != 200:
|
| 106 |
+
logger.error(f"Media Upload Failed: {response.text}")
|
| 107 |
+
response.raise_for_status()
|
| 108 |
+
|
| 109 |
+
result = response.json()
|
| 110 |
+
return result.get("id")
|
| 111 |
+
|
| 112 |
+
async def send_audio_message(
|
| 113 |
+
self,
|
| 114 |
+
tenant: Tenant,
|
| 115 |
+
to_phone: str,
|
| 116 |
+
media_id: str
|
| 117 |
+
) -> Dict[str, Any]:
|
| 118 |
+
"""
|
| 119 |
+
Send an audio message using an uploaded Media ID.
|
| 120 |
+
"""
|
| 121 |
+
if not tenant.meta_wa_config:
|
| 122 |
+
raise ValueError("Tenant has no Meta WhatsApp configuration")
|
| 123 |
+
|
| 124 |
+
phone_id = tenant.meta_wa_config.get("phone_number_id")
|
| 125 |
+
token = tenant.meta_wa_config.get("access_token")
|
| 126 |
+
|
| 127 |
+
url = f"{self.BASE_URL}/{phone_id}/messages"
|
| 128 |
+
|
| 129 |
+
payload = {
|
| 130 |
+
"messaging_product": "whatsapp",
|
| 131 |
+
"recipient_type": "individual",
|
| 132 |
+
"to": to_phone,
|
| 133 |
+
"type": "audio",
|
| 134 |
+
"audio": {
|
| 135 |
+
"id": media_id
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 140 |
+
response = await client.post(
|
| 141 |
+
url,
|
| 142 |
+
json=payload,
|
| 143 |
+
headers=self._get_headers(token)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
if response.status_code not in [200, 201]:
|
| 147 |
+
logger.error(f"Meta API Error (Audio): {response.text}")
|
| 148 |
+
|
| 149 |
+
response.raise_for_status()
|
| 150 |
+
return response.json()
|
| 151 |
+
|
| 152 |
+
async def mark_message_as_read(
|
| 153 |
+
self,
|
| 154 |
+
tenant: Tenant,
|
| 155 |
+
message_id: str
|
| 156 |
+
) -> bool:
|
| 157 |
+
"""Mark a message as read."""
|
| 158 |
+
if not tenant.meta_wa_config:
|
| 159 |
+
return False
|
| 160 |
+
|
| 161 |
+
phone_id = tenant.meta_wa_config.get("phone_number_id")
|
| 162 |
+
token = tenant.meta_wa_config.get("access_token")
|
| 163 |
+
|
| 164 |
+
url = f"{self.BASE_URL}/{phone_id}/messages"
|
| 165 |
+
|
| 166 |
+
payload = {
|
| 167 |
+
"messaging_product": "whatsapp",
|
| 168 |
+
"status": "read",
|
| 169 |
+
"message_id": message_id
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
| 174 |
+
await client.post(
|
| 175 |
+
url,
|
| 176 |
+
json=payload,
|
| 177 |
+
headers=self._get_headers(token)
|
| 178 |
+
)
|
| 179 |
+
return True
|
| 180 |
+
except Exception as e:
|
| 181 |
+
logger.warning(f"Failed to mark message read: {e}")
|
| 182 |
+
return False
|
| 183 |
+
|
| 184 |
+
# Singleton
|
| 185 |
+
whatsapp_cloud_service = WhatsAppCloudService()
|
| 186 |
+
def get_whatsapp_cloud_service() -> WhatsAppCloudService:
|
| 187 |
+
return whatsapp_cloud_service
|
backend/app/services/stripe_service.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import stripe
|
| 2 |
+
from app.core.config import settings
|
| 3 |
+
from fastapi import HTTPException
|
| 4 |
+
import logging
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
stripe_service = None
|
| 10 |
+
|
| 11 |
+
class StripeService:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.is_mock_mode = False
|
| 14 |
+
|
| 15 |
+
# Check if keys are missing or explicitly "mock"
|
| 16 |
+
if not settings.STRIPE_SECRET_KEY or "mock" in settings.STRIPE_SECRET_KEY.lower():
|
| 17 |
+
self.is_mock_mode = True
|
| 18 |
+
logger.warning("⚠️ STRIPE IS IN MOCK MODE. No real payments will be processed.")
|
| 19 |
+
else:
|
| 20 |
+
stripe.api_key = settings.STRIPE_SECRET_KEY
|
| 21 |
+
|
| 22 |
+
async def create_checkout_session(self, tenant_id: str, plan: str, email: str = None) -> str:
|
| 23 |
+
"""
|
| 24 |
+
Create a Stripe Checkout Session for subscription.
|
| 25 |
+
Returns the checkout URL.
|
| 26 |
+
"""
|
| 27 |
+
if self.is_mock_mode:
|
| 28 |
+
logger.info(f"🧾 [MOCK] Creating checkout for plan {plan} (Tenant: {tenant_id})")
|
| 29 |
+
return f"{settings.FRONTEND_URL}/settings/billing?success=true&mock_plan={plan}"
|
| 30 |
+
|
| 31 |
+
price_id = self._get_price_id(plan)
|
| 32 |
+
if not price_id:
|
| 33 |
+
raise HTTPException(status_code=400, detail=f"Invalid plan: {plan}")
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
checkout_session = stripe.checkout.Session.create(
|
| 37 |
+
payment_method_types=['card'],
|
| 38 |
+
line_items=[
|
| 39 |
+
{
|
| 40 |
+
'price': price_id,
|
| 41 |
+
'quantity': 1,
|
| 42 |
+
},
|
| 43 |
+
],
|
| 44 |
+
mode='subscription',
|
| 45 |
+
success_url=f"{settings.FRONTEND_URL}/settings/billing?success=true",
|
| 46 |
+
cancel_url=f"{settings.FRONTEND_URL}/settings/billing?canceled=true",
|
| 47 |
+
client_reference_id=tenant_id,
|
| 48 |
+
customer_email=email,
|
| 49 |
+
metadata={
|
| 50 |
+
"tenant_id": tenant_id,
|
| 51 |
+
"plan": plan
|
| 52 |
+
}
|
| 53 |
+
)
|
| 54 |
+
return checkout_session.url
|
| 55 |
+
except Exception as e:
|
| 56 |
+
logger.error(f"Stripe Checkout Error: {e}")
|
| 57 |
+
raise HTTPException(status_code=500, detail="Payment gateway error")
|
| 58 |
+
|
| 59 |
+
async def create_portal_session(self, customer_id: str) -> str:
|
| 60 |
+
"""
|
| 61 |
+
Create a Stripe Customer Portal session.
|
| 62 |
+
"""
|
| 63 |
+
if self.is_mock_mode:
|
| 64 |
+
logger.info(f"🚪 [MOCK] Accessing portal for customer {customer_id}")
|
| 65 |
+
return f"{settings.FRONTEND_URL}/settings/billing?portal_success=true"
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
portal_session = stripe.billing_portal.Session.create(
|
| 69 |
+
customer=customer_id,
|
| 70 |
+
return_url=f"{settings.FRONTEND_URL}/settings/billing",
|
| 71 |
+
)
|
| 72 |
+
return portal_session.url
|
| 73 |
+
except Exception as e:
|
| 74 |
+
logger.error(f"Stripe Portal Error: {e}")
|
| 75 |
+
raise HTTPException(status_code=500, detail="Could not access billing portal")
|
| 76 |
+
|
| 77 |
+
def construct_event(self, payload: bytes, sig_header: str):
|
| 78 |
+
"""
|
| 79 |
+
Verify webhook signature.
|
| 80 |
+
"""
|
| 81 |
+
if self.is_mock_mode:
|
| 82 |
+
logger.info("🪝 [MOCK] Skipping webhook signature verification")
|
| 83 |
+
# In mock mode, we assume the payload is already JSON parsed by FastAPI if processed manually,
|
| 84 |
+
# but here we follow standard Stripe pattern where payload is bytes.
|
| 85 |
+
# We return a dummy event with the data.
|
| 86 |
+
import json
|
| 87 |
+
try:
|
| 88 |
+
data = json.loads(payload)
|
| 89 |
+
return data # Return dict as event
|
| 90 |
+
except:
|
| 91 |
+
return {"type": "mock.event", "data": {"object": {}}}
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
event = stripe.Webhook.construct_event(
|
| 95 |
+
payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
|
| 96 |
+
)
|
| 97 |
+
return event
|
| 98 |
+
except ValueError as e:
|
| 99 |
+
# Invalid payload
|
| 100 |
+
raise HTTPException(status_code=400, detail="Invalid payload")
|
| 101 |
+
except stripe.error.SignatureVerificationError as e:
|
| 102 |
+
# Invalid signature
|
| 103 |
+
raise HTTPException(status_code=400, detail="Invalid signature")
|
| 104 |
+
|
| 105 |
+
def _get_price_id(self, plan: str) -> Optional[str]:
|
| 106 |
+
plan = plan.lower()
|
| 107 |
+
if plan == "start":
|
| 108 |
+
return settings.STRIPE_PRICE_START
|
| 109 |
+
elif plan == "growth":
|
| 110 |
+
return settings.STRIPE_PRICE_GROWTH
|
| 111 |
+
elif plan == "unlimited":
|
| 112 |
+
return settings.STRIPE_PRICE_UNLIMITED
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
stripe_service = StripeService()
|
backend/app/services/voice_manager.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import io
|
| 3 |
+
import logging
|
| 4 |
+
from typing import List, Optional, Deque
|
| 5 |
+
from collections import deque
|
| 6 |
+
import numpy as np
|
| 7 |
+
from pydub import AudioSegment
|
| 8 |
+
|
| 9 |
+
from app.services.llm_client import get_llm_client
|
| 10 |
+
from app.services.voice_service import voice_service
|
| 11 |
+
from app.core.config import settings
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
class VoiceSession:
|
| 16 |
+
"""State for a single WebSocket voice session."""
|
| 17 |
+
def __init__(self, session_id: str, tenant_id: str):
|
| 18 |
+
self.session_id = session_id
|
| 19 |
+
self.tenant_id = tenant_id
|
| 20 |
+
self.audio_buffer = io.BytesIO()
|
| 21 |
+
self.silence_frames = 0
|
| 22 |
+
self.is_listening = True
|
| 23 |
+
self.history = []
|
| 24 |
+
|
| 25 |
+
def add_audio(self, chunk: bytes):
|
| 26 |
+
self.audio_buffer.write(chunk)
|
| 27 |
+
|
| 28 |
+
def get_audio_bytes(self) -> bytes:
|
| 29 |
+
return self.audio_buffer.getvalue()
|
| 30 |
+
|
| 31 |
+
def clear_buffer(self):
|
| 32 |
+
self.audio_buffer = io.BytesIO()
|
| 33 |
+
self.silence_frames = 0
|
| 34 |
+
|
| 35 |
+
class VoiceManager:
|
| 36 |
+
"""
|
| 37 |
+
Orchestrates the Audio -> Text -> AI -> Audio pipeline.
|
| 38 |
+
"""
|
| 39 |
+
def __init__(self):
|
| 40 |
+
self.llm_client = get_llm_client()
|
| 41 |
+
|
| 42 |
+
async def process_audio_chunk(self, session: VoiceSession, chunk: bytes) -> Optional[bytes]:
|
| 43 |
+
"""
|
| 44 |
+
Ingest audio chunk.
|
| 45 |
+
Returns audio response (bytes) if turn is complete, else None.
|
| 46 |
+
|
| 47 |
+
Logic:
|
| 48 |
+
1. Accumulate audio.
|
| 49 |
+
2. Check for silence (VAD).
|
| 50 |
+
3. If silence > threshold:
|
| 51 |
+
- STT
|
| 52 |
+
- LLM
|
| 53 |
+
- TTS
|
| 54 |
+
- Return Audio
|
| 55 |
+
"""
|
| 56 |
+
session.add_audio(chunk)
|
| 57 |
+
|
| 58 |
+
# Simple Energy VAD (Placeholder)
|
| 59 |
+
# Real VAD needs PCM decoding. Assuming input is raw PCM or we decode it.
|
| 60 |
+
# For MVP, we might rely on client sending "END_OF_SPEECH" marker or
|
| 61 |
+
# we process every X seconds if streaming.
|
| 62 |
+
|
| 63 |
+
# Let's assume for MVP the client handles VAD or we wait for a specific
|
| 64 |
+
# "commit" content if we want robustness without heavy server CPU.
|
| 65 |
+
# BUT the requirement is "Real Time".
|
| 66 |
+
|
| 67 |
+
# TODO: Implement server-side VAD using pydub/numpy
|
| 68 |
+
# For now, return None. The Router will trigger 'process_turn' explicitly
|
| 69 |
+
# when silence is detected or buffer is full.
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
async def process_turn(self, session: VoiceSession, tenant_config=None) -> Optional[bytes]:
|
| 73 |
+
"""
|
| 74 |
+
Process the accumulated buffer as a full turn.
|
| 75 |
+
"""
|
| 76 |
+
audio_data = session.get_audio_bytes()
|
| 77 |
+
if not audio_data or len(audio_data) < 1000: # Ignore empty/noise
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
logger.info(f"🎤 Processing turn for {session.session_id}, size={len(audio_data)} bytes")
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
# 1. STT (Speech to Text)
|
| 84 |
+
# Use Gemini or Whisper. Gemini expects file or bytes.
|
| 85 |
+
transcript = await self.llm_client.transcribe_audio(audio_data)
|
| 86 |
+
logger.info(f"🗣️ User said: {transcript}")
|
| 87 |
+
|
| 88 |
+
if not transcript or len(transcript.strip()) < 2:
|
| 89 |
+
session.clear_buffer()
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
# 2. LLM (Generate Text Response)
|
| 93 |
+
# We assume a stateless chat for now or pass history if needed.
|
| 94 |
+
# Ideally we use AICore logic here but simplified for speed.
|
| 95 |
+
|
| 96 |
+
# Simple direct prompt for speed
|
| 97 |
+
prompt = f"User said: {transcript}. Reply conversationally, brief and helpful."
|
| 98 |
+
if session.history:
|
| 99 |
+
# Add limited history
|
| 100 |
+
hist_str = "\n".join([f"{msg['role']}: {msg['text']}" for msg in session.history[-4:]])
|
| 101 |
+
prompt = f"Previous chat:\n{hist_str}\n\n{prompt}"
|
| 102 |
+
|
| 103 |
+
response_text = await self.llm_client.generate_text(prompt)
|
| 104 |
+
# Use fallback direct access if AICore is too heavy/async complex for this MVP stream
|
| 105 |
+
# response_text = response_dict['text'] if isinstance(response_dict, dict) else response_text
|
| 106 |
+
|
| 107 |
+
logger.info(f"🤖 AI replying: {response_text}")
|
| 108 |
+
|
| 109 |
+
# Update history
|
| 110 |
+
session.history.append({"role": "user", "text": transcript})
|
| 111 |
+
session.history.append({"role": "ai", "text": response_text})
|
| 112 |
+
|
| 113 |
+
# 3. TTS (Text to Speech)
|
| 114 |
+
audio_response = await voice_service.generate_speech(response_text)
|
| 115 |
+
|
| 116 |
+
session.clear_buffer()
|
| 117 |
+
return audio_response
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
logger.error(f"Error in voice pipeline: {e}")
|
| 121 |
+
session.clear_buffer()
|
| 122 |
+
return None
|
| 123 |
+
|
| 124 |
+
voice_manager = VoiceManager()
|
backend/app/services/voice_service.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from openai import AsyncOpenAI
|
| 2 |
+
from app.core.config import settings
|
| 3 |
+
from fastapi import HTTPException
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
class VoiceService:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self.api_key = settings.OPENAI_API_KEY
|
| 11 |
+
if self.api_key:
|
| 12 |
+
self.client = AsyncOpenAI(api_key=self.api_key)
|
| 13 |
+
else:
|
| 14 |
+
self.client = None
|
| 15 |
+
logger.warning("OPENAI_API_KEY not found. Voice generation will be disabled.")
|
| 16 |
+
|
| 17 |
+
async def generate_audio(self, text: str, voice: str = "onyx") -> bytes:
|
| 18 |
+
"""
|
| 19 |
+
Generates audio from text using OpenAI's TTS API.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
text: The text to convert to speech.
|
| 23 |
+
voice: The voice ID to use (onyx, alloy, echo, fable, nova, shimmer).
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
bytes: The binary audio content (MP3).
|
| 27 |
+
"""
|
| 28 |
+
if not self.client:
|
| 29 |
+
raise HTTPException(status_code=503, detail="Voice service is not configured (Missing OpenAI Key)")
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
# "onyx" is best for the "Aggressive/Command Center" persona
|
| 33 |
+
response = await self.client.audio.speech.create(
|
| 34 |
+
model="tts-1",
|
| 35 |
+
voice=voice,
|
| 36 |
+
input=text
|
| 37 |
+
)
|
| 38 |
+
return response.content
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"Voice generation failed: {str(e)}")
|
| 41 |
+
raise HTTPException(status_code=500, detail=f"Voice generation failed: {str(e)}")
|
| 42 |
+
|
| 43 |
+
voice_service = VoiceService()
|
backend/app/services/whatsapp_qr.py
CHANGED
|
@@ -24,7 +24,13 @@ class WhatsAppQRSession:
|
|
| 24 |
self.evolution_api_key = settings.EVOLUTION_API_KEY
|
| 25 |
self.sessions: Dict[str, Dict] = {}
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def _is_configured(self) -> bool:
|
| 30 |
"""Check if Evolution API is properly configured"""
|
|
@@ -367,7 +373,7 @@ class WhatsAppQRSession:
|
|
| 367 |
headers=self._get_headers()
|
| 368 |
)
|
| 369 |
|
| 370 |
-
if response.status_code
|
| 371 |
logger.info(f"Message sent to {phone} via {instance_name}")
|
| 372 |
return True
|
| 373 |
else:
|
|
@@ -424,7 +430,7 @@ class WhatsAppQRSession:
|
|
| 424 |
headers=self._get_headers()
|
| 425 |
)
|
| 426 |
|
| 427 |
-
if response.status_code
|
| 428 |
logger.info(f"Media sent to {phone} via {instance_name}")
|
| 429 |
return True
|
| 430 |
else:
|
|
|
|
| 24 |
self.evolution_api_key = settings.EVOLUTION_API_KEY
|
| 25 |
self.sessions: Dict[str, Dict] = {}
|
| 26 |
|
| 27 |
+
# DEPRECATION NOTICE
|
| 28 |
+
logger.warning("⚠️ WhatsAppQRSession is DEPRECATED. Use WhatsAppCloudService (Official API) instead.")
|
| 29 |
+
# We disable functionality to prevent bans
|
| 30 |
+
self.evolution_url = None
|
| 31 |
+
self.evolution_api_key = None
|
| 32 |
+
|
| 33 |
+
# logger.info(f"WhatsApp Service initialized with URL: {self.evolution_url}")
|
| 34 |
|
| 35 |
def _is_configured(self) -> bool:
|
| 36 |
"""Check if Evolution API is properly configured"""
|
|
|
|
| 373 |
headers=self._get_headers()
|
| 374 |
)
|
| 375 |
|
| 376 |
+
if response.status_code in [200, 201]:
|
| 377 |
logger.info(f"Message sent to {phone} via {instance_name}")
|
| 378 |
return True
|
| 379 |
else:
|
|
|
|
| 430 |
headers=self._get_headers()
|
| 431 |
)
|
| 432 |
|
| 433 |
+
if response.status_code in [200, 201]:
|
| 434 |
logger.info(f"Media sent to {phone} via {instance_name}")
|
| 435 |
return True
|
| 436 |
else:
|
backend/app/tasks/ai.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.worker import celery_app
|
| 2 |
+
from app.services.embeddings import get_embedding_service
|
| 3 |
+
from typing import List, Dict, Any
|
| 4 |
+
|
| 5 |
+
@celery_app.task
|
| 6 |
+
def generate_embeddings_task(texts: List[str]) -> List[List[float]]:
|
| 7 |
+
"""
|
| 8 |
+
Generate embeddings for a batch of texts.
|
| 9 |
+
Worker task to offload OpenAI API calls.
|
| 10 |
+
"""
|
| 11 |
+
service = get_embedding_service()
|
| 12 |
+
return service.embed_batch(texts)
|
backend/app/tasks/email.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from app.worker import celery_app
|
| 2 |
+
from app.services.email import email_service
|
| 3 |
+
from app.models.lead import Lead # If needed, but usually we pass primitive types (emails, subject, body) to tasks
|
| 4 |
+
import asyncio
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
|
| 7 |
+
@celery_app.task
|
| 8 |
+
def send_email_task(to_email: str, subject: str, html_content: str):
|
| 9 |
+
"""
|
| 10 |
+
Background task to send email using async EmailService.
|
| 11 |
+
"""
|
| 12 |
+
try:
|
| 13 |
+
# Create a new event loop for this thread/task
|
| 14 |
+
loop = asyncio.new_event_loop()
|
| 15 |
+
asyncio.set_event_loop(loop)
|
| 16 |
+
|
| 17 |
+
# Run the async service method
|
| 18 |
+
loop.run_until_complete(email_service.send_email(
|
| 19 |
+
to_email=to_email,
|
| 20 |
+
subject=subject,
|
| 21 |
+
html_content=html_content
|
| 22 |
+
))
|
| 23 |
+
loop.close()
|
| 24 |
+
return f"Email sent to {to_email}"
|
| 25 |
+
except Exception as e:
|
| 26 |
+
return f"Failed to send email: {e}"
|
backend/app/worker.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from celery import Celery
|
| 2 |
+
from app.core.config import settings
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# Ensure settings are loaded
|
| 6 |
+
if not settings.REDIS_URL:
|
| 7 |
+
raise ValueError("REDIS_URL not set in settings")
|
| 8 |
+
|
| 9 |
+
celery_app = Celery(
|
| 10 |
+
"microfunnel_worker",
|
| 11 |
+
broker=settings.REDIS_URL,
|
| 12 |
+
backend=settings.REDIS_URL
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
celery_app.conf.update(
|
| 16 |
+
task_serializer="json",
|
| 17 |
+
accept_content=["json"],
|
| 18 |
+
result_serializer="json",
|
| 19 |
+
timezone="UTC",
|
| 20 |
+
enable_utc=True,
|
| 21 |
+
# Task specific settings
|
| 22 |
+
task_routes={
|
| 23 |
+
"app.tasks.email.send_email_task": "email-queue",
|
| 24 |
+
"app.tasks.ai.generate_embeddings_task": "ai-queue",
|
| 25 |
+
},
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Auto-discover tasks
|
| 29 |
+
celery_app.autodiscover_tasks(["app.tasks.email", "app.tasks.ai"])
|
backend/scripts/fix_env.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
env_path = ".env"
|
| 4 |
+
key_line = "OPENAI_API_KEY=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"
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
# Read existing content
|
| 8 |
+
if os.path.exists(env_path):
|
| 9 |
+
with open(env_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 10 |
+
lines = f.readlines()
|
| 11 |
+
else:
|
| 12 |
+
lines = []
|
| 13 |
+
|
| 14 |
+
# Check if key exists
|
| 15 |
+
found = False
|
| 16 |
+
new_lines = []
|
| 17 |
+
for line in lines:
|
| 18 |
+
if line.strip().startswith("OPENAI_API_KEY="):
|
| 19 |
+
new_lines.append(key_line + "\n")
|
| 20 |
+
found = True
|
| 21 |
+
else:
|
| 22 |
+
new_lines.append(line)
|
| 23 |
+
|
| 24 |
+
if not found:
|
| 25 |
+
if new_lines and not new_lines[-1].endswith("\n"):
|
| 26 |
+
new_lines[-1] += "\n"
|
| 27 |
+
new_lines.append(key_line + "\n")
|
| 28 |
+
|
| 29 |
+
# Write back
|
| 30 |
+
with open(env_path, "w", encoding="utf-8") as f:
|
| 31 |
+
f.writelines(new_lines)
|
| 32 |
+
|
| 33 |
+
print("Fixed .env with UTF-8")
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print(f"Error fixing .env: {e}")
|
backend/scripts/health_check.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
from sqlalchemy import text
|
| 5 |
+
|
| 6 |
+
# Add backend to path
|
| 7 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
| 8 |
+
|
| 9 |
+
from app.core.database import get_async_session
|
| 10 |
+
from app.services.cache_service import cache_service
|
| 11 |
+
from app.services.google_calendar import get_google_calendar_service
|
| 12 |
+
from app.worker import celery_app
|
| 13 |
+
from app.core.config import settings
|
| 14 |
+
|
| 15 |
+
async def check_db():
|
| 16 |
+
print("\n🔍 Checking Database...")
|
| 17 |
+
try:
|
| 18 |
+
async for session in get_async_session():
|
| 19 |
+
result = await session.execute(text("SELECT 1"))
|
| 20 |
+
print(f"✅ Database connected. Result: {result.scalar()}")
|
| 21 |
+
|
| 22 |
+
# Check pgvector extension
|
| 23 |
+
try:
|
| 24 |
+
await session.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
|
| 25 |
+
print("✅ pgvector extension verified.")
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"⚠️ pgvector check warning: {e}")
|
| 28 |
+
break
|
| 29 |
+
except Exception as e:
|
| 30 |
+
print(f"❌ Database connection failed: {e}")
|
| 31 |
+
|
| 32 |
+
async def check_redis():
|
| 33 |
+
print("\n🔍 Checking Redis Cache...")
|
| 34 |
+
try:
|
| 35 |
+
await cache_service.set("health_check", "ok", ttl=10)
|
| 36 |
+
val = await cache_service.get("health_check")
|
| 37 |
+
if val == "ok":
|
| 38 |
+
mode = "Redis" if cache_service.use_redis else "Memory Fallback"
|
| 39 |
+
print(f"✅ Cache working. Mode: {mode}")
|
| 40 |
+
else:
|
| 41 |
+
print("❌ Cache set/get mismatch.")
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"❌ Cache check failed: {e}")
|
| 44 |
+
|
| 45 |
+
def check_celery():
|
| 46 |
+
print("\n🔍 Checking Celery Config...")
|
| 47 |
+
try:
|
| 48 |
+
print(f"✅ Broker URL: {celery_app.conf.broker_url}")
|
| 49 |
+
print(f"✅ Registered Tasks: {list(celery_app.tasks.keys())}")
|
| 50 |
+
except Exception as e:
|
| 51 |
+
print(f"❌ Celery check failed: {e}")
|
| 52 |
+
|
| 53 |
+
def check_google_calendar():
|
| 54 |
+
print("\n🔍 Checking Google Calendar Service...")
|
| 55 |
+
try:
|
| 56 |
+
service = get_google_calendar_service()
|
| 57 |
+
# Mock tenant ID
|
| 58 |
+
from uuid import uuid4
|
| 59 |
+
url = service.get_auth_url(uuid4())
|
| 60 |
+
if "accounts.google.com" in url:
|
| 61 |
+
print("✅ Auth URL generation working.")
|
| 62 |
+
else:
|
| 63 |
+
print("❌ Auth URL unexpected format.")
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"❌ Google Calendar check failed: {e}")
|
| 66 |
+
|
| 67 |
+
async def main():
|
| 68 |
+
print("🏥 STARTING SYSTEM HEALTH CHECK")
|
| 69 |
+
await check_db()
|
| 70 |
+
await check_redis()
|
| 71 |
+
check_celery()
|
| 72 |
+
check_google_calendar()
|
| 73 |
+
print("\n🏁 Health Check Complete.")
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
if sys.platform == 'win32':
|
| 77 |
+
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
| 78 |
+
asyncio.run(main())
|
backend/scripts/patch_db_schema.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sqlalchemy import text
|
| 2 |
+
from app.core.database import async_engine as engine
|
| 3 |
+
import asyncio
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
# Configure logging
|
| 7 |
+
logging.basicConfig(level=logging.INFO)
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
async def patch_schema():
|
| 11 |
+
logger.info("🔧 Starting manual schema patch...")
|
| 12 |
+
|
| 13 |
+
async with engine.begin() as conn:
|
| 14 |
+
# 1. Add Stripe Fields to Tenants
|
| 15 |
+
logger.info("Checking/Adding Stripe fields...")
|
| 16 |
+
await conn.execute(text("""
|
| 17 |
+
DO $$
|
| 18 |
+
BEGIN
|
| 19 |
+
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='stripe_customer_id') THEN
|
| 20 |
+
ALTER TABLE tenants ADD COLUMN stripe_customer_id TEXT;
|
| 21 |
+
CREATE INDEX ix_tenants_stripe_customer_id ON tenants (stripe_customer_id);
|
| 22 |
+
RAISE NOTICE 'Added stripe_customer_id';
|
| 23 |
+
END IF;
|
| 24 |
+
|
| 25 |
+
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='stripe_subscription_id') THEN
|
| 26 |
+
ALTER TABLE tenants ADD COLUMN stripe_subscription_id TEXT;
|
| 27 |
+
RAISE NOTICE 'Added stripe_subscription_id';
|
| 28 |
+
END IF;
|
| 29 |
+
END $$;
|
| 30 |
+
"""))
|
| 31 |
+
|
| 32 |
+
# 2. Fix Embedding Dimension
|
| 33 |
+
# Note: This might fail if data is incompatible, but intended for fixing schema mismatch.
|
| 34 |
+
logger.info("Fixing Embedding dimension (384 -> 1536)...")
|
| 35 |
+
try:
|
| 36 |
+
await conn.execute(text("""
|
| 37 |
+
ALTER TABLE knowledge_base
|
| 38 |
+
ALTER COLUMN embedding TYPE vector(1536)
|
| 39 |
+
USING embedding::vector(1536);
|
| 40 |
+
"""))
|
| 41 |
+
logger.info("✅ Embedding dimension updated to 1536.")
|
| 42 |
+
except Exception as e:
|
| 43 |
+
logger.warning(f"⚠️ Could not update embedding dimension (might already be 1536 or PGVector issue): {e}")
|
| 44 |
+
|
| 45 |
+
# 3. Add Meta Config Columns (from failed migration)
|
| 46 |
+
# meta_wa_config, meta_ig_config
|
| 47 |
+
logger.info("Checking/Adding Meta Config fields...")
|
| 48 |
+
await conn.execute(text("""
|
| 49 |
+
DO $$
|
| 50 |
+
BEGIN
|
| 51 |
+
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='meta_wa_config') THEN
|
| 52 |
+
ALTER TABLE tenants ADD COLUMN meta_wa_config JSON;
|
| 53 |
+
RAISE NOTICE 'Added meta_wa_config';
|
| 54 |
+
END IF;
|
| 55 |
+
|
| 56 |
+
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='meta_ig_config') THEN
|
| 57 |
+
ALTER TABLE tenants ADD COLUMN meta_ig_config JSON;
|
| 58 |
+
RAISE NOTICE 'Added meta_ig_config';
|
| 59 |
+
END IF;
|
| 60 |
+
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='tenants' AND column_name='google_calendar_config') THEN
|
| 61 |
+
ALTER TABLE tenants ADD COLUMN google_calendar_config JSON;
|
| 62 |
+
RAISE NOTICE 'Added google_calendar_config';
|
| 63 |
+
END IF;
|
| 64 |
+
END $$;
|
| 65 |
+
"""))
|
| 66 |
+
|
| 67 |
+
logger.info("🎉 Schema patch completed successfully.")
|
| 68 |
+
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
asyncio.run(patch_schema())
|
backend/scripts/test_meta_ig.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# Add backend to path
|
| 6 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
| 7 |
+
|
| 8 |
+
from app.services.meta_instagram import get_instagram_graph_service
|
| 9 |
+
from app.models.tenant import Tenant
|
| 10 |
+
|
| 11 |
+
async def test_send_ig():
|
| 12 |
+
print("🚀 Testing Meta Instagram Graph API...")
|
| 13 |
+
|
| 14 |
+
# MOCK Tenant
|
| 15 |
+
tenant = Tenant(
|
| 16 |
+
business_name="Test Business",
|
| 17 |
+
meta_ig_config={
|
| 18 |
+
"page_id": "YOUR_FACEBOOK_PAGE_ID",
|
| 19 |
+
"access_token": "YOUR_PAGE_ACCESS_TOKEN"
|
| 20 |
+
}
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
service = get_instagram_graph_service()
|
| 24 |
+
|
| 25 |
+
recipient_id = input("Enter IG User ID (PSID): ")
|
| 26 |
+
if not recipient_id:
|
| 27 |
+
print("❌ Recipient ID required.")
|
| 28 |
+
return
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
print(f"📤 Sending DM to {recipient_id}...")
|
| 32 |
+
response = await service.send_message(
|
| 33 |
+
tenant=tenant,
|
| 34 |
+
recipient_id=recipient_id,
|
| 35 |
+
text="Hello from MicroFunnel Studio (Official IG API)! 📸"
|
| 36 |
+
)
|
| 37 |
+
print("✅ Success!", response)
|
| 38 |
+
except Exception as e:
|
| 39 |
+
print(f"❌ Failed: {e}")
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
asyncio.run(test_send_ig())
|
backend/scripts/test_meta_wa.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# Add backend to path
|
| 6 |
+
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
|
| 7 |
+
|
| 8 |
+
from app.services.meta_whatsapp import get_whatsapp_cloud_service
|
| 9 |
+
from app.models.tenant import Tenant
|
| 10 |
+
|
| 11 |
+
async def test_send():
|
| 12 |
+
print("🚀 Testing Meta WhatsApp Cloud API...")
|
| 13 |
+
|
| 14 |
+
# MOCK Tenant for testing (Replace with real tokens to test)
|
| 15 |
+
# You can also fetch a real tenant from DB if you prefer
|
| 16 |
+
tenant = Tenant(
|
| 17 |
+
business_name="Test Business",
|
| 18 |
+
meta_wa_config={
|
| 19 |
+
"phone_number_id": "YOUR_PHONE_ID",
|
| 20 |
+
"access_token": "YOUR_ACCESS_TOKEN"
|
| 21 |
+
}
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
service = get_whatsapp_cloud_service()
|
| 25 |
+
|
| 26 |
+
to_phone = input("Enter recipient phone number (e.g. 15551234567): ")
|
| 27 |
+
if not to_phone:
|
| 28 |
+
print("❌ Phone number required.")
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
print(f"📤 Sending message to {to_phone}...")
|
| 33 |
+
response = await service.send_text_message(
|
| 34 |
+
tenant=tenant,
|
| 35 |
+
to_phone=to_phone,
|
| 36 |
+
text="Hello from MicroFunnel Studio (Official API)! 🚀"
|
| 37 |
+
)
|
| 38 |
+
print("✅ Success!", response)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
print(f"❌ Failed: {e}")
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
asyncio.run(test_send())
|
backend/scripts/test_voice.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
# Add parent directory to path
|
| 6 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 7 |
+
|
| 8 |
+
from app.services.voice_service import voice_service
|
| 9 |
+
|
| 10 |
+
async def main():
|
| 11 |
+
text = "This is MicroFunnel Command Center. Systems initialized. Deployment authorized."
|
| 12 |
+
print(f"Generating audio for: '{text}'")
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
audio_bytes = await voice_service.generate_audio(text, voice="onyx")
|
| 16 |
+
|
| 17 |
+
output_file = "test_voice.mp3"
|
| 18 |
+
with open(output_file, "wb") as f:
|
| 19 |
+
f.write(audio_bytes)
|
| 20 |
+
|
| 21 |
+
print(f"✅ Success! Audio saved to {output_file}")
|
| 22 |
+
print(f"📊 Size: {len(audio_bytes)} bytes")
|
| 23 |
+
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"❌ Error: {e}")
|
| 26 |
+
|
| 27 |
+
if __name__ == "__main__":
|
| 28 |
+
asyncio.run(main())
|
backend/test_voice.mp3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b784721d828acc573446f08f290cea2cb5547b1bc88315f4dc3249bab9016a93
|
| 3 |
+
size 98880
|
frontend/app/dashboard/page.tsx
CHANGED
|
@@ -63,27 +63,27 @@ interface DashboardData {
|
|
| 63 |
lead_value_over_time: LeadValueOverTime[]
|
| 64 |
}
|
| 65 |
|
| 66 |
-
// DISC Colors (
|
| 67 |
const DISC_COLORS = {
|
| 68 |
-
'Dominant': '#
|
| 69 |
-
'Influential': '#
|
| 70 |
-
'Steady': '#
|
| 71 |
-
'Conscientious': '#
|
| 72 |
-
'Unknown': '#
|
| 73 |
}
|
| 74 |
|
| 75 |
const PSYCHOTYPE_RUSSIAN: Record<string, string> = {
|
| 76 |
-
'Dominant': 'Доминант
|
| 77 |
'Influential': 'Влияющий',
|
| 78 |
'Steady': 'Стабильный',
|
| 79 |
-
'Conscientious': 'А
|
| 80 |
'Unknown': 'Неизвестно'
|
| 81 |
}
|
| 82 |
|
| 83 |
const STAGE_RUSSIAN: Record<string, string> = {
|
| 84 |
-
'New': '
|
| 85 |
'Contacted': 'Контакт',
|
| 86 |
-
'Qualified': 'Квалиф
|
| 87 |
'Negotiation': 'Переговоры',
|
| 88 |
'Closed': 'Сделка'
|
| 89 |
}
|
|
@@ -101,10 +101,10 @@ export default function DashboardPage() {
|
|
| 101 |
|
| 102 |
const getDateRangeLabel = () => {
|
| 103 |
switch (dateRange) {
|
| 104 |
-
case '7d': return '
|
| 105 |
-
case '30d': return '
|
| 106 |
-
case '90d': return '
|
| 107 |
-
case 'all': return '
|
| 108 |
}
|
| 109 |
}
|
| 110 |
|
|
@@ -139,7 +139,7 @@ export default function DashboardPage() {
|
|
| 139 |
})
|
| 140 |
|
| 141 |
if (!response.ok) {
|
| 142 |
-
throw new Error('
|
| 143 |
}
|
| 144 |
|
| 145 |
const analyticsData = await response.json()
|
|
@@ -147,7 +147,7 @@ export default function DashboardPage() {
|
|
| 147 |
setLastUpdated(new Date())
|
| 148 |
} catch (err) {
|
| 149 |
console.error('Analytics fetch error:', err)
|
| 150 |
-
setError('
|
| 151 |
} finally {
|
| 152 |
setLoading(false)
|
| 153 |
}
|
|
@@ -157,7 +157,7 @@ export default function DashboardPage() {
|
|
| 157 |
if (authLoading) return
|
| 158 |
|
| 159 |
if (!user) {
|
| 160 |
-
setError('
|
| 161 |
setLoading(false)
|
| 162 |
return
|
| 163 |
}
|
|
@@ -165,20 +165,20 @@ export default function DashboardPage() {
|
|
| 165 |
fetchAnalytics()
|
| 166 |
}, [user, authLoading, dateRange])
|
| 167 |
|
| 168 |
-
// Custom Tooltip Component
|
| 169 |
const CustomTooltip = ({ active, payload, label }: any) => {
|
| 170 |
if (active && payload && payload.length) {
|
| 171 |
return (
|
| 172 |
-
<div className="bg-
|
| 173 |
-
<p className="text-
|
| 174 |
{payload.map((entry: any, index: number) => (
|
| 175 |
-
<div key={index} className="flex items-center gap-2 text-xs">
|
| 176 |
<div
|
| 177 |
-
className="w-
|
| 178 |
style={{ backgroundColor: entry.color }}
|
| 179 |
/>
|
| 180 |
-
<span className="text-slate-
|
| 181 |
-
<span className="font-bold text-
|
| 182 |
{typeof entry.value === 'number'
|
| 183 |
? entry.name.includes('Value') || entry.name.includes('Пайплайн')
|
| 184 |
? `$${entry.value.toLocaleString()}`
|
|
@@ -193,14 +193,14 @@ export default function DashboardPage() {
|
|
| 193 |
return null
|
| 194 |
}
|
| 195 |
|
| 196 |
-
// Percent Change Component
|
| 197 |
const PercentChange = ({ value }: { value: number }) => {
|
| 198 |
-
if (value === 0) return <span className="text-slate-
|
| 199 |
const isPositive = value > 0
|
| 200 |
return (
|
| 201 |
<span className={cn(
|
| 202 |
-
"flex items-center gap-1 text-
|
| 203 |
-
isPositive ? "text-emerald-
|
| 204 |
)}>
|
| 205 |
{isPositive ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />}
|
| 206 |
{Math.abs(value)}%
|
|
@@ -210,10 +210,10 @@ export default function DashboardPage() {
|
|
| 210 |
|
| 211 |
if (authLoading || (loading && !data)) {
|
| 212 |
return (
|
| 213 |
-
<div className="flex items-center justify-center min-h-screen bg-
|
| 214 |
<div className="flex flex-col items-center gap-4">
|
| 215 |
-
<
|
| 216 |
-
<p className="text-
|
| 217 |
</div>
|
| 218 |
</div>
|
| 219 |
)
|
|
@@ -221,19 +221,17 @@ export default function DashboardPage() {
|
|
| 221 |
|
| 222 |
if (error) {
|
| 223 |
return (
|
| 224 |
-
<div className="flex items-center justify-center min-h-screen bg-
|
| 225 |
-
<div className="bg-
|
| 226 |
-
<
|
| 227 |
-
|
| 228 |
-
</
|
| 229 |
-
<h2 className="text-xl font-bold text-slate-900 mb-2">Ошибка загрузки</h2>
|
| 230 |
-
<p className="text-slate-600 mb-6">{error}</p>
|
| 231 |
<button
|
| 232 |
onClick={fetchAnalytics}
|
| 233 |
-
className="px-6 py-2 bg-
|
| 234 |
>
|
| 235 |
<RefreshCw className="w-4 h-4" />
|
| 236 |
-
|
| 237 |
</button>
|
| 238 |
</div>
|
| 239 |
</div>
|
|
@@ -243,21 +241,17 @@ export default function DashboardPage() {
|
|
| 243 |
if (!data) return null
|
| 244 |
|
| 245 |
return (
|
| 246 |
-
<div className="min-h-screen bg-
|
| 247 |
-
<div className="max-w-7xl mx-auto space-y-
|
| 248 |
|
| 249 |
{/* Header */}
|
| 250 |
-
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
| 251 |
<div>
|
| 252 |
-
<h1 className="text-
|
|
|
|
|
|
|
| 253 |
<div className="flex items-center gap-2 mt-1">
|
| 254 |
-
<p className="text-slate-500">
|
| 255 |
-
{lastUpdated && (
|
| 256 |
-
<span className="text-xs text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full flex items-center gap-1">
|
| 257 |
-
<Clock className="w-3 h-3" />
|
| 258 |
-
Обновлено: {lastUpdated.toLocaleTimeString()}
|
| 259 |
-
</span>
|
| 260 |
-
)}
|
| 261 |
</div>
|
| 262 |
</div>
|
| 263 |
<div className="flex items-center gap-3">
|
|
@@ -265,28 +259,28 @@ export default function DashboardPage() {
|
|
| 265 |
<div className="relative">
|
| 266 |
<button
|
| 267 |
onClick={() => setIsDateDropdownOpen(!isDateDropdownOpen)}
|
| 268 |
-
className="px-4 py-2 bg-
|
| 269 |
>
|
| 270 |
<div className="flex items-center gap-2">
|
| 271 |
-
<Calendar className="w-
|
| 272 |
{getDateRangeLabel()}
|
| 273 |
</div>
|
| 274 |
-
<ArrowUp className={cn("w-3 h-3
|
| 275 |
</button>
|
| 276 |
|
| 277 |
<AnimatePresence>
|
| 278 |
{isDateDropdownOpen && (
|
| 279 |
<motion.div
|
| 280 |
-
initial={{ opacity: 0, y:
|
| 281 |
animate={{ opacity: 1, y: 0 }}
|
| 282 |
-
exit={{ opacity: 0, y:
|
| 283 |
-
className="absolute top-full right-0 mt-2 w-[
|
| 284 |
>
|
| 285 |
{[
|
| 286 |
-
{ val: '7d', label: '
|
| 287 |
-
{ val: '30d', label: '
|
| 288 |
-
{ val: '90d', label: '
|
| 289 |
-
{ val: 'all', label: '
|
| 290 |
].map((option) => (
|
| 291 |
<button
|
| 292 |
key={option.val}
|
|
@@ -295,8 +289,8 @@ export default function DashboardPage() {
|
|
| 295 |
setIsDateDropdownOpen(false)
|
| 296 |
}}
|
| 297 |
className={cn(
|
| 298 |
-
"w-full text-left px-4 py-2 text-
|
| 299 |
-
dateRange === option.val ? "text-indigo-
|
| 300 |
)}
|
| 301 |
>
|
| 302 |
{option.label}
|
|
@@ -311,206 +305,115 @@ export default function DashboardPage() {
|
|
| 311 |
{/* Refresh Button */}
|
| 312 |
<button
|
| 313 |
onClick={fetchAnalytics}
|
| 314 |
-
className="p-2 bg-
|
| 315 |
-
title="
|
| 316 |
>
|
| 317 |
-
<RefreshCw className="w-
|
| 318 |
</button>
|
| 319 |
</div>
|
| 320 |
</div>
|
| 321 |
|
| 322 |
{/* Key Metrics Grid */}
|
| 323 |
-
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-
|
|
|
|
| 324 |
{/* Total Leads */}
|
| 325 |
-
<
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
<div className="flex items-center justify-between mb-4">
|
| 334 |
-
<div className="w-12 h-12 bg-indigo-50 rounded-xl flex items-center justify-center text-indigo-600 group-hover:scale-110 transition-transform duration-300">
|
| 335 |
-
<Users className="w-6 h-6" />
|
| 336 |
-
</div>
|
| 337 |
-
<PercentChange value={data.metrics.total_leads_change} />
|
| 338 |
-
</div>
|
| 339 |
-
<p className="text-slate-500 text-sm font-medium uppercase tracking-wide">Всего лидов</p>
|
| 340 |
-
<h3 className="text-3xl font-bold text-slate-900 mt-1">{data.metrics.total_leads}</h3>
|
| 341 |
</div>
|
| 342 |
-
|
|
|
|
| 343 |
|
| 344 |
{/* Pipeline Value */}
|
| 345 |
-
<
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
<div className="relative z-10">
|
| 353 |
-
<div className="flex items-center justify-between mb-4">
|
| 354 |
-
<div className="w-12 h-12 bg-emerald-50 rounded-xl flex items-center justify-center text-emerald-600 group-hover:scale-110 transition-transform duration-300">
|
| 355 |
-
<DollarSign className="w-6 h-6" />
|
| 356 |
-
</div>
|
| 357 |
-
<PercentChange value={data.metrics.pipeline_value_change} />
|
| 358 |
-
</div>
|
| 359 |
-
<p className="text-slate-500 text-sm font-medium uppercase tracking-wide">Пайплайн</p>
|
| 360 |
-
<h3 className="text-3xl font-bold text-slate-900 mt-1">
|
| 361 |
${data.metrics.pipeline_value.toLocaleString()}
|
| 362 |
</h3>
|
|
|
|
| 363 |
</div>
|
| 364 |
-
|
|
|
|
| 365 |
|
| 366 |
{/* Conversion Rate */}
|
| 367 |
-
<
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
<div className="relative z-10">
|
| 375 |
-
<div className="flex items-center justify-between mb-4">
|
| 376 |
-
<div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center text-blue-600 group-hover:scale-110 transition-transform duration-300">
|
| 377 |
-
<Target className="w-6 h-6" />
|
| 378 |
-
</div>
|
| 379 |
-
<PercentChange value={data.metrics.conversion_rate_change} />
|
| 380 |
-
</div>
|
| 381 |
-
<p className="text-slate-500 text-sm font-medium uppercase tracking-wide">Конверсия</p>
|
| 382 |
-
<h3 className="text-3xl font-bold text-slate-900 mt-1">
|
| 383 |
{data.metrics.conversion_rate}%
|
| 384 |
</h3>
|
| 385 |
-
<
|
| 386 |
-
</div>
|
| 387 |
-
</motion.div>
|
| 388 |
-
|
| 389 |
-
{/* AI Efficiency */}
|
| 390 |
-
<motion.div
|
| 391 |
-
initial={{ opacity: 0, y: 20 }}
|
| 392 |
-
animate={{ opacity: 1, y: 0 }}
|
| 393 |
-
transition={{ delay: 0.4 }}
|
| 394 |
-
className="bg-gradient-to-br from-indigo-600 to-purple-700 p-6 rounded-2xl shadow-lg text-white relative overflow-hidden group hover:shadow-xl hover:-translate-y-1 transition-all duration-300"
|
| 395 |
-
>
|
| 396 |
-
<div className="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-8 -mt-8 blur-2xl transition-transform duration-700 group-hover:scale-125"></div>
|
| 397 |
-
<div className="relative z-10">
|
| 398 |
-
<div className="flex items-center justify-between mb-4">
|
| 399 |
-
<div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center text-white backdrop-blur-sm group-hover:rotate-12 transition-transform duration-300">
|
| 400 |
-
<Zap className="w-6 h-6" />
|
| 401 |
-
</div>
|
| 402 |
-
<span className="flex items-center gap-1 text-xs font-bold text-white/90 bg-white/20 px-2 py-1 rounded-full backdrop-blur-sm">
|
| 403 |
-
{data.metrics.active_leads_24h} Активных (24ч)
|
| 404 |
-
</span>
|
| 405 |
-
</div>
|
| 406 |
-
<p className="text-indigo-100 text-sm font-medium uppercase tracking-wide">Сэкономлено</p>
|
| 407 |
-
<div className="flex items-baseline gap-2 mt-1">
|
| 408 |
-
<h3 className="text-3xl font-bold text-white">
|
| 409 |
-
${data.metrics.money_saved.toLocaleString()}
|
| 410 |
-
</h3>
|
| 411 |
-
<span className="text-sm text-indigo-200">
|
| 412 |
-
/ {data.metrics.hours_saved} ч
|
| 413 |
-
</span>
|
| 414 |
-
</div>
|
| 415 |
</div>
|
| 416 |
-
|
| 417 |
-
|
| 418 |
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
transition={{ delay: 0.45 }}
|
| 426 |
-
className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4"
|
| 427 |
-
>
|
| 428 |
-
<div className="w-10 h-10 rounded-full bg-amber-50 flex items-center justify-center text-amber-600">
|
| 429 |
-
<Clock className="w-5 h-5" />
|
| 430 |
-
</div>
|
| 431 |
-
<div>
|
| 432 |
-
<p className="text-slate-500 text-xs uppercase font-bold tracking-wider">Ср. время ответа</p>
|
| 433 |
-
<h4 className="text-xl font-bold text-slate-900">{data.metrics.avg_response_time_seconds.toFixed(1)} сек</h4>
|
| 434 |
-
</div>
|
| 435 |
-
</motion.div>
|
| 436 |
-
|
| 437 |
-
{/* Total Bookings */}
|
| 438 |
-
<motion.div
|
| 439 |
-
initial={{ opacity: 0, y: 20 }}
|
| 440 |
-
animate={{ opacity: 1, y: 0 }}
|
| 441 |
-
transition={{ delay: 0.5 }}
|
| 442 |
-
className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4"
|
| 443 |
-
>
|
| 444 |
-
<div className="w-10 h-10 rounded-full bg-purple-50 flex items-center justify-center text-purple-600">
|
| 445 |
-
<Calendar className="w-5 h-5" />
|
| 446 |
-
</div>
|
| 447 |
-
<div>
|
| 448 |
-
<p className="text-slate-500 text-xs uppercase font-bold tracking-wider">Всего встреч</p>
|
| 449 |
-
<h4 className="text-xl font-bold text-slate-900">{data.metrics.total_bookings}</h4>
|
| 450 |
-
</div>
|
| 451 |
-
</motion.div>
|
| 452 |
-
|
| 453 |
-
{/* Active Leads Badge */}
|
| 454 |
-
<motion.div
|
| 455 |
-
initial={{ opacity: 0, y: 20 }}
|
| 456 |
-
animate={{ opacity: 1, y: 0 }}
|
| 457 |
-
transition={{ delay: 0.55 }}
|
| 458 |
-
className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm flex items-center gap-4"
|
| 459 |
-
>
|
| 460 |
-
<div className="w-10 h-10 rounded-full bg-pink-50 flex items-center justify-center text-pink-600">
|
| 461 |
-
<MessageSquare className="w-5 h-5" />
|
| 462 |
</div>
|
| 463 |
-
<div>
|
| 464 |
-
<
|
| 465 |
-
|
|
|
|
|
|
|
| 466 |
</div>
|
| 467 |
-
</
|
| 468 |
</div>
|
| 469 |
|
|
|
|
| 470 |
{/* Charts Section */}
|
| 471 |
-
<div className="grid grid-cols-1 lg:grid-cols-3 gap-
|
| 472 |
|
| 473 |
{/* Main Chart: Pipeline Value */}
|
| 474 |
-
<
|
| 475 |
-
initial={{ opacity: 0, y: 20 }}
|
| 476 |
-
animate={{ opacity: 1, y: 0 }}
|
| 477 |
-
transition={{ delay: 0.5 }}
|
| 478 |
-
className="lg:col-span-2 bg-white p-6 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow"
|
| 479 |
-
>
|
| 480 |
<div className="flex items-center justify-between mb-6">
|
| 481 |
<div>
|
| 482 |
-
<h3 className="text-
|
| 483 |
-
<p className="text-sm text-slate-500">Рост стоимости сделок за период</p>
|
| 484 |
-
</div>
|
| 485 |
-
<div className="p-2 bg-indigo-50 rounded-lg">
|
| 486 |
-
<TrendingUp className="w-5 h-5 text-indigo-600" />
|
| 487 |
</div>
|
|
|
|
| 488 |
</div>
|
| 489 |
-
<div className="h-[
|
| 490 |
<ResponsiveContainer width="100%" height="100%">
|
| 491 |
<AreaChart data={data.lead_value_over_time}>
|
| 492 |
<defs>
|
| 493 |
<linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
|
| 494 |
-
<stop offset="5%" stopColor="#
|
| 495 |
-
<stop offset="95%" stopColor="#
|
| 496 |
</linearGradient>
|
| 497 |
</defs>
|
| 498 |
-
<CartesianGrid strokeDasharray="3 3" stroke="#
|
| 499 |
<XAxis
|
| 500 |
dataKey="date"
|
| 501 |
-
stroke="#
|
| 502 |
-
fontSize={
|
|
|
|
| 503 |
tickLine={false}
|
| 504 |
axisLine={false}
|
| 505 |
dy={10}
|
| 506 |
tickFormatter={(val) => {
|
| 507 |
const d = new Date(val);
|
| 508 |
-
return d.toLocaleDateString('
|
| 509 |
}}
|
| 510 |
/>
|
| 511 |
<YAxis
|
| 512 |
-
stroke="#
|
| 513 |
-
fontSize={
|
|
|
|
| 514 |
tickLine={false}
|
| 515 |
axisLine={false}
|
| 516 |
tickFormatter={(value) => `$${value}`}
|
|
@@ -520,91 +423,74 @@ export default function DashboardPage() {
|
|
| 520 |
<Area
|
| 521 |
type="monotone"
|
| 522 |
dataKey="value"
|
| 523 |
-
stroke="#
|
| 524 |
-
strokeWidth={
|
| 525 |
fillOpacity={1}
|
| 526 |
fill="url(#colorValue)"
|
| 527 |
-
name="
|
|
|
|
| 528 |
/>
|
| 529 |
</AreaChart>
|
| 530 |
</ResponsiveContainer>
|
| 531 |
</div>
|
| 532 |
-
</
|
| 533 |
|
| 534 |
{/* Funnel Chart */}
|
| 535 |
-
<
|
| 536 |
-
initial={{ opacity: 0, y: 20 }}
|
| 537 |
-
animate={{ opacity: 1, y: 0 }}
|
| 538 |
-
transition={{ delay: 0.6 }}
|
| 539 |
-
className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow"
|
| 540 |
-
>
|
| 541 |
<div className="flex items-center justify-between mb-6">
|
| 542 |
<div>
|
| 543 |
-
<h3 className="text-
|
| 544 |
-
<p className="text-sm text-slate-500">Конверсия по этапам</p>
|
| 545 |
-
</div>
|
| 546 |
-
<div className="p-2 bg-emerald-50 rounded-lg">
|
| 547 |
-
<Activity className="w-5 h-5 text-emerald-600" />
|
| 548 |
</div>
|
| 549 |
</div>
|
| 550 |
<div className="space-y-4">
|
| 551 |
{data.funnel.map((stage, index) => (
|
| 552 |
<div key={index} className="relative group cursor-default">
|
| 553 |
-
<div className="flex items-center justify-between text-
|
| 554 |
-
<span className="
|
| 555 |
{STAGE_RUSSIAN[stage.stage] || stage.stage}
|
| 556 |
</span>
|
| 557 |
-
<span className="font-bold text-
|
| 558 |
</div>
|
| 559 |
-
<div className="h-
|
| 560 |
<motion.div
|
| 561 |
initial={{ width: 0 }}
|
| 562 |
animate={{ width: `${stage.percentage}%` }}
|
| 563 |
transition={{ duration: 1, delay: 0.5 + index * 0.1 }}
|
| 564 |
className={cn(
|
| 565 |
-
"h-full rounded-full transition-all duration-300 group-hover:brightness-
|
| 566 |
-
index === 0 ? "bg-indigo-
|
| 567 |
-
index === 1 ? "bg-indigo-
|
| 568 |
index === 2 ? "bg-indigo-500" :
|
| 569 |
-
index === 3 ? "bg-indigo-
|
| 570 |
-
"bg-emerald-
|
| 571 |
)}
|
| 572 |
/>
|
| 573 |
</div>
|
| 574 |
-
<div className="text-
|
| 575 |
{stage.percentage.toFixed(1)}%
|
| 576 |
</div>
|
| 577 |
</div>
|
| 578 |
))}
|
| 579 |
</div>
|
| 580 |
-
</
|
| 581 |
|
| 582 |
{/* DISC Distribution */}
|
| 583 |
-
<
|
| 584 |
-
|
| 585 |
-
animate={{ opacity: 1, y: 0 }}
|
| 586 |
-
transition={{ delay: 0.7 }}
|
| 587 |
-
className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow"
|
| 588 |
-
>
|
| 589 |
-
<div className="flex items-center justify-between mb-6">
|
| 590 |
<div>
|
| 591 |
-
<h3 className="text-
|
| 592 |
-
<p className="text-sm text-slate-500">Распределение базы</p>
|
| 593 |
-
</div>
|
| 594 |
-
<div className="p-2 bg-blue-50 rounded-lg">
|
| 595 |
-
<Users className="w-5 h-5 text-blue-600" />
|
| 596 |
</div>
|
| 597 |
</div>
|
| 598 |
-
<div className="h-[
|
| 599 |
<ResponsiveContainer width="100%" height="100%">
|
| 600 |
<PieChart>
|
| 601 |
<Pie
|
| 602 |
data={data.disc_distribution as any[]}
|
| 603 |
cx="50%"
|
| 604 |
cy="50%"
|
| 605 |
-
innerRadius={
|
| 606 |
-
outerRadius={
|
| 607 |
-
paddingAngle={
|
| 608 |
dataKey="count"
|
| 609 |
nameKey="psychotype"
|
| 610 |
stroke="none"
|
|
@@ -613,7 +499,7 @@ export default function DashboardPage() {
|
|
| 613 |
<Cell
|
| 614 |
key={`cell-${index}`}
|
| 615 |
fill={DISC_COLORS[entry.psychotype as keyof typeof DISC_COLORS] || DISC_COLORS['Unknown']}
|
| 616 |
-
className="hover:opacity-80 transition-opacity cursor-pointer"
|
| 617 |
/>
|
| 618 |
))}
|
| 619 |
</Pie>
|
|
@@ -623,68 +509,27 @@ export default function DashboardPage() {
|
|
| 623 |
{/* Center Text */}
|
| 624 |
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
| 625 |
<div className="text-center">
|
| 626 |
-
<span className="block text-
|
| 627 |
-
<span className="text-
|
| 628 |
</div>
|
| 629 |
</div>
|
| 630 |
</div>
|
| 631 |
-
|
|
|
|
| 632 |
{(data.disc_distribution as any[]).map((item, index) => (
|
| 633 |
-
<div key={index} className="flex items-center gap-
|
| 634 |
<div
|
| 635 |
-
className="w-
|
| 636 |
style={{ backgroundColor: DISC_COLORS[item.psychotype as keyof typeof DISC_COLORS] || DISC_COLORS['Unknown'] }}
|
| 637 |
/>
|
| 638 |
-
<span className="text-slate-
|
| 639 |
-
{
|
| 640 |
</span>
|
| 641 |
-
<span className="font-bold text-
|
| 642 |
</div>
|
| 643 |
))}
|
| 644 |
</div>
|
| 645 |
-
</
|
| 646 |
-
|
| 647 |
-
{/* Top Objections */}
|
| 648 |
-
<motion.div
|
| 649 |
-
initial={{ opacity: 0, y: 20 }}
|
| 650 |
-
animate={{ opacity: 1, y: 0 }}
|
| 651 |
-
transition={{ delay: 0.8 }}
|
| 652 |
-
className="lg:col-span-2 bg-white p-6 rounded-2xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow"
|
| 653 |
-
>
|
| 654 |
-
<div className="flex items-center justify-between mb-6">
|
| 655 |
-
<div>
|
| 656 |
-
<h3 className="text-lg font-bold text-slate-900">Топ возражений</h3>
|
| 657 |
-
<p className="text-sm text-slate-500">Частые причины отказов</p>
|
| 658 |
-
</div>
|
| 659 |
-
<div className="p-2 bg-amber-50 rounded-lg">
|
| 660 |
-
<AlertCircle className="w-5 h-5 text-amber-600" />
|
| 661 |
-
</div>
|
| 662 |
-
</div>
|
| 663 |
-
<div className="h-[250px] w-full">
|
| 664 |
-
<ResponsiveContainer width="100%" height="100%">
|
| 665 |
-
<BarChart data={data.top_objections} layout="vertical" margin={{ left: 20 }}>
|
| 666 |
-
<CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0" horizontal={false} />
|
| 667 |
-
<XAxis type="number" hide />
|
| 668 |
-
<YAxis
|
| 669 |
-
dataKey="objection"
|
| 670 |
-
type="category"
|
| 671 |
-
width={150}
|
| 672 |
-
tick={{ fontSize: 12, fill: '#64748b' }}
|
| 673 |
-
tickLine={false}
|
| 674 |
-
axisLine={false}
|
| 675 |
-
/>
|
| 676 |
-
<Tooltip content={<CustomTooltip />} />
|
| 677 |
-
<Bar
|
| 678 |
-
dataKey="count"
|
| 679 |
-
fill="#F59E0B"
|
| 680 |
-
radius={[0, 4, 4, 0]}
|
| 681 |
-
barSize={20}
|
| 682 |
-
name="Количество"
|
| 683 |
-
/>
|
| 684 |
-
</BarChart>
|
| 685 |
-
</ResponsiveContainer>
|
| 686 |
-
</div>
|
| 687 |
-
</motion.div>
|
| 688 |
|
| 689 |
</div>
|
| 690 |
</div>
|
|
|
|
| 63 |
lead_value_over_time: LeadValueOverTime[]
|
| 64 |
}
|
| 65 |
|
| 66 |
+
// DISC Colors (Neon / High Contrast)
|
| 67 |
const DISC_COLORS = {
|
| 68 |
+
'Dominant': '#ef4444', // Red-500 Neon
|
| 69 |
+
'Influential': '#f59e0b', // Amber-500 Neon
|
| 70 |
+
'Steady': '#10b981', // Emerald-500 Neon
|
| 71 |
+
'Conscientious': '#3b82f6', // Blue-500 Neon
|
| 72 |
+
'Unknown': '#475569' // Slate-600
|
| 73 |
}
|
| 74 |
|
| 75 |
const PSYCHOTYPE_RUSSIAN: Record<string, string> = {
|
| 76 |
+
'Dominant': 'Доминант',
|
| 77 |
'Influential': 'Влияющий',
|
| 78 |
'Steady': 'Стабильный',
|
| 79 |
+
'Conscientious': 'Аналитик',
|
| 80 |
'Unknown': 'Неизвестно'
|
| 81 |
}
|
| 82 |
|
| 83 |
const STAGE_RUSSIAN: Record<string, string> = {
|
| 84 |
+
'New': 'Новый',
|
| 85 |
'Contacted': 'Контакт',
|
| 86 |
+
'Qualified': 'Квалиф.',
|
| 87 |
'Negotiation': 'Переговоры',
|
| 88 |
'Closed': 'Сделка'
|
| 89 |
}
|
|
|
|
| 101 |
|
| 102 |
const getDateRangeLabel = () => {
|
| 103 |
switch (dateRange) {
|
| 104 |
+
case '7d': return '7 Days'
|
| 105 |
+
case '30d': return '30 Days'
|
| 106 |
+
case '90d': return '90 Days'
|
| 107 |
+
case 'all': return 'All Time'
|
| 108 |
}
|
| 109 |
}
|
| 110 |
|
|
|
|
| 139 |
})
|
| 140 |
|
| 141 |
if (!response.ok) {
|
| 142 |
+
throw new Error('Failed to load analytics')
|
| 143 |
}
|
| 144 |
|
| 145 |
const analyticsData = await response.json()
|
|
|
|
| 147 |
setLastUpdated(new Date())
|
| 148 |
} catch (err) {
|
| 149 |
console.error('Analytics fetch error:', err)
|
| 150 |
+
setError('System Error. Please retry.')
|
| 151 |
} finally {
|
| 152 |
setLoading(false)
|
| 153 |
}
|
|
|
|
| 157 |
if (authLoading) return
|
| 158 |
|
| 159 |
if (!user) {
|
| 160 |
+
setError('Unauthorized access')
|
| 161 |
setLoading(false)
|
| 162 |
return
|
| 163 |
}
|
|
|
|
| 165 |
fetchAnalytics()
|
| 166 |
}, [user, authLoading, dateRange])
|
| 167 |
|
| 168 |
+
// Custom Tooltip Component (Dark Mode)
|
| 169 |
const CustomTooltip = ({ active, payload, label }: any) => {
|
| 170 |
if (active && payload && payload.length) {
|
| 171 |
return (
|
| 172 |
+
<div className="bg-[#0f1117] p-3 rounded-lg border border-slate-700 shadow-2xl z-50">
|
| 173 |
+
<p className="text-xs font-mono text-slate-400 mb-2">{label}</p>
|
| 174 |
{payload.map((entry: any, index: number) => (
|
| 175 |
+
<div key={index} className="flex items-center gap-2 text-xs font-mono">
|
| 176 |
<div
|
| 177 |
+
className="w-1.5 h-1.5 rounded-full"
|
| 178 |
style={{ backgroundColor: entry.color }}
|
| 179 |
/>
|
| 180 |
+
<span className="text-slate-300">{entry.name}:</span>
|
| 181 |
+
<span className="font-bold text-white">
|
| 182 |
{typeof entry.value === 'number'
|
| 183 |
? entry.name.includes('Value') || entry.name.includes('Пайплайн')
|
| 184 |
? `$${entry.value.toLocaleString()}`
|
|
|
|
| 193 |
return null
|
| 194 |
}
|
| 195 |
|
| 196 |
+
// Percent Change Component (Neon Style)
|
| 197 |
const PercentChange = ({ value }: { value: number }) => {
|
| 198 |
+
if (value === 0) return <span className="text-slate-500 text-[10px] font-mono">0%</span>
|
| 199 |
const isPositive = value > 0
|
| 200 |
return (
|
| 201 |
<span className={cn(
|
| 202 |
+
"flex items-center gap-1 text-[10px] font-bold px-1.5 py-0.5 rounded border font-mono",
|
| 203 |
+
isPositive ? "text-emerald-400 border-emerald-500/30 bg-emerald-500/10" : "text-rose-400 border-rose-500/30 bg-rose-500/10"
|
| 204 |
)}>
|
| 205 |
{isPositive ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />}
|
| 206 |
{Math.abs(value)}%
|
|
|
|
| 210 |
|
| 211 |
if (authLoading || (loading && !data)) {
|
| 212 |
return (
|
| 213 |
+
<div className="flex items-center justify-center min-h-screen bg-[#030014]">
|
| 214 |
<div className="flex flex-col items-center gap-4">
|
| 215 |
+
<div className="w-8 h-8 rounded-full border-2 border-indigo-500 border-t-transparent animate-spin"></div>
|
| 216 |
+
<p className="text-indigo-400 font-mono text-xs animate-pulse">INITIALIZING DASHBOARD...</p>
|
| 217 |
</div>
|
| 218 |
</div>
|
| 219 |
)
|
|
|
|
| 221 |
|
| 222 |
if (error) {
|
| 223 |
return (
|
| 224 |
+
<div className="flex items-center justify-center min-h-screen bg-[#030014]">
|
| 225 |
+
<div className="bg-[#0f1117] p-8 rounded-xl border border-red-500/30 max-w-md text-center">
|
| 226 |
+
<AlertCircle className="w-8 h-8 text-red-500 mx-auto mb-4" />
|
| 227 |
+
<h2 className="text-lg font-bold text-white mb-2 font-mono">SYSTEM ERROR</h2>
|
| 228 |
+
<p className="text-slate-400 mb-6 text-sm">{error}</p>
|
|
|
|
|
|
|
| 229 |
<button
|
| 230 |
onClick={fetchAnalytics}
|
| 231 |
+
className="px-6 py-2 bg-red-600/20 hover:bg-red-600/30 text-red-400 border border-red-500/50 rounded flex items-center gap-2 mx-auto transition-all"
|
| 232 |
>
|
| 233 |
<RefreshCw className="w-4 h-4" />
|
| 234 |
+
RETRY CONNECTION
|
| 235 |
</button>
|
| 236 |
</div>
|
| 237 |
</div>
|
|
|
|
| 241 |
if (!data) return null
|
| 242 |
|
| 243 |
return (
|
| 244 |
+
<div className="min-h-screen bg-[#030014] p-8 font-['Inter'] text-slate-200">
|
| 245 |
+
<div className="max-w-7xl mx-auto space-y-6">
|
| 246 |
|
| 247 |
{/* Header */}
|
| 248 |
+
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4 border-b border-white/5 pb-6">
|
| 249 |
<div>
|
| 250 |
+
<h1 className="text-2xl font-black text-white tracking-wider flex items-center gap-3">
|
| 251 |
+
COMMAND CENTER <span className="px-2 py-0.5 rounded bg-indigo-500/20 text-indigo-400 text-[10px] font-mono border border-indigo-500/30">LIVESTREAM</span>
|
| 252 |
+
</h1>
|
| 253 |
<div className="flex items-center gap-2 mt-1">
|
| 254 |
+
<p className="text-slate-500 text-xs font-mono">Performance Metrics & AI Status</p>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
</div>
|
| 256 |
</div>
|
| 257 |
<div className="flex items-center gap-3">
|
|
|
|
| 259 |
<div className="relative">
|
| 260 |
<button
|
| 261 |
onClick={() => setIsDateDropdownOpen(!isDateDropdownOpen)}
|
| 262 |
+
className="px-4 py-2 bg-[#0f1117] border border-white/10 rounded-lg text-xs font-mono text-slate-400 flex items-center gap-2 hover:border-indigo-500/50 transition-colors w-[180px] justify-between"
|
| 263 |
>
|
| 264 |
<div className="flex items-center gap-2">
|
| 265 |
+
<Calendar className="w-3 h-3" />
|
| 266 |
{getDateRangeLabel()}
|
| 267 |
</div>
|
| 268 |
+
<ArrowUp className={cn("w-3 h-3 transition-transform", isDateDropdownOpen ? "rotate-0" : "rotate-180")} />
|
| 269 |
</button>
|
| 270 |
|
| 271 |
<AnimatePresence>
|
| 272 |
{isDateDropdownOpen && (
|
| 273 |
<motion.div
|
| 274 |
+
initial={{ opacity: 0, y: 5 }}
|
| 275 |
animate={{ opacity: 1, y: 0 }}
|
| 276 |
+
exit={{ opacity: 0, y: 5 }}
|
| 277 |
+
className="absolute top-full right-0 mt-2 w-[180px] bg-[#0f1117] rounded-lg border border-white/10 z-50 overflow-hidden"
|
| 278 |
>
|
| 279 |
{[
|
| 280 |
+
{ val: '7d', label: '7 Days' },
|
| 281 |
+
{ val: '30d', label: '30 Days' },
|
| 282 |
+
{ val: '90d', label: '90 Days' },
|
| 283 |
+
{ val: 'all', label: 'All Time' }
|
| 284 |
].map((option) => (
|
| 285 |
<button
|
| 286 |
key={option.val}
|
|
|
|
| 289 |
setIsDateDropdownOpen(false)
|
| 290 |
}}
|
| 291 |
className={cn(
|
| 292 |
+
"w-full text-left px-4 py-2 text-xs font-mono transition-colors flex items-center justify-between hover:bg-white/5",
|
| 293 |
+
dateRange === option.val ? "text-indigo-400 bg-indigo-500/10" : "text-slate-400"
|
| 294 |
)}
|
| 295 |
>
|
| 296 |
{option.label}
|
|
|
|
| 305 |
{/* Refresh Button */}
|
| 306 |
<button
|
| 307 |
onClick={fetchAnalytics}
|
| 308 |
+
className="p-2 bg-[#0f1117] border border-white/10 rounded-lg hover:border-indigo-500/50 text-slate-400 transition-colors hover:rotate-180 duration-500"
|
| 309 |
+
title="Sync Data"
|
| 310 |
>
|
| 311 |
+
<RefreshCw className="w-4 h-4" />
|
| 312 |
</button>
|
| 313 |
</div>
|
| 314 |
</div>
|
| 315 |
|
| 316 |
{/* Key Metrics Grid */}
|
| 317 |
+
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
| 318 |
+
|
| 319 |
{/* Total Leads */}
|
| 320 |
+
<div className="glass-card p-5 rounded-xl relative overflow-hidden group">
|
| 321 |
+
<div className="flex items-center justify-between mb-2">
|
| 322 |
+
<span className="text-slate-500 text-[10px] font-bold uppercase tracking-widest font-mono">Total Leads</span>
|
| 323 |
+
<Users className="w-4 h-4 text-slate-600 group-hover:text-indigo-500 transition-colors" />
|
| 324 |
+
</div>
|
| 325 |
+
<div className="flex items-end justify-between">
|
| 326 |
+
<h3 className="text-3xl font-mono font-bold text-white tracking-tight">{data.metrics.total_leads}</h3>
|
| 327 |
+
<PercentChange value={data.metrics.total_leads_change} />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
</div>
|
| 329 |
+
<div className="absolute bottom-0 left-0 w-full h-1 bg-gradient-to-r from-indigo-500 to-transparent opacity-50"></div>
|
| 330 |
+
</div>
|
| 331 |
|
| 332 |
{/* Pipeline Value */}
|
| 333 |
+
<div className="glass-card p-5 rounded-xl relative overflow-hidden group">
|
| 334 |
+
<div className="flex items-center justify-between mb-2">
|
| 335 |
+
<span className="text-slate-500 text-[10px] font-bold uppercase tracking-widest font-mono">Pipeline Value</span>
|
| 336 |
+
<DollarSign className="w-4 h-4 text-slate-600 group-hover:text-emerald-500 transition-colors" />
|
| 337 |
+
</div>
|
| 338 |
+
<div className="flex items-end justify-between">
|
| 339 |
+
<h3 className="text-3xl font-mono font-bold text-white tracking-tight text-emerald-400 drop-shadow-[0_0_8px_rgba(16,185,129,0.3)]">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 340 |
${data.metrics.pipeline_value.toLocaleString()}
|
| 341 |
</h3>
|
| 342 |
+
<PercentChange value={data.metrics.pipeline_value_change} />
|
| 343 |
</div>
|
| 344 |
+
<div className="absolute bottom-0 left-0 w-full h-1 bg-gradient-to-r from-emerald-500 to-transparent opacity-50"></div>
|
| 345 |
+
</div>
|
| 346 |
|
| 347 |
{/* Conversion Rate */}
|
| 348 |
+
<div className="glass-card p-5 rounded-xl relative overflow-hidden group">
|
| 349 |
+
<div className="flex items-center justify-between mb-2">
|
| 350 |
+
<span className="text-slate-500 text-[10px] font-bold uppercase tracking-widest font-mono">Conversion</span>
|
| 351 |
+
<Target className="w-4 h-4 text-slate-600 group-hover:text-blue-500 transition-colors" />
|
| 352 |
+
</div>
|
| 353 |
+
<div className="flex items-end justify-between">
|
| 354 |
+
<h3 className="text-3xl font-mono font-bold text-white tracking-tight text-blue-400">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
{data.metrics.conversion_rate}%
|
| 356 |
</h3>
|
| 357 |
+
<PercentChange value={data.metrics.conversion_rate_change} />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
</div>
|
| 359 |
+
<div className="absolute bottom-0 left-0 w-full h-1 bg-gradient-to-r from-blue-500 to-transparent opacity-50"></div>
|
| 360 |
+
</div>
|
| 361 |
|
| 362 |
+
{/* Active AI Threads */}
|
| 363 |
+
<div className="glass-card p-5 rounded-xl relative overflow-hidden group border-indigo-500/30 bg-indigo-900/10">
|
| 364 |
+
<div className="absolute -right-4 -top-4 w-20 h-20 bg-indigo-500/20 blur-xl rounded-full"></div>
|
| 365 |
+
<div className="flex items-center justify-between mb-2 relative z-10">
|
| 366 |
+
<span className="text-indigo-300 text-[10px] font-bold uppercase tracking-widest font-mono">Active Threads (24h)</span>
|
| 367 |
+
<Zap className="w-4 h-4 text-indigo-400 animate-pulse" />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
</div>
|
| 369 |
+
<div className="flex items-end justify-between relative z-10">
|
| 370 |
+
<h3 className="text-3xl font-mono font-bold text-white tracking-tight">
|
| 371 |
+
{data.metrics.active_leads_24h}
|
| 372 |
+
</h3>
|
| 373 |
+
<span className="text-[10px] text-indigo-300 font-mono bg-indigo-500/20 px-1.5 py-0.5 rounded border border-indigo-500/30">ONLINE</span>
|
| 374 |
</div>
|
| 375 |
+
</div>
|
| 376 |
</div>
|
| 377 |
|
| 378 |
+
|
| 379 |
{/* Charts Section */}
|
| 380 |
+
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
| 381 |
|
| 382 |
{/* Main Chart: Pipeline Value */}
|
| 383 |
+
<div className="lg:col-span-2 glass-card p-6 rounded-xl">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
<div className="flex items-center justify-between mb-6">
|
| 385 |
<div>
|
| 386 |
+
<h3 className="text-sm font-bold text-white font-mono uppercase">Pipeline Velocity</h3>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
</div>
|
| 388 |
+
<Activity className="w-4 h-4 text-slate-500" />
|
| 389 |
</div>
|
| 390 |
+
<div className="h-[280px] w-full">
|
| 391 |
<ResponsiveContainer width="100%" height="100%">
|
| 392 |
<AreaChart data={data.lead_value_over_time}>
|
| 393 |
<defs>
|
| 394 |
<linearGradient id="colorValue" x1="0" y1="0" x2="0" y2="1">
|
| 395 |
+
<stop offset="5%" stopColor="#6366f1" stopOpacity={0.3} />
|
| 396 |
+
<stop offset="95%" stopColor="#6366f1" stopOpacity={0} />
|
| 397 |
</linearGradient>
|
| 398 |
</defs>
|
| 399 |
+
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" vertical={false} />
|
| 400 |
<XAxis
|
| 401 |
dataKey="date"
|
| 402 |
+
stroke="#475569"
|
| 403 |
+
fontSize={10}
|
| 404 |
+
fontFamily="monospace"
|
| 405 |
tickLine={false}
|
| 406 |
axisLine={false}
|
| 407 |
dy={10}
|
| 408 |
tickFormatter={(val) => {
|
| 409 |
const d = new Date(val);
|
| 410 |
+
return d.toLocaleDateString('en-US', { day: 'numeric', month: 'short' });
|
| 411 |
}}
|
| 412 |
/>
|
| 413 |
<YAxis
|
| 414 |
+
stroke="#475569"
|
| 415 |
+
fontSize={10}
|
| 416 |
+
fontFamily="monospace"
|
| 417 |
tickLine={false}
|
| 418 |
axisLine={false}
|
| 419 |
tickFormatter={(value) => `$${value}`}
|
|
|
|
| 423 |
<Area
|
| 424 |
type="monotone"
|
| 425 |
dataKey="value"
|
| 426 |
+
stroke="#6366f1"
|
| 427 |
+
strokeWidth={2}
|
| 428 |
fillOpacity={1}
|
| 429 |
fill="url(#colorValue)"
|
| 430 |
+
name="Pipeline"
|
| 431 |
+
activeDot={{ r: 6, strokeWidth: 0, fill: '#fff' }}
|
| 432 |
/>
|
| 433 |
</AreaChart>
|
| 434 |
</ResponsiveContainer>
|
| 435 |
</div>
|
| 436 |
+
</div>
|
| 437 |
|
| 438 |
{/* Funnel Chart */}
|
| 439 |
+
<div className="glass-card p-6 rounded-xl">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
<div className="flex items-center justify-between mb-6">
|
| 441 |
<div>
|
| 442 |
+
<h3 className="text-sm font-bold text-white font-mono uppercase">Conversion Funnel</h3>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
</div>
|
| 444 |
</div>
|
| 445 |
<div className="space-y-4">
|
| 446 |
{data.funnel.map((stage, index) => (
|
| 447 |
<div key={index} className="relative group cursor-default">
|
| 448 |
+
<div className="flex items-center justify-between text-xs mb-1 font-mono">
|
| 449 |
+
<span className="text-slate-400 group-hover:text-indigo-400 transition-colors uppercase">
|
| 450 |
{STAGE_RUSSIAN[stage.stage] || stage.stage}
|
| 451 |
</span>
|
| 452 |
+
<span className="font-bold text-white">{stage.count}</span>
|
| 453 |
</div>
|
| 454 |
+
<div className="h-1.5 bg-white/5 rounded-full overflow-hidden">
|
| 455 |
<motion.div
|
| 456 |
initial={{ width: 0 }}
|
| 457 |
animate={{ width: `${stage.percentage}%` }}
|
| 458 |
transition={{ duration: 1, delay: 0.5 + index * 0.1 }}
|
| 459 |
className={cn(
|
| 460 |
+
"h-full rounded-full transition-all duration-300 group-hover:brightness-125 shadow-[0_0_10px_rgba(99,102,241,0.5)]",
|
| 461 |
+
index === 0 ? "bg-indigo-700" :
|
| 462 |
+
index === 1 ? "bg-indigo-600" :
|
| 463 |
index === 2 ? "bg-indigo-500" :
|
| 464 |
+
index === 3 ? "bg-indigo-400" :
|
| 465 |
+
"bg-emerald-400"
|
| 466 |
)}
|
| 467 |
/>
|
| 468 |
</div>
|
| 469 |
+
<div className="text-[10px] text-slate-500 mt-1 text-right font-mono">
|
| 470 |
{stage.percentage.toFixed(1)}%
|
| 471 |
</div>
|
| 472 |
</div>
|
| 473 |
))}
|
| 474 |
</div>
|
| 475 |
+
</div>
|
| 476 |
|
| 477 |
{/* DISC Distribution */}
|
| 478 |
+
<div className="glass-card p-6 rounded-xl">
|
| 479 |
+
<div className="flex items-center justify-between mb-4">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
<div>
|
| 481 |
+
<h3 className="text-sm font-bold text-white font-mono uppercase">Psychograpics (DISC)</h3>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
</div>
|
| 483 |
</div>
|
| 484 |
+
<div className="h-[200px] w-full relative">
|
| 485 |
<ResponsiveContainer width="100%" height="100%">
|
| 486 |
<PieChart>
|
| 487 |
<Pie
|
| 488 |
data={data.disc_distribution as any[]}
|
| 489 |
cx="50%"
|
| 490 |
cy="50%"
|
| 491 |
+
innerRadius={50}
|
| 492 |
+
outerRadius={70}
|
| 493 |
+
paddingAngle={2}
|
| 494 |
dataKey="count"
|
| 495 |
nameKey="psychotype"
|
| 496 |
stroke="none"
|
|
|
|
| 499 |
<Cell
|
| 500 |
key={`cell-${index}`}
|
| 501 |
fill={DISC_COLORS[entry.psychotype as keyof typeof DISC_COLORS] || DISC_COLORS['Unknown']}
|
| 502 |
+
className="hover:opacity-80 transition-opacity cursor-pointer stroke-black stroke-2"
|
| 503 |
/>
|
| 504 |
))}
|
| 505 |
</Pie>
|
|
|
|
| 509 |
{/* Center Text */}
|
| 510 |
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
| 511 |
<div className="text-center">
|
| 512 |
+
<span className="block text-xl font-bold text-white font-mono">{data.metrics.total_leads}</span>
|
| 513 |
+
<span className="text-[8px] text-slate-500 uppercase tracking-widest">LEADS</span>
|
| 514 |
</div>
|
| 515 |
</div>
|
| 516 |
</div>
|
| 517 |
+
|
| 518 |
+
<div className="grid grid-cols-2 gap-2 mt-2">
|
| 519 |
{(data.disc_distribution as any[]).map((item, index) => (
|
| 520 |
+
<div key={index} className="flex items-center gap-1.5 text-[10px]">
|
| 521 |
<div
|
| 522 |
+
className="w-1.5 h-1.5 rounded-full"
|
| 523 |
style={{ backgroundColor: DISC_COLORS[item.psychotype as keyof typeof DISC_COLORS] || DISC_COLORS['Unknown'] }}
|
| 524 |
/>
|
| 525 |
+
<span className="text-slate-400 truncate font-mono uppercase">
|
| 526 |
+
{item.psychotype.slice(0, 4)}
|
| 527 |
</span>
|
| 528 |
+
<span className="font-bold text-white ml-auto font-mono">{item.percentage.toFixed(0)}%</span>
|
| 529 |
</div>
|
| 530 |
))}
|
| 531 |
</div>
|
| 532 |
+
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 533 |
|
| 534 |
</div>
|
| 535 |
</div>
|
frontend/app/globals.css
CHANGED
|
@@ -5,48 +5,86 @@ html {
|
|
| 5 |
scroll-behavior: smooth;
|
| 6 |
}
|
| 7 |
|
| 8 |
-
/*
|
|
|
|
|
|
|
|
|
|
| 9 |
:root {
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
--primary: #6366f1;
|
| 14 |
-
|
| 15 |
-
--
|
| 16 |
-
--
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
}
|
| 19 |
|
| 20 |
body {
|
| 21 |
background-color: var(--background);
|
|
|
|
| 22 |
background-image:
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
background-
|
|
|
|
| 26 |
color: var(--foreground);
|
| 27 |
-
font-family: 'Inter', sans-serif;
|
| 28 |
overflow-x: hidden;
|
| 29 |
min-height: 100vh;
|
| 30 |
}
|
| 31 |
|
| 32 |
-
/*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
input,
|
| 34 |
textarea,
|
| 35 |
select {
|
| 36 |
-
color: #
|
| 37 |
-
/*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
}
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
/* white text for dark backgrounds */
|
| 47 |
}
|
| 48 |
|
| 49 |
-
/*
|
| 50 |
input:-webkit-autofill,
|
| 51 |
input:-webkit-autofill:hover,
|
| 52 |
input:-webkit-autofill:focus,
|
|
@@ -54,46 +92,44 @@ input:-webkit-autofill:active {
|
|
| 54 |
-webkit-background-clip: text;
|
| 55 |
-webkit-text-fill-color: #ffffff !important;
|
| 56 |
transition: background-color 5000s ease-in-out 0s;
|
| 57 |
-
box-shadow: inset 0 0 20px 20px
|
| 58 |
-
/* slate-900-ish */
|
| 59 |
}
|
| 60 |
|
| 61 |
-
/*
|
| 62 |
::-webkit-scrollbar {
|
| 63 |
-
width:
|
| 64 |
}
|
| 65 |
|
| 66 |
::-webkit-scrollbar-track {
|
| 67 |
-
background:
|
| 68 |
}
|
| 69 |
|
| 70 |
::-webkit-scrollbar-thumb {
|
| 71 |
-
background:
|
| 72 |
-
border-radius:
|
| 73 |
}
|
| 74 |
|
| 75 |
::-webkit-scrollbar-thumb:hover {
|
| 76 |
-
background:
|
| 77 |
}
|
| 78 |
|
| 79 |
-
/*
|
| 80 |
-
.glass {
|
| 81 |
-
background:
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
border: 1px solid var(--
|
| 85 |
-
|
| 86 |
-
/* Hint for browser */
|
| 87 |
}
|
| 88 |
|
| 89 |
-
.glass-card {
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
}
|
| 98 |
|
| 99 |
/* Text Gradients */
|
|
@@ -202,6 +238,21 @@ input:-webkit-autofill:active {
|
|
| 202 |
animation: shimmer 2s linear infinite;
|
| 203 |
}
|
| 204 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
.input-glow:focus-within {
|
| 206 |
box-shadow: 0 0 20px -5px rgba(99, 102, 241, 0.4);
|
| 207 |
border-color: rgba(99, 102, 241, 0.5);
|
|
|
|
| 5 |
scroll-behavior: smooth;
|
| 6 |
}
|
| 7 |
|
| 8 |
+
/*
|
| 9 |
+
DESIGN SYSTEM: DARK MODE ENTERPRISE
|
| 10 |
+
"Command Center" Aesthetic
|
| 11 |
+
*/
|
| 12 |
:root {
|
| 13 |
+
/* The Void (Base) */
|
| 14 |
+
--background: #030014;
|
| 15 |
+
/* Deep Space */
|
| 16 |
+
--surface: #0f1117;
|
| 17 |
+
/* Gunmetal */
|
| 18 |
+
--surface-highlight: #1e293b;
|
| 19 |
+
|
| 20 |
+
/* The Energy (Accents) */
|
| 21 |
--primary: #6366f1;
|
| 22 |
+
/* Indigo */
|
| 23 |
+
--primary-glow: rgba(99, 102, 241, 0.5);
|
| 24 |
+
--accent: #f43f5e;
|
| 25 |
+
/* Rose Neon */
|
| 26 |
+
--cyan: #06b6d4;
|
| 27 |
+
/* Cyber Blue */
|
| 28 |
+
|
| 29 |
+
/* Text */
|
| 30 |
+
--foreground: #f8fafc;
|
| 31 |
+
--text-muted: #94a3b8;
|
| 32 |
+
|
| 33 |
+
/* Structure */
|
| 34 |
+
--border: rgba(255, 255, 255, 0.08);
|
| 35 |
+
--border-active: rgba(99, 102, 241, 0.5);
|
| 36 |
+
--radius-sm: 4px;
|
| 37 |
+
--radius-md: 8px;
|
| 38 |
}
|
| 39 |
|
| 40 |
body {
|
| 41 |
background-color: var(--background);
|
| 42 |
+
/* Hex Grid Background Pattern */
|
| 43 |
background-image:
|
| 44 |
+
linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
|
| 45 |
+
linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
|
| 46 |
+
background-size: 50px 50px;
|
| 47 |
+
background-position: center top;
|
| 48 |
color: var(--foreground);
|
| 49 |
+
font-family: 'Inter', system-ui, sans-serif;
|
| 50 |
overflow-x: hidden;
|
| 51 |
min-height: 100vh;
|
| 52 |
}
|
| 53 |
|
| 54 |
+
/* Add a vignette to focus center */
|
| 55 |
+
body::after {
|
| 56 |
+
content: "";
|
| 57 |
+
position: fixed;
|
| 58 |
+
inset: 0;
|
| 59 |
+
background: radial-gradient(circle at 50% 50%, transparent 0%, #030014 90%);
|
| 60 |
+
pointer-events: none;
|
| 61 |
+
z-index: -1;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
/* UTILITIES */
|
| 65 |
+
|
| 66 |
+
/* Inputs & Textareas - High Visibility */
|
| 67 |
input,
|
| 68 |
textarea,
|
| 69 |
select {
|
| 70 |
+
color: #f8fafc !important;
|
| 71 |
+
/* White text */
|
| 72 |
+
background-color: rgba(15, 23, 42, 0.6) !important;
|
| 73 |
+
/* Semi-transparent dark */
|
| 74 |
+
border: 1px solid var(--border) !important;
|
| 75 |
+
border-radius: var(--radius-md) !important;
|
| 76 |
+
transition: all 0.2s ease;
|
| 77 |
}
|
| 78 |
|
| 79 |
+
input:focus,
|
| 80 |
+
textarea:focus,
|
| 81 |
+
select:focus {
|
| 82 |
+
outline: none !important;
|
| 83 |
+
border-color: var(--primary) !important;
|
| 84 |
+
box-shadow: 0 0 15px -3px var(--primary-glow) !important;
|
|
|
|
| 85 |
}
|
| 86 |
|
| 87 |
+
/* Chrome/Edge Autofill Fix */
|
| 88 |
input:-webkit-autofill,
|
| 89 |
input:-webkit-autofill:hover,
|
| 90 |
input:-webkit-autofill:focus,
|
|
|
|
| 92 |
-webkit-background-clip: text;
|
| 93 |
-webkit-text-fill-color: #ffffff !important;
|
| 94 |
transition: background-color 5000s ease-in-out 0s;
|
| 95 |
+
box-shadow: inset 0 0 20px 20px #0f172a29;
|
|
|
|
| 96 |
}
|
| 97 |
|
| 98 |
+
/* Scrollbar - Sleek */
|
| 99 |
::-webkit-scrollbar {
|
| 100 |
+
width: 6px;
|
| 101 |
}
|
| 102 |
|
| 103 |
::-webkit-scrollbar-track {
|
| 104 |
+
background: #020005;
|
| 105 |
}
|
| 106 |
|
| 107 |
::-webkit-scrollbar-thumb {
|
| 108 |
+
background: #334155;
|
| 109 |
+
border-radius: 3px;
|
| 110 |
}
|
| 111 |
|
| 112 |
::-webkit-scrollbar-thumb:hover {
|
| 113 |
+
background: #475569;
|
| 114 |
}
|
| 115 |
|
| 116 |
+
/* Glass Cards - Sharper */
|
| 117 |
+
.glass-card {
|
| 118 |
+
background: rgba(15, 17, 23, 0.7);
|
| 119 |
+
/* Darker, less transparent */
|
| 120 |
+
backdrop-filter: blur(12px);
|
| 121 |
+
border: 1px solid var(--border);
|
| 122 |
+
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.5);
|
|
|
|
| 123 |
}
|
| 124 |
|
| 125 |
+
.glass-card:hover {
|
| 126 |
+
border-color: rgba(255, 255, 255, 0.15);
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
/* Neon Text */
|
| 130 |
+
.text-neon {
|
| 131 |
+
color: #fff;
|
| 132 |
+
text-shadow: 0 0 10px rgba(99, 102, 241, 0.8);
|
| 133 |
}
|
| 134 |
|
| 135 |
/* Text Gradients */
|
|
|
|
| 238 |
animation: shimmer 2s linear infinite;
|
| 239 |
}
|
| 240 |
|
| 241 |
+
/* Animations */
|
| 242 |
+
@keyframes grid-move {
|
| 243 |
+
0% {
|
| 244 |
+
transform: translateY(0);
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
100% {
|
| 248 |
+
transform: translateY(50px);
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
.animate-grid {
|
| 253 |
+
animation: grid-move 20s linear infinite;
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
.input-glow:focus-within {
|
| 257 |
box-shadow: 0 0 20px -5px rgba(99, 102, 241, 0.4);
|
| 258 |
border-color: rgba(99, 102, 241, 0.5);
|
frontend/app/knowledge/page.tsx
DELETED
|
@@ -1,404 +0,0 @@
|
|
| 1 |
-
'use client'
|
| 2 |
-
|
| 3 |
-
import { useState, useCallback } from 'react'
|
| 4 |
-
import { useDropzone } from 'react-dropzone'
|
| 5 |
-
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
| 6 |
-
import { knowledgeApi } from '@/lib/api'
|
| 7 |
-
import { Upload, FileText, Trash2, Search, Sparkles, BookOpen, AlertCircle, CheckCircle2, Loader2, X, ShoppingBag } from 'lucide-react'
|
| 8 |
-
import { cn } from '@/lib/utils'
|
| 9 |
-
import { useAuth } from '@/contexts/AuthContext'
|
| 10 |
-
import { useToast } from '@/contexts/ToastContext'
|
| 11 |
-
import { motion, AnimatePresence } from 'framer-motion'
|
| 12 |
-
|
| 13 |
-
import ProductSettings from '@/components/settings/ProductSettings'
|
| 14 |
-
|
| 15 |
-
export default function KnowledgePage() {
|
| 16 |
-
const [activeTab, setActiveTab] = useState<'files' | 'catalog'>('files')
|
| 17 |
-
const [searchQuery, setSearchQuery] = useState('')
|
| 18 |
-
const [uploadedFiles, setUploadedFiles] = useState<string[]>([])
|
| 19 |
-
const queryClient = useQueryClient()
|
| 20 |
-
const { user, isLoading: authLoading } = useAuth()
|
| 21 |
-
const toast = useToast()
|
| 22 |
-
|
| 23 |
-
const { data: knowledgeData, isLoading: knowledgeLoading } = useQuery({
|
| 24 |
-
queryKey: ['knowledge', user?.tenant_id],
|
| 25 |
-
queryFn: () => knowledgeApi.list({ limit: 100 }),
|
| 26 |
-
enabled: !!user && activeTab === 'files',
|
| 27 |
-
})
|
| 28 |
-
|
| 29 |
-
const { data: searchResults, isLoading: isSearching } = useQuery({
|
| 30 |
-
queryKey: ['knowledge-search', user?.tenant_id, searchQuery],
|
| 31 |
-
queryFn: () => knowledgeApi.search(searchQuery, 10),
|
| 32 |
-
enabled: !!user && searchQuery.length > 2 && activeTab === 'files',
|
| 33 |
-
})
|
| 34 |
-
|
| 35 |
-
const uploadMutation = useMutation({
|
| 36 |
-
mutationFn: async (file: File) => {
|
| 37 |
-
if (!user) throw new Error('Пользователь не авторизован')
|
| 38 |
-
return knowledgeApi.upload(file)
|
| 39 |
-
},
|
| 40 |
-
onSuccess: (data, file) => {
|
| 41 |
-
queryClient.invalidateQueries({ queryKey: ['knowledge', user?.tenant_id] })
|
| 42 |
-
toast.success('Успех!', `Файл "${file.name}" успешно загружен и изучен AI`)
|
| 43 |
-
setUploadedFiles(prev => [...prev, file.name])
|
| 44 |
-
setTimeout(() => {
|
| 45 |
-
setUploadedFiles(prev => prev.filter(f => f !== file.name))
|
| 46 |
-
}, 3000)
|
| 47 |
-
},
|
| 48 |
-
onError: (error: Error) => {
|
| 49 |
-
toast.error('Ошибка', error.message || 'Не удалось загрузить файл')
|
| 50 |
-
},
|
| 51 |
-
})
|
| 52 |
-
|
| 53 |
-
const deleteMutation = useMutation({
|
| 54 |
-
mutationFn: async (id: string) => {
|
| 55 |
-
// Implement delete API call here if available
|
| 56 |
-
// await knowledgeApi.delete(id)
|
| 57 |
-
return Promise.resolve()
|
| 58 |
-
},
|
| 59 |
-
onSuccess: () => {
|
| 60 |
-
queryClient.invalidateQueries({ queryKey: ['knowledge', user?.tenant_id] })
|
| 61 |
-
toast.success('Удалено', 'Запись удалена из базы знаний')
|
| 62 |
-
}
|
| 63 |
-
})
|
| 64 |
-
|
| 65 |
-
const onDrop = useCallback((acceptedFiles: File[]) => {
|
| 66 |
-
if (acceptedFiles.length === 0) return
|
| 67 |
-
|
| 68 |
-
acceptedFiles.forEach((file) => {
|
| 69 |
-
uploadMutation.mutate(file)
|
| 70 |
-
})
|
| 71 |
-
}, [uploadMutation])
|
| 72 |
-
|
| 73 |
-
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
| 74 |
-
onDrop,
|
| 75 |
-
accept: {
|
| 76 |
-
'application/pdf': ['.pdf'],
|
| 77 |
-
'text/plain': ['.txt'],
|
| 78 |
-
},
|
| 79 |
-
})
|
| 80 |
-
|
| 81 |
-
if (authLoading || !user) {
|
| 82 |
-
return (
|
| 83 |
-
<div className="flex items-center justify-center min-h-screen bg-slate-50">
|
| 84 |
-
<Loader2 className="w-12 h-12 animate-spin text-indigo-600" />
|
| 85 |
-
</div>
|
| 86 |
-
)
|
| 87 |
-
}
|
| 88 |
-
|
| 89 |
-
return (
|
| 90 |
-
<div className="min-h-screen bg-slate-100 p-8">
|
| 91 |
-
<div className="max-w-5xl mx-auto space-y-8">
|
| 92 |
-
{/* Header */}
|
| 93 |
-
<motion.div
|
| 94 |
-
initial={{ opacity: 0, y: -20 }}
|
| 95 |
-
animate={{ opacity: 1, y: 0 }}
|
| 96 |
-
className="flex items-center justify-between"
|
| 97 |
-
>
|
| 98 |
-
<div>
|
| 99 |
-
<h1 className="text-3xl font-bold text-slate-900 mb-2 tracking-tight flex items-center gap-3">
|
| 100 |
-
База Знаний
|
| 101 |
-
</h1>
|
| 102 |
-
<p className="text-slate-600">
|
| 103 |
-
Управление знаниями AI и каталогом товаров
|
| 104 |
-
</p>
|
| 105 |
-
</div>
|
| 106 |
-
<div className="bg-white p-1 rounded-xl shadow-sm border border-slate-200 flex gap-1">
|
| 107 |
-
<button
|
| 108 |
-
onClick={() => setActiveTab('files')}
|
| 109 |
-
className={cn(
|
| 110 |
-
"px-4 py-2 rounded-lg text-sm font-medium transition-all flex items-center gap-2",
|
| 111 |
-
activeTab === 'files'
|
| 112 |
-
? "bg-indigo-600 text-white shadow-md"
|
| 113 |
-
: "text-slate-600 hover:bg-slate-50"
|
| 114 |
-
)}
|
| 115 |
-
>
|
| 116 |
-
<FileText className="w-4 h-4" />
|
| 117 |
-
Файлы
|
| 118 |
-
</button>
|
| 119 |
-
<button
|
| 120 |
-
onClick={() => setActiveTab('catalog')}
|
| 121 |
-
className={cn(
|
| 122 |
-
"px-4 py-2 rounded-lg text-sm font-medium transition-all flex items-center gap-2",
|
| 123 |
-
activeTab === 'catalog'
|
| 124 |
-
? "bg-indigo-600 text-white shadow-md"
|
| 125 |
-
: "text-slate-600 hover:bg-slate-50"
|
| 126 |
-
)}
|
| 127 |
-
>
|
| 128 |
-
<ShoppingBag className="w-4 h-4" />
|
| 129 |
-
Каталог
|
| 130 |
-
</button>
|
| 131 |
-
</div>
|
| 132 |
-
</motion.div>
|
| 133 |
-
|
| 134 |
-
{activeTab === 'files' ? (
|
| 135 |
-
<>
|
| 136 |
-
{/* Upload Zone */}
|
| 137 |
-
<motion.div
|
| 138 |
-
initial={{ opacity: 0, y: 20 }}
|
| 139 |
-
animate={{ opacity: 1, y: 0 }}
|
| 140 |
-
transition={{ delay: 0.1 }}
|
| 141 |
-
className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8"
|
| 142 |
-
>
|
| 143 |
-
<h2 className="text-lg font-bold text-slate-900 mb-6 flex items-center gap-2">
|
| 144 |
-
<Upload className="w-5 h-5 text-indigo-600" />
|
| 145 |
-
Загрузить файлы
|
| 146 |
-
</h2>
|
| 147 |
-
<div
|
| 148 |
-
{...getRootProps()}
|
| 149 |
-
className={cn(
|
| 150 |
-
"border-2 border-dashed rounded-xl p-12 text-center cursor-pointer transition-all duration-300 relative overflow-hidden",
|
| 151 |
-
isDragActive
|
| 152 |
-
? "border-indigo-500 bg-indigo-50/50 scale-[1.01]"
|
| 153 |
-
: "border-slate-200 hover:border-indigo-400 hover:bg-slate-50",
|
| 154 |
-
uploadMutation.isPending && "opacity-75 cursor-wait"
|
| 155 |
-
)}
|
| 156 |
-
>
|
| 157 |
-
<input {...getInputProps()} />
|
| 158 |
-
<div className="flex flex-col items-center gap-4 relative z-10">
|
| 159 |
-
{uploadMutation.isPending ? (
|
| 160 |
-
<>
|
| 161 |
-
<div className="p-4 bg-indigo-50 rounded-full">
|
| 162 |
-
<Loader2 className="w-8 h-8 text-indigo-600 animate-spin" />
|
| 163 |
-
</div>
|
| 164 |
-
<div>
|
| 165 |
-
<p className="text-indigo-900 font-bold text-lg">Обработка файла...</p>
|
| 166 |
-
<p className="text-sm text-indigo-600">AI анализирует содержимое</p>
|
| 167 |
-
</div>
|
| 168 |
-
</>
|
| 169 |
-
) : isDragActive ? (
|
| 170 |
-
<>
|
| 171 |
-
<div className="p-4 bg-indigo-100 rounded-full animate-bounce">
|
| 172 |
-
<Upload className="w-8 h-8 text-indigo-600" />
|
| 173 |
-
</div>
|
| 174 |
-
<p className="text-indigo-900 font-bold text-lg">Отпустите файлы здесь...</p>
|
| 175 |
-
</>
|
| 176 |
-
) : (
|
| 177 |
-
<>
|
| 178 |
-
<div className="p-4 bg-slate-100 rounded-full group-hover:bg-indigo-50 transition-colors">
|
| 179 |
-
<Upload className="w-8 h-8 text-slate-400 group-hover:text-indigo-600 transition-colors" />
|
| 180 |
-
</div>
|
| 181 |
-
<div>
|
| 182 |
-
<p className="text-slate-900 font-bold text-lg mb-1">
|
| 183 |
-
Перетащите PDF или TXT файлы сюда
|
| 184 |
-
</p>
|
| 185 |
-
<p className="text-sm text-slate-500">или кликните для выбора файлов</p>
|
| 186 |
-
</div>
|
| 187 |
-
<div className="flex items-center gap-4 text-xs font-medium text-slate-400 mt-2">
|
| 188 |
-
<span className="flex items-center gap-1.5 bg-slate-50 px-2 py-1 rounded-md border border-slate-100">
|
| 189 |
-
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
|
| 190 |
-
PDF документы
|
| 191 |
-
</span>
|
| 192 |
-
<span className="flex items-center gap-1.5 bg-slate-50 px-2 py-1 rounded-md border border-slate-100">
|
| 193 |
-
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
|
| 194 |
-
TXT файлы
|
| 195 |
-
</span>
|
| 196 |
-
</div>
|
| 197 |
-
</>
|
| 198 |
-
)}
|
| 199 |
-
</div>
|
| 200 |
-
</div>
|
| 201 |
-
|
| 202 |
-
{/* Uploaded Files List */}
|
| 203 |
-
<AnimatePresence>
|
| 204 |
-
{uploadedFiles.length > 0 && (
|
| 205 |
-
<div className="mt-6 space-y-2">
|
| 206 |
-
{uploadedFiles.map((fileName, idx) => (
|
| 207 |
-
<motion.div
|
| 208 |
-
key={`${fileName}-${idx}`}
|
| 209 |
-
initial={{ opacity: 0, x: -20 }}
|
| 210 |
-
animate={{ opacity: 1, x: 0 }}
|
| 211 |
-
exit={{ opacity: 0, x: 20 }}
|
| 212 |
-
className="flex items-center gap-3 p-3 bg-emerald-50 border border-emerald-100 rounded-xl text-emerald-700"
|
| 213 |
-
>
|
| 214 |
-
<CheckCircle2 className="w-5 h-5 text-emerald-500 flex-shrink-0" />
|
| 215 |
-
<span className="text-sm font-medium truncate flex-1">{fileName}</span>
|
| 216 |
-
<span className="text-xs font-bold bg-white/50 px-2 py-1 rounded-md">Загружено</span>
|
| 217 |
-
</motion.div>
|
| 218 |
-
))}
|
| 219 |
-
</div>
|
| 220 |
-
)}
|
| 221 |
-
</AnimatePresence>
|
| 222 |
-
</motion.div>
|
| 223 |
-
|
| 224 |
-
{/* Search & Results */}
|
| 225 |
-
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
| 226 |
-
{/* Search Column */}
|
| 227 |
-
<motion.div
|
| 228 |
-
initial={{ opacity: 0, y: 20 }}
|
| 229 |
-
animate={{ opacity: 1, y: 0 }}
|
| 230 |
-
transition={{ delay: 0.2 }}
|
| 231 |
-
className="lg:col-span-2 space-y-6"
|
| 232 |
-
>
|
| 233 |
-
<div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
|
| 234 |
-
<h2 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
|
| 235 |
-
<Search className="w-5 h-5 text-indigo-600" />
|
| 236 |
-
Поиск в базе знаний
|
| 237 |
-
</h2>
|
| 238 |
-
<div className="relative">
|
| 239 |
-
<Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
|
| 240 |
-
<input
|
| 241 |
-
type="text"
|
| 242 |
-
placeholder="Введите вопрос или ключевые слова..."
|
| 243 |
-
value={searchQuery}
|
| 244 |
-
onChange={(e) => setSearchQuery(e.target.value)}
|
| 245 |
-
className="w-full pl-12 pr-10 py-4 bg-slate-50 border-2 border-slate-200 rounded-xl focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500 transition-all font-medium text-slate-900 placeholder:text-slate-400"
|
| 246 |
-
/>
|
| 247 |
-
{searchQuery && (
|
| 248 |
-
<button
|
| 249 |
-
onClick={() => setSearchQuery('')}
|
| 250 |
-
className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
| 251 |
-
>
|
| 252 |
-
<X className="w-4 h-4" />
|
| 253 |
-
</button>
|
| 254 |
-
)}
|
| 255 |
-
</div>
|
| 256 |
-
|
| 257 |
-
<AnimatePresence mode="wait">
|
| 258 |
-
{searchQuery.length > 2 && (
|
| 259 |
-
<motion.div
|
| 260 |
-
initial={{ opacity: 0, height: 0 }}
|
| 261 |
-
animate={{ opacity: 1, height: 'auto' }}
|
| 262 |
-
exit={{ opacity: 0, height: 0 }}
|
| 263 |
-
className="mt-6"
|
| 264 |
-
>
|
| 265 |
-
<div className="flex items-center justify-between mb-4">
|
| 266 |
-
<h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
|
| 267 |
-
<Sparkles className="w-4 h-4 text-indigo-600" />
|
| 268 |
-
Результаты поиска
|
| 269 |
-
</h3>
|
| 270 |
-
<span className="text-xs font-medium text-slate-500 bg-slate-100 px-2 py-1 rounded-md">
|
| 271 |
-
{searchResults?.count || 0} найдено
|
| 272 |
-
</span>
|
| 273 |
-
</div>
|
| 274 |
-
|
| 275 |
-
{isSearching ? (
|
| 276 |
-
<div className="flex flex-col items-center justify-center py-12 text-slate-400">
|
| 277 |
-
<Loader2 className="w-8 h-8 animate-spin mb-2" />
|
| 278 |
-
<span className="text-sm">Ищем ответы...</span>
|
| 279 |
-
</div>
|
| 280 |
-
) : searchResults?.results?.length > 0 ? (
|
| 281 |
-
<div className="space-y-4">
|
| 282 |
-
{searchResults.results.map((result: any, idx: number) => (
|
| 283 |
-
<motion.div
|
| 284 |
-
key={idx}
|
| 285 |
-
initial={{ opacity: 0, y: 10 }}
|
| 286 |
-
animate={{ opacity: 1, y: 0 }}
|
| 287 |
-
transition={{ delay: idx * 0.05 }}
|
| 288 |
-
className="group p-4 bg-white border border-slate-200 rounded-xl hover:border-indigo-300 hover:shadow-md transition-all relative overflow-hidden"
|
| 289 |
-
>
|
| 290 |
-
<div className="absolute left-0 top-0 bottom-0 w-1 bg-indigo-500 opacity-0 group-hover:opacity-100 transition-opacity" />
|
| 291 |
-
<p className="text-sm text-slate-700 leading-relaxed mb-3">{result.content}</p>
|
| 292 |
-
<div className="flex items-center justify-between text-xs">
|
| 293 |
-
<span className="font-bold text-indigo-600 bg-indigo-50 px-2 py-1 rounded-md">
|
| 294 |
-
{((result.similarity || 0) * 100).toFixed(0)}% совпадение
|
| 295 |
-
</span>
|
| 296 |
-
<span className="text-slate-400 font-medium uppercase tracking-wide">
|
| 297 |
-
{result.category || 'Общее'}
|
| 298 |
-
</span>
|
| 299 |
-
</div>
|
| 300 |
-
</motion.div>
|
| 301 |
-
))}
|
| 302 |
-
</div>
|
| 303 |
-
) : (
|
| 304 |
-
<div className="text-center py-12 bg-slate-50 rounded-xl border border-dashed border-slate-200">
|
| 305 |
-
<AlertCircle className="w-10 h-10 mx-auto text-slate-300 mb-3" />
|
| 306 |
-
<p className="text-slate-900 font-medium">Ничего не найдено</p>
|
| 307 |
-
<p className="text-sm text-slate-500">Попробуйте изменить запрос</p>
|
| 308 |
-
</div>
|
| 309 |
-
)}
|
| 310 |
-
</motion.div>
|
| 311 |
-
)}
|
| 312 |
-
</AnimatePresence>
|
| 313 |
-
</div>
|
| 314 |
-
</motion.div>
|
| 315 |
-
|
| 316 |
-
{/* Files List Column */}
|
| 317 |
-
<motion.div
|
| 318 |
-
initial={{ opacity: 0, y: 20 }}
|
| 319 |
-
animate={{ opacity: 1, y: 0 }}
|
| 320 |
-
transition={{ delay: 0.3 }}
|
| 321 |
-
className="bg-white rounded-2xl shadow-sm border border-slate-200 flex flex-col h-[600px]"
|
| 322 |
-
>
|
| 323 |
-
<div className="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50 rounded-t-2xl">
|
| 324 |
-
<h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
|
| 325 |
-
<FileText className="w-5 h-5 text-indigo-600" />
|
| 326 |
-
Файлы
|
| 327 |
-
</h2>
|
| 328 |
-
<span className="text-xs font-bold bg-white border border-slate-200 px-2 py-1 rounded-md text-slate-600">
|
| 329 |
-
{knowledgeData?.count || 0}
|
| 330 |
-
</span>
|
| 331 |
-
</div>
|
| 332 |
-
|
| 333 |
-
<div className="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
|
| 334 |
-
{knowledgeLoading ? (
|
| 335 |
-
<div className="flex items-center justify-center h-full text-slate-400">
|
| 336 |
-
<Loader2 className="w-8 h-8 animate-spin" />
|
| 337 |
-
</div>
|
| 338 |
-
) : knowledgeData?.entries?.length > 0 ? (
|
| 339 |
-
knowledgeData.entries.map((entry: any) => (
|
| 340 |
-
<motion.div
|
| 341 |
-
key={entry.id}
|
| 342 |
-
layout
|
| 343 |
-
initial={{ opacity: 0 }}
|
| 344 |
-
animate={{ opacity: 1 }}
|
| 345 |
-
className="group p-4 bg-white border border-slate-200 rounded-xl hover:border-indigo-300 hover:shadow-sm transition-all"
|
| 346 |
-
>
|
| 347 |
-
<div className="flex items-start gap-3">
|
| 348 |
-
<div className="p-2 bg-indigo-50 text-indigo-600 rounded-lg flex-shrink-0 group-hover:bg-indigo-100 transition-colors">
|
| 349 |
-
<FileText className="w-5 h-5" />
|
| 350 |
-
</div>
|
| 351 |
-
<div className="flex-1 min-w-0">
|
| 352 |
-
<div className="flex items-center gap-2 mb-1">
|
| 353 |
-
<span className="text-xs font-bold text-indigo-600 uppercase tracking-wide bg-indigo-50 px-1.5 py-0.5 rounded">
|
| 354 |
-
{entry.category || 'DOC'}
|
| 355 |
-
</span>
|
| 356 |
-
<span className="text-[10px] text-slate-400">
|
| 357 |
-
{new Date(entry.created_at).toLocaleDateString()}
|
| 358 |
-
</span>
|
| 359 |
-
</div>
|
| 360 |
-
<p className="text-sm text-slate-700 line-clamp-2 leading-relaxed mb-2">
|
| 361 |
-
{entry.content}
|
| 362 |
-
</p>
|
| 363 |
-
<div className="flex items-center justify-between">
|
| 364 |
-
<span className="text-xs text-slate-500 font-medium bg-slate-50 px-2 py-1 rounded border border-slate-100">
|
| 365 |
-
{entry.source_type}
|
| 366 |
-
</span>
|
| 367 |
-
<button
|
| 368 |
-
onClick={() => deleteMutation.mutate(entry.id)}
|
| 369 |
-
className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
|
| 370 |
-
title="Удалить"
|
| 371 |
-
>
|
| 372 |
-
<Trash2 className="w-4 h-4" />
|
| 373 |
-
</button>
|
| 374 |
-
</div>
|
| 375 |
-
</div>
|
| 376 |
-
</div>
|
| 377 |
-
</motion.div>
|
| 378 |
-
))
|
| 379 |
-
) : (
|
| 380 |
-
<div className="flex flex-col items-center justify-center h-full text-center p-8">
|
| 381 |
-
<div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4">
|
| 382 |
-
<FileText className="w-8 h-8 text-slate-300" />
|
| 383 |
-
</div>
|
| 384 |
-
<h3 className="font-bold text-slate-900 mb-1">Пусто</h3>
|
| 385 |
-
<p className="text-sm text-slate-500">Загрузите файлы, чтобы наполнить базу знаний</p>
|
| 386 |
-
</div>
|
| 387 |
-
)}
|
| 388 |
-
</div>
|
| 389 |
-
</motion.div>
|
| 390 |
-
</div>
|
| 391 |
-
</>
|
| 392 |
-
) : (
|
| 393 |
-
<motion.div
|
| 394 |
-
initial={{ opacity: 0, y: 20 }}
|
| 395 |
-
animate={{ opacity: 1, y: 0 }}
|
| 396 |
-
className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8 min-h-[600px]"
|
| 397 |
-
>
|
| 398 |
-
<ProductSettings />
|
| 399 |
-
</motion.div>
|
| 400 |
-
)}
|
| 401 |
-
</div>
|
| 402 |
-
</div>
|
| 403 |
-
)
|
| 404 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/app/live/page.tsx
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client';
|
| 2 |
+
|
| 3 |
+
import { useEffect, useState } from 'react';
|
| 4 |
+
import { useRouter } from 'next/navigation';
|
| 5 |
+
import { LiveConversation } from '@/components/Voice/LiveConversation';
|
| 6 |
+
import Sidebar from '@/components/Sidebar'; // Assuming Sidebar exists
|
| 7 |
+
import { cn } from '@/lib/utils';
|
| 8 |
+
|
| 9 |
+
export default function LiveVoicePage() {
|
| 10 |
+
const router = useRouter();
|
| 11 |
+
const [token, setToken] = useState<string | null>(null);
|
| 12 |
+
const [loading, setLoading] = useState(true);
|
| 13 |
+
|
| 14 |
+
useEffect(() => {
|
| 15 |
+
// Simple auth check
|
| 16 |
+
const storedToken = localStorage.getItem('token');
|
| 17 |
+
if (!storedToken) {
|
| 18 |
+
router.push('/login');
|
| 19 |
+
return;
|
| 20 |
+
}
|
| 21 |
+
setToken(storedToken);
|
| 22 |
+
setLoading(false);
|
| 23 |
+
}, [router]);
|
| 24 |
+
|
| 25 |
+
if (loading) {
|
| 26 |
+
return <div className="min-h-screen bg-black flex items-center justify-center text-white">Loading Voice Engine...</div>;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
return (
|
| 30 |
+
<div className="flex h-screen bg-black overflow-hidden font-sans">
|
| 31 |
+
<Sidebar />
|
| 32 |
+
|
| 33 |
+
<main className="flex-1 flex flex-col relative">
|
| 34 |
+
{/* Header */}
|
| 35 |
+
<div className="absolute top-0 left-0 right-0 p-8 flex justify-between items-center z-10 pointer-events-none">
|
| 36 |
+
<div>
|
| 37 |
+
<h1 className="text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-white to-white/50">
|
| 38 |
+
Voice Intelligence
|
| 39 |
+
</h1>
|
| 40 |
+
<p className="text-white/40 mt-2">Real-time Advanced Conversational AI</p>
|
| 41 |
+
</div>
|
| 42 |
+
</div>
|
| 43 |
+
|
| 44 |
+
{/* Main Content (Centered Orb) */}
|
| 45 |
+
<div className="flex-1 flex items-center justify-center p-8">
|
| 46 |
+
{token && <LiveConversation token={token} />}
|
| 47 |
+
</div>
|
| 48 |
+
</main>
|
| 49 |
+
</div>
|
| 50 |
+
);
|
| 51 |
+
}
|
frontend/app/page.tsx
CHANGED
|
@@ -1,5 +1,135 @@
|
|
| 1 |
import { redirect } from 'next/navigation'
|
| 2 |
|
|
|
|
|
|
|
|
|
|
| 3 |
export default function HomePage() {
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
}
|
|
|
|
| 1 |
import { redirect } from 'next/navigation'
|
| 2 |
|
| 3 |
+
import Link from 'next/link'
|
| 4 |
+
import { ArrowRight, Zap, Target, BarChart3, Shield, Bot, MessageSquare } from 'lucide-react'
|
| 5 |
+
|
| 6 |
export default function HomePage() {
|
| 7 |
+
return (
|
| 8 |
+
<div className="min-h-screen bg-[#030014] overflow-hidden relative selection:bg-indigo-500/30">
|
| 9 |
+
|
| 10 |
+
{/* Background Grid Animation */}
|
| 11 |
+
<div className="fixed inset-0 z-0 pointer-events-none opacity-20"
|
| 12 |
+
style={{
|
| 13 |
+
backgroundImage: 'linear-gradient(rgba(99, 102, 241, 0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(99, 102, 241, 0.1) 1px, transparent 1px)',
|
| 14 |
+
backgroundSize: '50px 50px',
|
| 15 |
+
transform: 'perspective(500px) rotateX(60deg) translateY(-100px) scale(2)'
|
| 16 |
+
}}>
|
| 17 |
+
</div>
|
| 18 |
+
|
| 19 |
+
{/* Hero Section */}
|
| 20 |
+
<div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-32 pb-16">
|
| 21 |
+
<div className="text-center">
|
| 22 |
+
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-indigo-500/30 bg-indigo-500/10 mb-8 animate-pulse-glow">
|
| 23 |
+
<span className="relative flex h-2 w-2">
|
| 24 |
+
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-indigo-400 opacity-75"></span>
|
| 25 |
+
<span className="relative inline-flex rounded-full h-2 w-2 bg-indigo-500"></span>
|
| 26 |
+
</span>
|
| 27 |
+
<span className="text-indigo-300 text-sm font-medium tracking-wide">SYSTEM ONLINE v2.0</span>
|
| 28 |
+
</div>
|
| 29 |
+
|
| 30 |
+
<h1 className="text-6xl md:text-8xl font-black tracking-tighter text-white mb-8 leading-tight">
|
| 31 |
+
YOUR AI <span className="text-transparent bg-clip-text bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 text-neon">SALES ARMY</span>
|
| 32 |
+
<br />IS READY.
|
| 33 |
+
</h1>
|
| 34 |
+
|
| 35 |
+
<p className="mt-4 max-w-2xl mx-auto text-xl text-slate-400 leading-relaxed">
|
| 36 |
+
Replace your sales team with an AI that never sleeps, never complains, and closes deals <span className="text-white font-bold">24/7</span>.
|
| 37 |
+
Deploy autonomous agents on WhatsApp & Instagram in 5 minutes.
|
| 38 |
+
</p>
|
| 39 |
+
|
| 40 |
+
<div className="mt-12 flex flex-col sm:flex-row gap-6 justify-center items-center">
|
| 41 |
+
<Link href="/register"
|
| 42 |
+
className="group relative px-8 py-4 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-lg tracking-wider transition-all clip-path-polygon hover:scale-105 active:scale-95 shadow-[0_0_30px_-5px_rgba(99,102,241,0.6)]">
|
| 43 |
+
<span className="flex items-center gap-2">
|
| 44 |
+
START DOMINATING <ArrowRight className="w-5 h-5 group-hover:translate-x-1 transition-transform" />
|
| 45 |
+
</span>
|
| 46 |
+
</Link>
|
| 47 |
+
|
| 48 |
+
<Link href="/login" className="px-8 py-4 text-slate-300 hover:text-white font-semibold tracking-wide transition-colors">
|
| 49 |
+
LOG IN // ACCESS TERMINAL
|
| 50 |
+
</Link>
|
| 51 |
+
</div>
|
| 52 |
+
</div>
|
| 53 |
+
|
| 54 |
+
{/* Dashboard Preview / Stats */}
|
| 55 |
+
<div className="mt-24 relative">
|
| 56 |
+
<div className="absolute -inset-4 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-xl blur-lg opacity-30 animate-pulse"></div>
|
| 57 |
+
<div className="relative glass-card rounded-xl p-1 border border-white/10 overflow-hidden">
|
| 58 |
+
|
| 59 |
+
{/* Mock Dashboard UI - Hero Image */}
|
| 60 |
+
<div className="bg-[#0f1117] rounded-lg p-8 grid grid-cols-1 md:grid-cols-3 gap-6">
|
| 61 |
+
|
| 62 |
+
{/* Stat 1 */}
|
| 63 |
+
<div className="p-6 rounded-lg bg-[#030014] border border-white/5 flex flex-col items-center">
|
| 64 |
+
<div className="text-slate-400 text-sm uppercase tracking-widest mb-2">Revenue Today</div>
|
| 65 |
+
<div className="text-4xl font-mono text-green-400 font-bold drop-shadow-[0_0_10px_rgba(74,222,128,0.5)]">$12,450</div>
|
| 66 |
+
<div className="text-xs text-green-500 mt-2 flex items-center gap-1">
|
| 67 |
+
<Zap className="w-3 h-3" /> +15% vs yesterday
|
| 68 |
+
</div>
|
| 69 |
+
</div>
|
| 70 |
+
|
| 71 |
+
{/* Stat 2 */}
|
| 72 |
+
<div className="p-6 rounded-lg bg-[#030014] border border-white/5 flex flex-col items-center">
|
| 73 |
+
<div className="text-slate-400 text-sm uppercase tracking-widest mb-2">Active Agents</div>
|
| 74 |
+
<div className="text-4xl font-mono text-indigo-400 font-bold drop-shadow-[0_0_10px_rgba(99,102,241,0.5)]">84</div>
|
| 75 |
+
<div className="text-xs text-indigo-500 mt-2 flex items-center gap-1">
|
| 76 |
+
<Bot className="w-3 h-3" /> All Systems Operational
|
| 77 |
+
</div>
|
| 78 |
+
</div>
|
| 79 |
+
|
| 80 |
+
{/* Stat 3 */}
|
| 81 |
+
<div className="p-6 rounded-lg bg-[#030014] border border-white/5 flex flex-col items-center">
|
| 82 |
+
<div className="text-slate-400 text-sm uppercase tracking-widest mb-2">Conversion Rate</div>
|
| 83 |
+
<div className="text-4xl font-mono text-pink-400 font-bold drop-shadow-[0_0_10px_rgba(236,72,153,0.5)]">8.4%</div>
|
| 84 |
+
<div className="text-xs text-pink-500 mt-2 flex items-center gap-1">
|
| 85 |
+
<Target className="w-3 h-3" /> Market Leader
|
| 86 |
+
</div>
|
| 87 |
+
</div>
|
| 88 |
+
|
| 89 |
+
</div>
|
| 90 |
+
|
| 91 |
+
{/* Fake Code / Terminal */}
|
| 92 |
+
<div className="mt-1 bg-black/50 p-4 font-mono text-xs text-slate-500 border-t border-white/5">
|
| 93 |
+
<span className="text-green-500">root@microfunnel:~$</span> deploy_agent --mode=aggressive --target=whatsapp<br />
|
| 94 |
+
<span className="text-blue-500">[INFO]</span> Initializing Neural Engine... OK<br />
|
| 95 |
+
<span className="text-blue-500">[INFO]</span> Connected to Meta Cloud API... OK<br />
|
| 96 |
+
<span className="text-purple-500">[SUCCESS]</span> Agent "Hunter-V1" is now live and closing deals.
|
| 97 |
+
</div>
|
| 98 |
+
</div>
|
| 99 |
+
</div>
|
| 100 |
+
</div>
|
| 101 |
+
|
| 102 |
+
{/* Features Grid */}
|
| 103 |
+
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-32 grid grid-cols-1 md:grid-cols-3 gap-8">
|
| 104 |
+
|
| 105 |
+
<div className="glass-card p-8 rounded-xl hover:bg-white/5 transition-all group">
|
| 106 |
+
<MessageSquare className="w-12 h-12 text-indigo-500 mb-6 group-hover:scale-110 transition-transform duration-300" />
|
| 107 |
+
<h3 className="text-2xl font-bold text-white mb-4">Official Meta API</h3>
|
| 108 |
+
<p className="text-slate-400 leading-relaxed">
|
| 109 |
+
No more bans. We use the official Cloud API for WhatsApp & Instagram.
|
| 110 |
+
<span className="block mt-2 text-green-400 font-mono text-sm">✓ 99.9% Uptime Verified</span>
|
| 111 |
+
</p>
|
| 112 |
+
</div>
|
| 113 |
+
|
| 114 |
+
<div className="glass-card p-8 rounded-xl hover:bg-white/5 transition-all group">
|
| 115 |
+
<Bot className="w-12 h-12 text-pink-500 mb-6 group-hover:scale-110 transition-transform duration-300" />
|
| 116 |
+
<h3 className="text-2xl font-bold text-white mb-4">Honest AI</h3>
|
| 117 |
+
<p className="text-slate-400 leading-relaxed">
|
| 118 |
+
We don't pretend to be human. We are faster, smarter, and more efficient.
|
| 119 |
+
Your customers will prefer the speed.
|
| 120 |
+
</p>
|
| 121 |
+
</div>
|
| 122 |
+
|
| 123 |
+
<div className="glass-card p-8 rounded-xl hover:bg-white/5 transition-all group border-blue-500/20">
|
| 124 |
+
<Shield className="w-12 h-12 text-blue-500 mb-6 group-hover:scale-110 transition-transform duration-300" />
|
| 125 |
+
<h3 className="text-2xl font-bold text-white mb-4">Enterprise Grade</h3>
|
| 126 |
+
<p className="text-slate-400 leading-relaxed">
|
| 127 |
+
Secure, scalable, and built for dominance. Manage thousands of conversations without breaking a sweat.
|
| 128 |
+
</p>
|
| 129 |
+
</div>
|
| 130 |
+
|
| 131 |
+
</div>
|
| 132 |
+
|
| 133 |
+
</div>
|
| 134 |
+
)
|
| 135 |
}
|
frontend/app/settings/billing/page.tsx
CHANGED
|
@@ -3,63 +3,91 @@
|
|
| 3 |
import { useState, useEffect } from 'react'
|
| 4 |
import {
|
| 5 |
CreditCard, Check, Zap, Shield, Crown, AlertTriangle,
|
| 6 |
-
ArrowUpRight, BarChart3, Clock, Loader2
|
| 7 |
} from 'lucide-react'
|
| 8 |
-
import { motion } from 'framer-motion'
|
| 9 |
import { cn } from '@/lib/utils'
|
| 10 |
import { api } from '@/lib/api'
|
|
|
|
| 11 |
|
| 12 |
// Interfaces
|
| 13 |
-
interface
|
| 14 |
-
plan:
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
}
|
| 25 |
|
| 26 |
const PLANS = [
|
| 27 |
{
|
| 28 |
id: 'start',
|
| 29 |
-
name: 'С
|
| 30 |
price: 99,
|
| 31 |
-
features: ['1 Канал (Любой)', '300
|
| 32 |
-
color: 'blue'
|
|
|
|
| 33 |
},
|
| 34 |
{
|
| 35 |
id: 'growth',
|
| 36 |
-
name: 'Р
|
| 37 |
price: 199,
|
| 38 |
-
features: ['3 Канала (TG + WA + LI)', '1000
|
| 39 |
-
color: 'indigo'
|
|
|
|
| 40 |
},
|
| 41 |
{
|
| 42 |
id: 'unlimited',
|
| 43 |
-
name: 'М
|
| 44 |
price: 499,
|
| 45 |
-
features: ['Безлимит каналов', '5000+
|
| 46 |
-
color: 'purple'
|
|
|
|
| 47 |
}
|
| 48 |
]
|
| 49 |
|
| 50 |
export default function BillingPage() {
|
| 51 |
const [loading, setLoading] = useState(true)
|
| 52 |
-
const [
|
| 53 |
-
const [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
useEffect(() => {
|
| 56 |
fetchBilling()
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
const fetchBilling = async () => {
|
| 60 |
try {
|
| 61 |
-
const response = await api.get('/api/v1/tenants/me/
|
| 62 |
-
|
| 63 |
} catch (error) {
|
| 64 |
console.error('Failed to fetch billing:', error)
|
| 65 |
} finally {
|
|
@@ -67,201 +95,312 @@ export default function BillingPage() {
|
|
| 67 |
}
|
| 68 |
}
|
| 69 |
|
| 70 |
-
const
|
| 71 |
-
if (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
setUpgrading(planId)
|
| 76 |
try {
|
| 77 |
-
await api.post('/api/v1/
|
| 78 |
-
|
| 79 |
-
|
|
|
|
| 80 |
} catch (error) {
|
| 81 |
-
console.error('
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
setUpgrading(null)
|
| 85 |
}
|
| 86 |
}
|
| 87 |
|
| 88 |
if (loading) {
|
| 89 |
return (
|
| 90 |
-
<div className="flex items-center justify-center min-h-screen bg-
|
| 91 |
-
<Loader2 className="w-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
</div>
|
| 93 |
)
|
| 94 |
}
|
| 95 |
|
| 96 |
-
|
|
|
|
| 97 |
|
| 98 |
return (
|
| 99 |
-
<div className="min-h-screen bg-
|
| 100 |
-
<div className="max-w-6xl mx-auto space-y-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
{/* Header */}
|
| 103 |
<div className="flex items-center justify-between">
|
| 104 |
<div>
|
| 105 |
-
<h1 className="text-3xl font-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
</div>
|
| 108 |
-
{stats.is_expired && (
|
| 109 |
-
<div className="px-4 py-2 bg-red-100 text-red-700 rounded-lg flex items-center gap-2 font-bold animate-pulse">
|
| 110 |
-
<AlertTriangle className="w-5 h-5" />
|
| 111 |
-
Подписка истекла!
|
| 112 |
-
</div>
|
| 113 |
-
)}
|
| 114 |
</div>
|
| 115 |
|
| 116 |
-
{/*
|
| 117 |
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
| 118 |
-
{/* Current Plan
|
| 119 |
<motion.div
|
| 120 |
-
initial={{ opacity: 0,
|
| 121 |
-
animate={{ opacity: 1,
|
| 122 |
-
className="bg-white p-6 rounded-2xl
|
| 123 |
>
|
| 124 |
-
<div className="
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
</div>
|
| 128 |
-
<div>
|
| 129 |
-
<
|
| 130 |
-
|
|
|
|
|
|
|
| 131 |
</div>
|
| 132 |
</div>
|
| 133 |
-
<div className="mt-4">
|
| 134 |
-
<span className="text-3xl font-bold text-slate-900">${stats.plan_price}</span>
|
| 135 |
-
<span className="text-slate-500">/мес</span>
|
| 136 |
-
</div>
|
| 137 |
</motion.div>
|
| 138 |
|
| 139 |
-
{/* Usage
|
| 140 |
<motion.div
|
| 141 |
-
initial={{ opacity: 0,
|
| 142 |
-
animate={{ opacity: 1,
|
| 143 |
transition={{ delay: 0.1 }}
|
| 144 |
-
className="bg-white p-6 rounded-2xl
|
| 145 |
>
|
| 146 |
-
<div className="
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
</
|
|
|
|
|
|
|
|
|
|
| 155 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
</div>
|
| 157 |
-
{stats.conversations_limit !== null && (
|
| 158 |
-
<div className="w-full bg-slate-100 rounded-full h-3 mt-4 overflow-hidden">
|
| 159 |
-
<div
|
| 160 |
-
className={cn(
|
| 161 |
-
"h-full rounded-full transition-all duration-500",
|
| 162 |
-
stats.usage_percentage > 90 ? "bg-red-500" : "bg-blue-600"
|
| 163 |
-
)}
|
| 164 |
-
style={{ width: `${Math.min(stats.usage_percentage, 100)}%` }}
|
| 165 |
-
/>
|
| 166 |
-
</div>
|
| 167 |
-
)}
|
| 168 |
-
<p className="text-xs text-slate-500 mt-2 text-right">
|
| 169 |
-
{stats.conversations_limit === null ? 'Безлимитный доступ' : `${stats.usage_percentage}% использовано`}
|
| 170 |
-
</p>
|
| 171 |
</motion.div>
|
| 172 |
|
| 173 |
-
{/*
|
| 174 |
<motion.div
|
| 175 |
-
initial={{ opacity: 0,
|
| 176 |
-
animate={{ opacity: 1,
|
| 177 |
transition={{ delay: 0.2 }}
|
| 178 |
-
className="bg-white p-6 rounded-2xl
|
| 179 |
>
|
| 180 |
-
<div className="
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
</div>
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
</div>
|
| 188 |
</div>
|
| 189 |
-
{stats.subscription_end && (
|
| 190 |
-
<p className="text-sm text-slate-500 mt-4">
|
| 191 |
-
Истекает: {new Date(stats.subscription_end).toLocaleDateString()}
|
| 192 |
-
</p>
|
| 193 |
-
)}
|
| 194 |
</motion.div>
|
| 195 |
</div>
|
| 196 |
|
| 197 |
{/* Plans Grid */}
|
| 198 |
-
<
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
const isPopular = plan.id === 'growth'
|
| 203 |
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
initial={{ opacity: 0, y: 20 }}
|
| 208 |
-
animate={{ opacity: 1, y: 0 }}
|
| 209 |
-
transition={{ delay: 0.1 * index }}
|
| 210 |
-
className={cn(
|
| 211 |
-
"relative bg-white rounded-2xl p-6 border-2 transition-all hover:shadow-xl hover:-translate-y-1",
|
| 212 |
-
isCurrent ? "border-indigo-600 ring-4 ring-indigo-50" : "border-slate-100",
|
| 213 |
-
isPopular && !isCurrent ? "border-purple-300 shadow-md" : ""
|
| 214 |
-
)}
|
| 215 |
-
>
|
| 216 |
-
{isPopular && !isCurrent && (
|
| 217 |
-
<div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-gradient-to-r from-purple-500 to-indigo-500 text-white px-3 py-1 rounded-full text-xs font-bold shadow-sm">
|
| 218 |
-
POPULAR
|
| 219 |
-
</div>
|
| 220 |
-
)}
|
| 221 |
-
|
| 222 |
-
<div className="mb-4">
|
| 223 |
-
<h3 className="text-lg font-bold text-slate-900">{plan.name}</h3>
|
| 224 |
-
<div className="flex items-baseline gap-1 mt-2">
|
| 225 |
-
<span className="text-3xl font-bold text-slate-900">${plan.price}</span>
|
| 226 |
-
<span className="text-slate-500">/мес</span>
|
| 227 |
-
</div>
|
| 228 |
-
</div>
|
| 229 |
-
|
| 230 |
-
<ul className="space-y-3 mb-8">
|
| 231 |
-
{plan.features.map((feature, i) => (
|
| 232 |
-
<li key={i} className="flex items-center gap-2 text-sm text-slate-600">
|
| 233 |
-
<Check className="w-4 h-4 text-emerald-500 flex-shrink-0" />
|
| 234 |
-
{feature}
|
| 235 |
-
</li>
|
| 236 |
-
))}
|
| 237 |
-
</ul>
|
| 238 |
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
| 242 |
className={cn(
|
| 243 |
-
"
|
| 244 |
isCurrent
|
| 245 |
-
? "bg-
|
| 246 |
-
: "bg-
|
| 247 |
-
|
| 248 |
)}
|
| 249 |
>
|
| 250 |
-
{
|
| 251 |
-
<
|
| 252 |
-
|
| 253 |
-
<
|
| 254 |
-
) : (
|
| 255 |
-
<>
|
| 256 |
-
Выбрать {plan.name}
|
| 257 |
-
<ArrowUpRight className="w-4 h-4" />
|
| 258 |
-
</>
|
| 259 |
)}
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
</div>
|
|
|
|
| 265 |
</div>
|
| 266 |
</div>
|
| 267 |
)
|
|
|
|
| 3 |
import { useState, useEffect } from 'react'
|
| 4 |
import {
|
| 5 |
CreditCard, Check, Zap, Shield, Crown, AlertTriangle,
|
| 6 |
+
ArrowUpRight, BarChart3, Clock, Loader2, Sparkles, X
|
| 7 |
} from 'lucide-react'
|
| 8 |
+
import { motion, AnimatePresence } from 'framer-motion'
|
| 9 |
import { cn } from '@/lib/utils'
|
| 10 |
import { api } from '@/lib/api'
|
| 11 |
+
import { useSearchParams } from 'next/navigation'
|
| 12 |
|
| 13 |
// Interfaces
|
| 14 |
+
interface BillingResponse {
|
| 15 |
+
plan: {
|
| 16 |
+
id: string
|
| 17 |
+
name: string
|
| 18 |
+
price: number
|
| 19 |
+
limits: {
|
| 20 |
+
conversations: number | null
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
usage: {
|
| 24 |
+
conversations_used: number
|
| 25 |
+
usage_percentage: number
|
| 26 |
+
is_over_limit: boolean
|
| 27 |
+
days_left: number
|
| 28 |
+
current_period_end: string | null
|
| 29 |
+
}
|
| 30 |
+
subscription_status: string
|
| 31 |
}
|
| 32 |
|
| 33 |
const PLANS = [
|
| 34 |
{
|
| 35 |
id: 'start',
|
| 36 |
+
name: 'СТАРТ',
|
| 37 |
price: 99,
|
| 38 |
+
features: ['1 Канал (Любой)', '300 Диалогов / мес', 'Все AI функции', 'CRM Интеграция', 'Базовая аналитика'],
|
| 39 |
+
color: 'blue',
|
| 40 |
+
popular: false
|
| 41 |
},
|
| 42 |
{
|
| 43 |
id: 'growth',
|
| 44 |
+
name: 'РОСТ',
|
| 45 |
price: 199,
|
| 46 |
+
features: ['3 Канала (TG + WA + LI)', '1000 Диалогов / мес', 'Все AI функции', 'CRM Интеграция', 'Расширенная аналитика'],
|
| 47 |
+
color: 'indigo',
|
| 48 |
+
popular: true
|
| 49 |
},
|
| 50 |
{
|
| 51 |
id: 'unlimited',
|
| 52 |
+
name: 'МАСШТАБ',
|
| 53 |
price: 499,
|
| 54 |
+
features: ['Безлимит каналов', '5000+ Диалогов / мес', 'Все AI функции', 'Приоритетная поддержка', 'Кастомные решения'],
|
| 55 |
+
color: 'purple',
|
| 56 |
+
popular: false
|
| 57 |
}
|
| 58 |
]
|
| 59 |
|
| 60 |
export default function BillingPage() {
|
| 61 |
const [loading, setLoading] = useState(true)
|
| 62 |
+
const [data, setData] = useState<BillingResponse | null>(null)
|
| 63 |
+
const [processing, setProcessing] = useState<string | null>(null)
|
| 64 |
+
|
| 65 |
+
const searchParams = useSearchParams()
|
| 66 |
+
const success = searchParams.get('success')
|
| 67 |
+
const canceled = searchParams.get('canceled')
|
| 68 |
+
const mockPlan = searchParams.get('mock_plan')
|
| 69 |
+
const [showToast, setShowToast] = useState<{ type: 'success' | 'error', message: string } | null>(null)
|
| 70 |
|
| 71 |
useEffect(() => {
|
| 72 |
fetchBilling()
|
| 73 |
+
if (success) {
|
| 74 |
+
if (mockPlan) {
|
| 75 |
+
// Mock Mode Activation
|
| 76 |
+
api.post(`/api/v1/billing/mock-success?plan=${mockPlan}`).then(() => {
|
| 77 |
+
setShowToast({ type: 'success', message: 'Тестовая подписка активирована! (Mock Mode)' })
|
| 78 |
+
fetchBilling() // Refresh to show new status
|
| 79 |
+
})
|
| 80 |
+
} else {
|
| 81 |
+
setShowToast({ type: 'success', message: 'Подписка успешно обновлена! Добро пожаловать на новый уровень.' })
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
if (canceled) setShowToast({ type: 'error', message: 'Оплата отменена. Средства не были списаны.' })
|
| 85 |
+
}, [success, canceled, mockPlan])
|
| 86 |
|
| 87 |
const fetchBilling = async () => {
|
| 88 |
try {
|
| 89 |
+
const response = await api.get('/api/v1/tenants/me/usage')
|
| 90 |
+
setData(response.data)
|
| 91 |
} catch (error) {
|
| 92 |
console.error('Failed to fetch billing:', error)
|
| 93 |
} finally {
|
|
|
|
| 95 |
}
|
| 96 |
}
|
| 97 |
|
| 98 |
+
const handleCheckout = async (planId: string) => {
|
| 99 |
+
if (processing) return
|
| 100 |
+
setProcessing(planId)
|
| 101 |
+
|
| 102 |
+
try {
|
| 103 |
+
// Direct Stripe Checkout
|
| 104 |
+
const response = await api.post('/api/v1/billing/checkout', { plan: planId })
|
| 105 |
+
if (response.data.url) {
|
| 106 |
+
window.location.href = response.data.url
|
| 107 |
+
}
|
| 108 |
+
} catch (error) {
|
| 109 |
+
console.error('Checkout failed:', error)
|
| 110 |
+
setShowToast({ type: 'error', message: 'Не удалось начать оплату. Попробуйте снова.' })
|
| 111 |
+
setProcessing(null)
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
|
| 115 |
+
const handlePortal = async () => {
|
| 116 |
+
if (processing) return
|
| 117 |
+
setProcessing('portal')
|
| 118 |
|
|
|
|
| 119 |
try {
|
| 120 |
+
const response = await api.post('/api/v1/billing/portal')
|
| 121 |
+
if (response.data.url) {
|
| 122 |
+
window.location.href = response.data.url
|
| 123 |
+
}
|
| 124 |
} catch (error) {
|
| 125 |
+
console.error('Portal failed:', error)
|
| 126 |
+
setShowToast({ type: 'error', message: 'Не удалось открыть портал управления.' })
|
| 127 |
+
setProcessing(null)
|
|
|
|
| 128 |
}
|
| 129 |
}
|
| 130 |
|
| 131 |
if (loading) {
|
| 132 |
return (
|
| 133 |
+
<div className="flex items-center justify-center min-h-screen bg-[#020005]">
|
| 134 |
+
<Loader2 className="w-8 h-8 animate-spin text-indigo-500" />
|
| 135 |
+
</div>
|
| 136 |
+
)
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
if (!data) {
|
| 140 |
+
return (
|
| 141 |
+
<div className="flex items-center justify-center min-h-screen bg-[#020005] text-red-500">
|
| 142 |
+
<AlertTriangle className="w-6 h-6 mr-2" />
|
| 143 |
+
<span>Не удалось загрузить данные биллинга. Попробуйте позже.</span>
|
| 144 |
</div>
|
| 145 |
)
|
| 146 |
}
|
| 147 |
|
| 148 |
+
const currentPlanId = data?.plan.id.toLowerCase() || 'trial'
|
| 149 |
+
const isTrial = currentPlanId === 'trial'
|
| 150 |
|
| 151 |
return (
|
| 152 |
+
<div className="min-h-screen bg-[#020005] p-8 font-['Inter'] text-slate-200">
|
| 153 |
+
<div className="max-w-6xl mx-auto space-y-10">
|
| 154 |
+
|
| 155 |
+
{/* Toast Notification */}
|
| 156 |
+
<AnimatePresence>
|
| 157 |
+
{showToast && (
|
| 158 |
+
<motion.div
|
| 159 |
+
initial={{ opacity: 0, y: -20 }}
|
| 160 |
+
animate={{ opacity: 1, y: 0 }}
|
| 161 |
+
exit={{ opacity: 0 }}
|
| 162 |
+
className={cn(
|
| 163 |
+
"fixed top-8 right-8 z-50 px-6 py-4 rounded-xl border backdrop-blur-xl shadow-2xl flex items-center gap-3",
|
| 164 |
+
showToast.type === 'success'
|
| 165 |
+
? "bg-emerald-500/10 border-emerald-500/30 text-emerald-400"
|
| 166 |
+
: "bg-red-500/10 border-red-500/30 text-red-400"
|
| 167 |
+
)}
|
| 168 |
+
>
|
| 169 |
+
{showToast.type === 'success' ? <Check className="w-5 h-5" /> : <AlertTriangle className="w-5 h-5" />}
|
| 170 |
+
<span className="font-medium">{showToast.message}</span>
|
| 171 |
+
<button onClick={() => setShowToast(null)} className="ml-4 hover:opacity-70"><X className="w-4 h-4" /></button>
|
| 172 |
+
</motion.div>
|
| 173 |
+
)}
|
| 174 |
+
</AnimatePresence>
|
| 175 |
|
| 176 |
{/* Header */}
|
| 177 |
<div className="flex items-center justify-between">
|
| 178 |
<div>
|
| 179 |
+
<h1 className="text-3xl font-black text-white tracking-tight uppercase flex items-center gap-3">
|
| 180 |
+
<span className="bg-clip-text text-transparent bg-gradient-to-r from-indigo-400 to-purple-400">
|
| 181 |
+
Command Center
|
| 182 |
+
</span>
|
| 183 |
+
<span className="text-slate-600">/</span>
|
| 184 |
+
BILLING
|
| 185 |
+
</h1>
|
| 186 |
+
<p className="text-slate-500 mt-2 font-mono text-sm tracking-wide">
|
| 187 |
+
Управление подпиской и лимитами использования.
|
| 188 |
+
</p>
|
| 189 |
+
</div>
|
| 190 |
+
|
| 191 |
+
{/* Status Badge */}
|
| 192 |
+
<div className={cn(
|
| 193 |
+
"px-4 py-2 rounded-lg border flex items-center gap-2 font-bold font-mono text-xs tracking-wider uppercase",
|
| 194 |
+
data?.subscription_status === 'active'
|
| 195 |
+
? "bg-emerald-500/10 border-emerald-500/30 text-emerald-400"
|
| 196 |
+
: "bg-amber-500/10 border-amber-500/30 text-amber-400"
|
| 197 |
+
)}>
|
| 198 |
+
<div className={cn(
|
| 199 |
+
"w-2 h-2 rounded-full animate-pulse",
|
| 200 |
+
data?.subscription_status === 'active' ? "bg-emerald-500" : "bg-amber-500"
|
| 201 |
+
)} />
|
| 202 |
+
СТАТУС: {data?.subscription_status === 'active' ? 'АКТИВЕН' : 'НЕАКТИВЕН'}
|
| 203 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
</div>
|
| 205 |
|
| 206 |
+
{/* Stats Dashboard */}
|
| 207 |
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
| 208 |
+
{/* Current Plan */}
|
| 209 |
<motion.div
|
| 210 |
+
initial={{ opacity: 0, scale: 0.95 }}
|
| 211 |
+
animate={{ opacity: 1, scale: 1 }}
|
| 212 |
+
className="group relative bg-[#0A0A1F] border border-white/5 p-6 rounded-2xl overflow-hidden hover:border-indigo-500/30 transition-all duration-500"
|
| 213 |
>
|
| 214 |
+
<div className="absolute inset-0 bg-gradient-to-br from-indigo-500/5 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
|
| 215 |
+
<div className="relative z-10 flex flex-col h-full">
|
| 216 |
+
<div className="flex items-start justify-between mb-4">
|
| 217 |
+
<div>
|
| 218 |
+
<p className="text-xs font-bold text-indigo-400 uppercase tracking-widest font-mono mb-1">Текущий тариф</p>
|
| 219 |
+
<h3 className="text-2xl font-black text-white">{data?.plan.name}</h3>
|
| 220 |
+
</div>
|
| 221 |
+
<div className="p-2.5 bg-indigo-500/10 rounded-lg text-indigo-400 border border-indigo-500/20">
|
| 222 |
+
<Crown className="w-5 h-5" />
|
| 223 |
+
</div>
|
| 224 |
</div>
|
| 225 |
+
<div className="mt-auto pt-4 border-t border-white/5">
|
| 226 |
+
<div className="flex items-baseline gap-1">
|
| 227 |
+
<span className="text-2xl font-bold text-white">${data?.plan.price}</span>
|
| 228 |
+
<span className="text-xs text-slate-500 font-mono">/МЕС</span>
|
| 229 |
+
</div>
|
| 230 |
</div>
|
| 231 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
</motion.div>
|
| 233 |
|
| 234 |
+
{/* Usage Metrics */}
|
| 235 |
<motion.div
|
| 236 |
+
initial={{ opacity: 0, scale: 0.95 }}
|
| 237 |
+
animate={{ opacity: 1, scale: 1 }}
|
| 238 |
transition={{ delay: 0.1 }}
|
| 239 |
+
className="group relative bg-[#0A0A1F] border border-white/5 p-6 rounded-2xl overflow-hidden hover:border-blue-500/30 transition-all duration-500"
|
| 240 |
>
|
| 241 |
+
<div className="absolute inset-0 bg-gradient-to-br from-blue-500/5 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
|
| 242 |
+
<div className="relative z-10">
|
| 243 |
+
<div className="flex items-start justify-between mb-6">
|
| 244 |
+
<div>
|
| 245 |
+
<p className="text-xs font-bold text-blue-400 uppercase tracking-widest font-mono mb-1">Диалоги</p>
|
| 246 |
+
<h3 className="text-2xl font-black text-white">
|
| 247 |
+
{data?.usage.conversations_used} <span className="text-slate-600 text-lg">/ {data?.plan.limits.conversations === null ? '∞' : data?.plan.limits.conversations}</span>
|
| 248 |
+
</h3>
|
| 249 |
+
</div>
|
| 250 |
+
<div className="p-2.5 bg-blue-500/10 rounded-lg text-blue-400 border border-blue-500/20">
|
| 251 |
+
<BarChart3 className="w-5 h-5" />
|
| 252 |
+
</div>
|
| 253 |
</div>
|
| 254 |
+
|
| 255 |
+
{data?.plan.limits.conversations !== null && (
|
| 256 |
+
<div className="space-y-2">
|
| 257 |
+
<div className="h-2 w-full bg-white/5 rounded-full overflow-hidden">
|
| 258 |
+
<div
|
| 259 |
+
className={cn(
|
| 260 |
+
"h-full rounded-full transition-all duration-1000 ease-out",
|
| 261 |
+
data.usage.usage_percentage > 90 ? "bg-red-500 shadow-[0_0_10px_rgba(239,68,68,0.5)]" : "bg-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.5)]"
|
| 262 |
+
)}
|
| 263 |
+
style={{ width: `${Math.min(data.usage.usage_percentage, 100)}%` }}
|
| 264 |
+
/>
|
| 265 |
+
</div>
|
| 266 |
+
<p className="text-[10px] text-right text-slate-500 font-mono">
|
| 267 |
+
{data.usage.usage_percentage.toFixed(1)}% ИСПОЛЬЗОВАНО
|
| 268 |
+
</p>
|
| 269 |
+
</div>
|
| 270 |
+
)}
|
| 271 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
</motion.div>
|
| 273 |
|
| 274 |
+
{/* Renewal / Portal */}
|
| 275 |
<motion.div
|
| 276 |
+
initial={{ opacity: 0, scale: 0.95 }}
|
| 277 |
+
animate={{ opacity: 1, scale: 1 }}
|
| 278 |
transition={{ delay: 0.2 }}
|
| 279 |
+
className="group relative bg-[#0A0A1F] border border-white/5 p-6 rounded-2xl overflow-hidden hover:border-emerald-500/30 transition-all duration-500"
|
| 280 |
>
|
| 281 |
+
<div className="absolute inset-0 bg-gradient-to-br from-emerald-500/5 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
|
| 282 |
+
<div className="relative z-10 flex flex-col h-full">
|
| 283 |
+
<div className="flex items-start justify-between mb-4">
|
| 284 |
+
<div>
|
| 285 |
+
<p className="text-xs font-bold text-emerald-400 uppercase tracking-widest font-mono mb-1">Дней осталось</p>
|
| 286 |
+
<h3 className="text-xl font-bold text-white">
|
| 287 |
+
{data?.usage.days_left} Дней
|
| 288 |
+
</h3>
|
| 289 |
+
</div>
|
| 290 |
+
<div className="p-2.5 bg-emerald-500/10 rounded-lg text-emerald-400 border border-emerald-500/20">
|
| 291 |
+
<Clock className="w-5 h-5" />
|
| 292 |
+
</div>
|
| 293 |
</div>
|
| 294 |
+
|
| 295 |
+
<div className="mt-auto">
|
| 296 |
+
{/* Manage Subscription Button if not Trial */}
|
| 297 |
+
{!isTrial ? (
|
| 298 |
+
<button
|
| 299 |
+
onClick={handlePortal}
|
| 300 |
+
disabled={processing === 'portal'}
|
| 301 |
+
className="w-full py-2 bg-white/5 hover:bg-white/10 border border-white/10 rounded-lg text-xs font-bold text-white transition-all flex items-center justify-center gap-2 group/btn"
|
| 302 |
+
>
|
| 303 |
+
{processing === 'portal' ? (
|
| 304 |
+
<Loader2 className="w-3 h-3 animate-spin" />
|
| 305 |
+
) : (
|
| 306 |
+
<>
|
| 307 |
+
УПРАВЛЕНИЕ ПОДПИСКОЙ
|
| 308 |
+
<ArrowUpRight className="w-3 h-3 text-slate-400 group-hover/btn:text-white group-hover/btn:translate-x-0.5 group-hover/btn:-translate-y-0.5 transition-all" />
|
| 309 |
+
</>
|
| 310 |
+
)}
|
| 311 |
+
</button>
|
| 312 |
+
) : (
|
| 313 |
+
<p className="text-xs text-slate-500 font-mono">
|
| 314 |
+
ПРОБНЫЙ ПЕРИОД ДО: {data?.usage.current_period_end ? new Date(data.usage.current_period_end).toLocaleDateString() : 'N/A'}
|
| 315 |
+
</p>
|
| 316 |
+
)}
|
| 317 |
</div>
|
| 318 |
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
</motion.div>
|
| 320 |
</div>
|
| 321 |
|
| 322 |
{/* Plans Grid */}
|
| 323 |
+
<div className="pt-8 border-t border-white/10">
|
| 324 |
+
<h2 className="text-xl font-black text-white mb-8 tracking-tight flex items-center gap-2">
|
| 325 |
+
ДОСТУПНЫЕ ТАРИФЫ <span className="px-2 py-0.5 rounded bg-indigo-500/20 text-indigo-400 text-[10px] font-mono border border-indigo-500/30">UPGRADE</span>
|
| 326 |
+
</h2>
|
|
|
|
| 327 |
|
| 328 |
+
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
| 329 |
+
{PLANS.map((plan, index) => {
|
| 330 |
+
const isCurrent = currentPlanId === plan.id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
+
return (
|
| 333 |
+
<motion.div
|
| 334 |
+
key={plan.id}
|
| 335 |
+
initial={{ opacity: 0, y: 20 }}
|
| 336 |
+
animate={{ opacity: 1, y: 0 }}
|
| 337 |
+
transition={{ delay: 0.1 * index }}
|
| 338 |
className={cn(
|
| 339 |
+
"relative rounded-2xl p-6 transition-all duration-500 flex flex-col",
|
| 340 |
isCurrent
|
| 341 |
+
? "bg-[#0A0A1F] border-2 border-indigo-500/50 shadow-[0_0_30px_-5px_rgba(99,102,241,0.2)]"
|
| 342 |
+
: "bg-[#050510] border border-white/5 hover:border-white/10 hover:translate-y-[-4px]",
|
| 343 |
+
plan.popular && !isCurrent ? "border-purple-500/30 shadow-[0_0_20px_-5px_rgba(168,85,247,0.1)]" : ""
|
| 344 |
)}
|
| 345 |
>
|
| 346 |
+
{plan.popular && !isCurrent && (
|
| 347 |
+
<div className="absolute -top-3 left-1/2 -translate-x-1/2 bg-gradient-to-r from-purple-600 to-indigo-600 text-white px-3 py-0.5 rounded-full text-[10px] font-bold tracking-widest border border-white/10 shadow-lg">
|
| 348 |
+
РЕКОМЕНДУЕМ
|
| 349 |
+
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
)}
|
| 351 |
+
|
| 352 |
+
<div className="mb-6">
|
| 353 |
+
<h3 className="text-lg font-black text-white tracking-wide">{plan.name}</h3>
|
| 354 |
+
<div className="flex items-baseline gap-1 mt-2">
|
| 355 |
+
<span className="text-3xl font-bold text-white">${plan.price}</span>
|
| 356 |
+
<span className="text-sm text-slate-500 font-mono">/МЕС</span>
|
| 357 |
+
</div>
|
| 358 |
+
</div>
|
| 359 |
+
|
| 360 |
+
<ul className="space-y-4 mb-8 flex-1">
|
| 361 |
+
{plan.features.map((feature, i) => (
|
| 362 |
+
<li key={i} className="flex items-start gap-3 text-sm text-slate-400">
|
| 363 |
+
<div className={cn(
|
| 364 |
+
"mt-0.5 w-4 h-4 rounded-full flex items-center justify-center flex-shrink-0",
|
| 365 |
+
isCurrent ? "bg-indigo-500/20 text-indigo-400" : "bg-white/5 text-slate-500"
|
| 366 |
+
)}>
|
| 367 |
+
<Check className="w-2.5 h-2.5" />
|
| 368 |
+
</div>
|
| 369 |
+
{feature}
|
| 370 |
+
</li>
|
| 371 |
+
))}
|
| 372 |
+
</ul>
|
| 373 |
+
|
| 374 |
+
<button
|
| 375 |
+
onClick={() => handleCheckout(plan.id)}
|
| 376 |
+
disabled={processing !== null || isCurrent}
|
| 377 |
+
className={cn(
|
| 378 |
+
"w-full py-3.5 rounded-xl font-bold font-mono text-xs tracking-wider uppercase transition-all flex items-center justify-center gap-2",
|
| 379 |
+
isCurrent
|
| 380 |
+
? "bg-white/5 text-slate-500 cursor-not-allowed border border-white/5"
|
| 381 |
+
: "bg-indigo-600 hover:bg-indigo-500 text-white shadow-lg shadow-indigo-500/20 hover:shadow-indigo-500/40",
|
| 382 |
+
processing === plan.id && "opacity-70 cursor-wait"
|
| 383 |
+
)}
|
| 384 |
+
>
|
| 385 |
+
{processing === plan.id ? (
|
| 386 |
+
<Loader2 className="w-4 h-4 animate-spin" />
|
| 387 |
+
) : isCurrent ? (
|
| 388 |
+
<span className="flex items-center gap-2">
|
| 389 |
+
<Check className="w-3 h-3" /> ТЕКУЩИЙ ТАРИФ
|
| 390 |
+
</span>
|
| 391 |
+
) : (
|
| 392 |
+
<>
|
| 393 |
+
ВЫБРАТЬ {plan.name}
|
| 394 |
+
<ArrowUpRight className="w-3 h-3" />
|
| 395 |
+
</>
|
| 396 |
+
)}
|
| 397 |
+
</button>
|
| 398 |
+
</motion.div>
|
| 399 |
+
)
|
| 400 |
+
})}
|
| 401 |
+
</div>
|
| 402 |
</div>
|
| 403 |
+
|
| 404 |
</div>
|
| 405 |
</div>
|
| 406 |
)
|
frontend/app/settings/brain/page.tsx
CHANGED
|
@@ -1,16 +1,20 @@
|
|
| 1 |
'use client'
|
| 2 |
|
| 3 |
-
import { useState, useEffect } from 'react'
|
| 4 |
import { useAuth } from '@/contexts/AuthContext'
|
| 5 |
import {
|
| 6 |
Brain, Plus, X, Save, Loader2, Sparkles, Target, TrendingUp, Zap, Shield, Users,
|
| 7 |
BookOpen, Award, Ban, Calculator, DollarSign, CheckCircle2, AlertCircle,
|
| 8 |
-
LayoutGrid, Calendar, ShoppingBag, Briefcase
|
| 9 |
} from 'lucide-react'
|
| 10 |
import { motion, AnimatePresence } from 'framer-motion'
|
| 11 |
import { cn } from '@/lib/utils'
|
| 12 |
-
import { api } from '@/lib/api'
|
| 13 |
import BookingSettings from '@/components/BookingSettings'
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
interface AISettings {
|
| 16 |
business_description: string
|
|
@@ -28,7 +32,7 @@ interface AIPersona {
|
|
| 28 |
manager_monthly_salary: number
|
| 29 |
}
|
| 30 |
|
| 31 |
-
type TabType = 'persona' | 'booking'
|
| 32 |
|
| 33 |
interface BotIdentity {
|
| 34 |
bot_name: string
|
|
@@ -77,6 +81,8 @@ const METHODOLOGY_OPTIONS = [
|
|
| 77 |
|
| 78 |
export default function BrainSettingsPage() {
|
| 79 |
const { user } = useAuth()
|
|
|
|
|
|
|
| 80 |
const [loading, setLoading] = useState(true)
|
| 81 |
const [saving, setSaving] = useState(false)
|
| 82 |
const [activeTab, setActiveTab] = useState<TabType>('persona')
|
|
@@ -84,6 +90,10 @@ export default function BrainSettingsPage() {
|
|
| 84 |
const [newField, setNewField] = useState('')
|
| 85 |
const [newBannedWord, setNewBannedWord] = useState('')
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
const [settings, setSettings] = useState<AISettings>({
|
| 88 |
business_description: '',
|
| 89 |
selling_style: 'Consultative',
|
|
@@ -105,6 +115,64 @@ export default function BrainSettingsPage() {
|
|
| 105 |
bot_role: ''
|
| 106 |
})
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
useEffect(() => {
|
| 110 |
if (user) {
|
|
@@ -154,10 +222,10 @@ export default function BrainSettingsPage() {
|
|
| 154 |
},
|
| 155 |
...persona
|
| 156 |
})
|
| 157 |
-
|
| 158 |
} catch (error) {
|
| 159 |
console.error('Failed to save AI settings:', error)
|
| 160 |
-
|
| 161 |
} finally {
|
| 162 |
setSaving(false)
|
| 163 |
}
|
|
@@ -169,11 +237,11 @@ export default function BrainSettingsPage() {
|
|
| 169 |
await api.patch(`/api/v1/tenants/${user.tenant_id}`, {
|
| 170 |
booking_settings: newSettings
|
| 171 |
})
|
| 172 |
-
|
| 173 |
setBookingSettings(newSettings)
|
| 174 |
} catch (error) {
|
| 175 |
console.error('Failed to save booking settings:', error)
|
| 176 |
-
|
| 177 |
}
|
| 178 |
}
|
| 179 |
|
|
@@ -181,7 +249,7 @@ export default function BrainSettingsPage() {
|
|
| 181 |
const addCustomField = () => {
|
| 182 |
if (!newField.trim()) return
|
| 183 |
if (settings.custom_fields.includes(newField.trim())) {
|
| 184 |
-
|
| 185 |
return
|
| 186 |
}
|
| 187 |
|
|
@@ -202,7 +270,7 @@ export default function BrainSettingsPage() {
|
|
| 202 |
const addBannedWord = () => {
|
| 203 |
if (!newBannedWord.trim()) return
|
| 204 |
if (persona.banned_words.includes(newBannedWord.trim())) {
|
| 205 |
-
|
| 206 |
return
|
| 207 |
}
|
| 208 |
|
|
@@ -266,7 +334,7 @@ export default function BrainSettingsPage() {
|
|
| 266 |
</div>
|
| 267 |
|
| 268 |
{/* Navigation Tabs */}
|
| 269 |
-
<div className="flex gap-2 p-1 bg-white rounded-xl border border-slate-200 w-fit">
|
| 270 |
<button
|
| 271 |
onClick={() => setActiveTab('persona')}
|
| 272 |
className={cn(
|
|
@@ -280,7 +348,31 @@ export default function BrainSettingsPage() {
|
|
| 280 |
Личность & Правила
|
| 281 |
</button>
|
| 282 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
<button
|
| 286 |
onClick={() => setActiveTab('booking')}
|
|
@@ -297,7 +389,7 @@ export default function BrainSettingsPage() {
|
|
| 297 |
</div>
|
| 298 |
</motion.div>
|
| 299 |
|
| 300 |
-
|
| 301 |
|
| 302 |
{activeTab === 'booking' && (
|
| 303 |
<BookingSettings
|
|
@@ -306,6 +398,266 @@ export default function BrainSettingsPage() {
|
|
| 306 |
/>
|
| 307 |
)}
|
| 308 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
{activeTab === 'persona' && (
|
| 310 |
<motion.div
|
| 311 |
variants={container}
|
|
|
|
| 1 |
'use client'
|
| 2 |
|
| 3 |
+
import { useState, useEffect, useCallback } from 'react'
|
| 4 |
import { useAuth } from '@/contexts/AuthContext'
|
| 5 |
import {
|
| 6 |
Brain, Plus, X, Save, Loader2, Sparkles, Target, TrendingUp, Zap, Shield, Users,
|
| 7 |
BookOpen, Award, Ban, Calculator, DollarSign, CheckCircle2, AlertCircle,
|
| 8 |
+
LayoutGrid, Calendar, ShoppingBag, Briefcase, FileText, Upload, Trash2, Search
|
| 9 |
} from 'lucide-react'
|
| 10 |
import { motion, AnimatePresence } from 'framer-motion'
|
| 11 |
import { cn } from '@/lib/utils'
|
| 12 |
+
import { api, knowledgeApi } from '@/lib/api'
|
| 13 |
import BookingSettings from '@/components/BookingSettings'
|
| 14 |
+
import ProductSettings from '@/components/settings/ProductSettings'
|
| 15 |
+
import { useDropzone } from 'react-dropzone'
|
| 16 |
+
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
| 17 |
+
import { useToast } from '@/contexts/ToastContext'
|
| 18 |
|
| 19 |
interface AISettings {
|
| 20 |
business_description: string
|
|
|
|
| 32 |
manager_monthly_salary: number
|
| 33 |
}
|
| 34 |
|
| 35 |
+
type TabType = 'persona' | 'knowledge' | 'catalog' | 'booking'
|
| 36 |
|
| 37 |
interface BotIdentity {
|
| 38 |
bot_name: string
|
|
|
|
| 81 |
|
| 82 |
export default function BrainSettingsPage() {
|
| 83 |
const { user } = useAuth()
|
| 84 |
+
const toast = useToast()
|
| 85 |
+
const queryClient = useQueryClient()
|
| 86 |
const [loading, setLoading] = useState(true)
|
| 87 |
const [saving, setSaving] = useState(false)
|
| 88 |
const [activeTab, setActiveTab] = useState<TabType>('persona')
|
|
|
|
| 90 |
const [newField, setNewField] = useState('')
|
| 91 |
const [newBannedWord, setNewBannedWord] = useState('')
|
| 92 |
|
| 93 |
+
// Knowledge State
|
| 94 |
+
const [searchQuery, setSearchQuery] = useState('')
|
| 95 |
+
const [uploadedFiles, setUploadedFiles] = useState<string[]>([])
|
| 96 |
+
|
| 97 |
const [settings, setSettings] = useState<AISettings>({
|
| 98 |
business_description: '',
|
| 99 |
selling_style: 'Consultative',
|
|
|
|
| 115 |
bot_role: ''
|
| 116 |
})
|
| 117 |
|
| 118 |
+
// --- Knowledge Queries ---
|
| 119 |
+
const { data: knowledgeData, isLoading: knowledgeLoading } = useQuery({
|
| 120 |
+
queryKey: ['knowledge', user?.tenant_id],
|
| 121 |
+
queryFn: () => knowledgeApi.list({ limit: 100 }),
|
| 122 |
+
enabled: !!user && activeTab === 'knowledge',
|
| 123 |
+
})
|
| 124 |
+
|
| 125 |
+
const { data: searchResults, isLoading: isSearching } = useQuery({
|
| 126 |
+
queryKey: ['knowledge-search', user?.tenant_id, searchQuery],
|
| 127 |
+
queryFn: () => knowledgeApi.search(searchQuery, 10),
|
| 128 |
+
enabled: !!user && searchQuery.length > 2 && activeTab === 'knowledge',
|
| 129 |
+
})
|
| 130 |
+
|
| 131 |
+
const uploadMutation = useMutation({
|
| 132 |
+
mutationFn: async (file: File) => {
|
| 133 |
+
if (!user) throw new Error('Пользователь не авторизован')
|
| 134 |
+
return knowledgeApi.upload(file)
|
| 135 |
+
},
|
| 136 |
+
onSuccess: (data, file) => {
|
| 137 |
+
queryClient.invalidateQueries({ queryKey: ['knowledge', user?.tenant_id] })
|
| 138 |
+
toast.success('Успех!', `Файл "${file.name}" успешно загружен и изучен AI`)
|
| 139 |
+
setUploadedFiles(prev => [...prev, file.name])
|
| 140 |
+
setTimeout(() => {
|
| 141 |
+
setUploadedFiles(prev => prev.filter(f => f !== file.name))
|
| 142 |
+
}, 3000)
|
| 143 |
+
},
|
| 144 |
+
onError: (error: Error) => {
|
| 145 |
+
toast.error('Ошибка', 'Не удалось загрузить файл')
|
| 146 |
+
},
|
| 147 |
+
})
|
| 148 |
+
|
| 149 |
+
const deleteMutation = useMutation({
|
| 150 |
+
mutationFn: async (id: string) => {
|
| 151 |
+
// Implement delete API call here if available, currently mock or pending
|
| 152 |
+
return Promise.resolve()
|
| 153 |
+
},
|
| 154 |
+
onSuccess: () => {
|
| 155 |
+
queryClient.invalidateQueries({ queryKey: ['knowledge', user?.tenant_id] })
|
| 156 |
+
toast.success('Удалено', 'Запись удалена из базы знаний')
|
| 157 |
+
}
|
| 158 |
+
})
|
| 159 |
+
|
| 160 |
+
const onDrop = useCallback((acceptedFiles: File[]) => {
|
| 161 |
+
if (acceptedFiles.length === 0) return
|
| 162 |
+
|
| 163 |
+
acceptedFiles.forEach((file) => {
|
| 164 |
+
uploadMutation.mutate(file)
|
| 165 |
+
})
|
| 166 |
+
}, [uploadMutation])
|
| 167 |
+
|
| 168 |
+
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
| 169 |
+
onDrop,
|
| 170 |
+
accept: {
|
| 171 |
+
'application/pdf': ['.pdf'],
|
| 172 |
+
'text/plain': ['.txt'],
|
| 173 |
+
},
|
| 174 |
+
})
|
| 175 |
+
// -------------------------
|
| 176 |
|
| 177 |
useEffect(() => {
|
| 178 |
if (user) {
|
|
|
|
| 222 |
},
|
| 223 |
...persona
|
| 224 |
})
|
| 225 |
+
toast.success('Успех!', 'Настройки AI Brain сохранены')
|
| 226 |
} catch (error) {
|
| 227 |
console.error('Failed to save AI settings:', error)
|
| 228 |
+
toast.error('Ошибка', 'Не удалось сохранить настройки')
|
| 229 |
} finally {
|
| 230 |
setSaving(false)
|
| 231 |
}
|
|
|
|
| 237 |
await api.patch(`/api/v1/tenants/${user.tenant_id}`, {
|
| 238 |
booking_settings: newSettings
|
| 239 |
})
|
| 240 |
+
toast.success('Успех!', 'Настройки записи сохранены')
|
| 241 |
setBookingSettings(newSettings)
|
| 242 |
} catch (error) {
|
| 243 |
console.error('Failed to save booking settings:', error)
|
| 244 |
+
toast.error('Ошибка', 'Не удалось сохранить настройки записи')
|
| 245 |
}
|
| 246 |
}
|
| 247 |
|
|
|
|
| 249 |
const addCustomField = () => {
|
| 250 |
if (!newField.trim()) return
|
| 251 |
if (settings.custom_fields.includes(newField.trim())) {
|
| 252 |
+
toast.error('Ошибка', 'Это поле уже добавлено')
|
| 253 |
return
|
| 254 |
}
|
| 255 |
|
|
|
|
| 270 |
const addBannedWord = () => {
|
| 271 |
if (!newBannedWord.trim()) return
|
| 272 |
if (persona.banned_words.includes(newBannedWord.trim())) {
|
| 273 |
+
toast.error('Ошибка', 'Это слово уже в списке')
|
| 274 |
return
|
| 275 |
}
|
| 276 |
|
|
|
|
| 334 |
</div>
|
| 335 |
|
| 336 |
{/* Navigation Tabs */}
|
| 337 |
+
<div className="flex flex-wrap gap-2 p-1 bg-white rounded-xl border border-slate-200 w-fit">
|
| 338 |
<button
|
| 339 |
onClick={() => setActiveTab('persona')}
|
| 340 |
className={cn(
|
|
|
|
| 348 |
Личность & Правила
|
| 349 |
</button>
|
| 350 |
|
| 351 |
+
<button
|
| 352 |
+
onClick={() => setActiveTab('knowledge')}
|
| 353 |
+
className={cn(
|
| 354 |
+
"px-6 py-2.5 rounded-lg text-sm font-bold flex items-center gap-2 transition-all",
|
| 355 |
+
activeTab === 'knowledge'
|
| 356 |
+
? "bg-slate-100 text-slate-900 shadow-sm"
|
| 357 |
+
: "text-slate-500 hover:text-slate-700 hover:bg-slate-50"
|
| 358 |
+
)}
|
| 359 |
+
>
|
| 360 |
+
<FileText className="w-4 h-4" />
|
| 361 |
+
Знания (RAG)
|
| 362 |
+
</button>
|
| 363 |
|
| 364 |
+
<button
|
| 365 |
+
onClick={() => setActiveTab('catalog')}
|
| 366 |
+
className={cn(
|
| 367 |
+
"px-6 py-2.5 rounded-lg text-sm font-bold flex items-center gap-2 transition-all",
|
| 368 |
+
activeTab === 'catalog'
|
| 369 |
+
? "bg-slate-100 text-slate-900 shadow-sm"
|
| 370 |
+
: "text-slate-500 hover:text-slate-700 hover:bg-slate-50"
|
| 371 |
+
)}
|
| 372 |
+
>
|
| 373 |
+
<ShoppingBag className="w-4 h-4" />
|
| 374 |
+
Товары
|
| 375 |
+
</button>
|
| 376 |
|
| 377 |
<button
|
| 378 |
onClick={() => setActiveTab('booking')}
|
|
|
|
| 389 |
</div>
|
| 390 |
</motion.div>
|
| 391 |
|
| 392 |
+
{/* --- CONTENT SECTIONS --- */}
|
| 393 |
|
| 394 |
{activeTab === 'booking' && (
|
| 395 |
<BookingSettings
|
|
|
|
| 398 |
/>
|
| 399 |
)}
|
| 400 |
|
| 401 |
+
{activeTab === 'catalog' && (
|
| 402 |
+
<motion.div
|
| 403 |
+
variants={container}
|
| 404 |
+
initial="hidden"
|
| 405 |
+
animate="show"
|
| 406 |
+
>
|
| 407 |
+
<ProductSettings />
|
| 408 |
+
</motion.div>
|
| 409 |
+
)}
|
| 410 |
+
|
| 411 |
+
{activeTab === 'knowledge' && (
|
| 412 |
+
<motion.div
|
| 413 |
+
variants={container}
|
| 414 |
+
initial="hidden"
|
| 415 |
+
animate="show"
|
| 416 |
+
className="space-y-6"
|
| 417 |
+
>
|
| 418 |
+
{/* Upload Zone */}
|
| 419 |
+
<motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 p-8">
|
| 420 |
+
<h2 className="text-lg font-bold text-slate-900 mb-6 flex items-center gap-2">
|
| 421 |
+
<Upload className="w-5 h-5 text-indigo-600" />
|
| 422 |
+
Загрузить файлы
|
| 423 |
+
</h2>
|
| 424 |
+
<div
|
| 425 |
+
{...getRootProps()}
|
| 426 |
+
className={cn(
|
| 427 |
+
"border-2 border-dashed rounded-xl p-12 text-center cursor-pointer transition-all duration-300 relative overflow-hidden",
|
| 428 |
+
isDragActive
|
| 429 |
+
? "border-indigo-500 bg-indigo-50/50 scale-[1.01]"
|
| 430 |
+
: "border-slate-200 hover:border-indigo-400 hover:bg-slate-50",
|
| 431 |
+
uploadMutation.isPending && "opacity-75 cursor-wait"
|
| 432 |
+
)}
|
| 433 |
+
>
|
| 434 |
+
<input {...getInputProps()} />
|
| 435 |
+
<div className="flex flex-col items-center gap-4 relative z-10">
|
| 436 |
+
{uploadMutation.isPending ? (
|
| 437 |
+
<>
|
| 438 |
+
<div className="p-4 bg-indigo-50 rounded-full">
|
| 439 |
+
<Loader2 className="w-8 h-8 text-indigo-600 animate-spin" />
|
| 440 |
+
</div>
|
| 441 |
+
<div>
|
| 442 |
+
<p className="text-indigo-900 font-bold text-lg">Обработка файла...</p>
|
| 443 |
+
<p className="text-sm text-indigo-600">AI анализирует содержимое</p>
|
| 444 |
+
</div>
|
| 445 |
+
</>
|
| 446 |
+
) : isDragActive ? (
|
| 447 |
+
<>
|
| 448 |
+
<div className="p-4 bg-indigo-100 rounded-full animate-bounce">
|
| 449 |
+
<Upload className="w-8 h-8 text-indigo-600" />
|
| 450 |
+
</div>
|
| 451 |
+
<p className="text-indigo-900 font-bold text-lg">Отпустите файлы здесь...</p>
|
| 452 |
+
</>
|
| 453 |
+
) : (
|
| 454 |
+
<>
|
| 455 |
+
<div className="p-4 bg-slate-100 rounded-full group-hover:bg-indigo-50 transition-colors">
|
| 456 |
+
<Upload className="w-8 h-8 text-slate-400 group-hover:text-indigo-600 transition-colors" />
|
| 457 |
+
</div>
|
| 458 |
+
<div>
|
| 459 |
+
<p className="text-slate-900 font-bold text-lg mb-1">
|
| 460 |
+
Перетащите PDF или TXT файлы сюда
|
| 461 |
+
</p>
|
| 462 |
+
<p className="text-sm text-slate-500">или кликните для выбора файлов</p>
|
| 463 |
+
</div>
|
| 464 |
+
<div className="flex items-center gap-4 text-xs font-medium text-slate-400 mt-2">
|
| 465 |
+
<span className="flex items-center gap-1.5 bg-slate-50 px-2 py-1 rounded-md border border-slate-100">
|
| 466 |
+
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
|
| 467 |
+
PDF документы
|
| 468 |
+
</span>
|
| 469 |
+
<span className="flex items-center gap-1.5 bg-slate-50 px-2 py-1 rounded-md border border-slate-100">
|
| 470 |
+
<CheckCircle2 className="w-3.5 h-3.5 text-emerald-500" />
|
| 471 |
+
TXT файлы
|
| 472 |
+
</span>
|
| 473 |
+
</div>
|
| 474 |
+
</>
|
| 475 |
+
)}
|
| 476 |
+
</div>
|
| 477 |
+
</div>
|
| 478 |
+
|
| 479 |
+
{/* Uploaded Files List */}
|
| 480 |
+
<AnimatePresence>
|
| 481 |
+
{uploadedFiles.length > 0 && (
|
| 482 |
+
<div className="mt-6 space-y-2">
|
| 483 |
+
{uploadedFiles.map((fileName, idx) => (
|
| 484 |
+
<motion.div
|
| 485 |
+
key={`${fileName}-${idx}`}
|
| 486 |
+
initial={{ opacity: 0, x: -20 }}
|
| 487 |
+
animate={{ opacity: 1, x: 0 }}
|
| 488 |
+
exit={{ opacity: 0, x: 20 }}
|
| 489 |
+
className="flex items-center gap-3 p-3 bg-emerald-50 border border-emerald-100 rounded-xl text-emerald-700"
|
| 490 |
+
>
|
| 491 |
+
<CheckCircle2 className="w-5 h-5 text-emerald-500 flex-shrink-0" />
|
| 492 |
+
<span className="text-sm font-medium truncate flex-1">{fileName}</span>
|
| 493 |
+
<span className="text-xs font-bold bg-white/50 px-2 py-1 rounded-md">Загружено</span>
|
| 494 |
+
</motion.div>
|
| 495 |
+
))}
|
| 496 |
+
</div>
|
| 497 |
+
)}
|
| 498 |
+
</AnimatePresence>
|
| 499 |
+
</motion.div>
|
| 500 |
+
|
| 501 |
+
{/* Search & Results */}
|
| 502 |
+
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
|
| 503 |
+
{/* Search Column */}
|
| 504 |
+
<motion.div variants={item} className="lg:col-span-2 space-y-6">
|
| 505 |
+
<div className="bg-white rounded-2xl shadow-sm border border-slate-200 p-6">
|
| 506 |
+
<h2 className="text-lg font-bold text-slate-900 mb-4 flex items-center gap-2">
|
| 507 |
+
<Search className="w-5 h-5 text-indigo-600" />
|
| 508 |
+
Проверка знаний (Тест)
|
| 509 |
+
</h2>
|
| 510 |
+
<div className="relative">
|
| 511 |
+
<Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-slate-400" />
|
| 512 |
+
<input
|
| 513 |
+
type="text"
|
| 514 |
+
placeholder="Введите вопрос или ключевые слова..."
|
| 515 |
+
value={searchQuery}
|
| 516 |
+
onChange={(e) => setSearchQuery(e.target.value)}
|
| 517 |
+
className="w-full pl-12 pr-10 py-4 bg-slate-50 border-2 border-slate-200 rounded-xl focus:ring-4 focus:ring-indigo-500/10 focus:border-indigo-500 transition-all font-medium text-slate-900 placeholder:text-slate-400"
|
| 518 |
+
/>
|
| 519 |
+
{searchQuery && (
|
| 520 |
+
<button
|
| 521 |
+
onClick={() => setSearchQuery('')}
|
| 522 |
+
className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
|
| 523 |
+
>
|
| 524 |
+
<X className="w-4 h-4" />
|
| 525 |
+
</button>
|
| 526 |
+
)}
|
| 527 |
+
</div>
|
| 528 |
+
|
| 529 |
+
<AnimatePresence mode="wait">
|
| 530 |
+
{searchQuery.length > 2 && (
|
| 531 |
+
<motion.div
|
| 532 |
+
initial={{ opacity: 0, height: 0 }}
|
| 533 |
+
animate={{ opacity: 1, height: 'auto' }}
|
| 534 |
+
exit={{ opacity: 0, height: 0 }}
|
| 535 |
+
className="mt-6"
|
| 536 |
+
>
|
| 537 |
+
<div className="flex items-center justify-between mb-4">
|
| 538 |
+
<h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
|
| 539 |
+
<Sparkles className="w-4 h-4 text-indigo-600" />
|
| 540 |
+
Результаты поиска
|
| 541 |
+
</h3>
|
| 542 |
+
<span className="text-xs font-medium text-slate-500 bg-slate-100 px-2 py-1 rounded-md">
|
| 543 |
+
{searchResults?.count || 0} найдено
|
| 544 |
+
</span>
|
| 545 |
+
</div>
|
| 546 |
+
|
| 547 |
+
{isSearching ? (
|
| 548 |
+
<div className="flex flex-col items-center justify-center py-12 text-slate-400">
|
| 549 |
+
<Loader2 className="w-8 h-8 animate-spin mb-2" />
|
| 550 |
+
<span className="text-sm">Ищем ответы...</span>
|
| 551 |
+
</div>
|
| 552 |
+
) : searchResults?.results?.length > 0 ? (
|
| 553 |
+
<div className="space-y-4">
|
| 554 |
+
{searchResults.results.map((result: any, idx: number) => (
|
| 555 |
+
<motion.div
|
| 556 |
+
key={idx}
|
| 557 |
+
initial={{ opacity: 0, y: 10 }}
|
| 558 |
+
animate={{ opacity: 1, y: 0 }}
|
| 559 |
+
transition={{ delay: idx * 0.05 }}
|
| 560 |
+
className="group p-4 bg-white border border-slate-200 rounded-xl hover:border-indigo-300 hover:shadow-md transition-all relative overflow-hidden"
|
| 561 |
+
>
|
| 562 |
+
<div className="absolute left-0 top-0 bottom-0 w-1 bg-indigo-500 opacity-0 group-hover:opacity-100 transition-opacity" />
|
| 563 |
+
<p className="text-sm text-slate-700 leading-relaxed mb-3">{result.content}</p>
|
| 564 |
+
<div className="flex items-center justify-between text-xs">
|
| 565 |
+
<span className="font-bold text-indigo-600 bg-indigo-50 px-2 py-1 rounded-md">
|
| 566 |
+
{((result.similarity || 0) * 100).toFixed(0)}% совпадение
|
| 567 |
+
</span>
|
| 568 |
+
<span className="text-slate-400 font-medium uppercase tracking-wide">
|
| 569 |
+
{result.category || 'Общее'}
|
| 570 |
+
</span>
|
| 571 |
+
</div>
|
| 572 |
+
</motion.div>
|
| 573 |
+
))}
|
| 574 |
+
</div>
|
| 575 |
+
) : (
|
| 576 |
+
<div className="text-center py-12 bg-slate-50 rounded-xl border border-dashed border-slate-200">
|
| 577 |
+
<AlertCircle className="w-10 h-10 mx-auto text-slate-300 mb-3" />
|
| 578 |
+
<p className="text-slate-900 font-medium">Ничего не найдено</p>
|
| 579 |
+
<p className="text-sm text-slate-500">Попробуйте изменить запрос</p>
|
| 580 |
+
</div>
|
| 581 |
+
)}
|
| 582 |
+
</motion.div>
|
| 583 |
+
)}
|
| 584 |
+
</AnimatePresence>
|
| 585 |
+
</div>
|
| 586 |
+
</motion.div>
|
| 587 |
+
|
| 588 |
+
{/* Files List Column */}
|
| 589 |
+
<motion.div variants={item} className="bg-white rounded-2xl shadow-sm border border-slate-200 flex flex-col h-[600px]">
|
| 590 |
+
<div className="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50/50 rounded-t-2xl">
|
| 591 |
+
<h2 className="text-lg font-bold text-slate-900 flex items-center gap-2">
|
| 592 |
+
<FileText className="w-5 h-5 text-indigo-600" />
|
| 593 |
+
Список файлов
|
| 594 |
+
</h2>
|
| 595 |
+
<span className="text-xs font-bold bg-white border border-slate-200 px-2 py-1 rounded-md text-slate-600">
|
| 596 |
+
{knowledgeData?.count || 0}
|
| 597 |
+
</span>
|
| 598 |
+
</div>
|
| 599 |
+
|
| 600 |
+
<div className="flex-1 overflow-y-auto p-4 space-y-3 custom-scrollbar">
|
| 601 |
+
{knowledgeLoading ? (
|
| 602 |
+
<div className="flex items-center justify-center h-full text-slate-400">
|
| 603 |
+
<Loader2 className="w-8 h-8 animate-spin" />
|
| 604 |
+
</div>
|
| 605 |
+
) : knowledgeData?.entries?.length > 0 ? (
|
| 606 |
+
knowledgeData.entries.map((entry: any) => (
|
| 607 |
+
<motion.div
|
| 608 |
+
key={entry.id}
|
| 609 |
+
layout
|
| 610 |
+
initial={{ opacity: 0 }}
|
| 611 |
+
animate={{ opacity: 1 }}
|
| 612 |
+
className="group p-4 bg-white border border-slate-200 rounded-xl hover:border-indigo-300 hover:shadow-sm transition-all"
|
| 613 |
+
>
|
| 614 |
+
<div className="flex items-start gap-3">
|
| 615 |
+
<div className="p-2 bg-indigo-50 text-indigo-600 rounded-lg flex-shrink-0 group-hover:bg-indigo-100 transition-colors">
|
| 616 |
+
<FileText className="w-5 h-5" />
|
| 617 |
+
</div>
|
| 618 |
+
<div className="flex-1 min-w-0">
|
| 619 |
+
<div className="flex items-center gap-2 mb-1">
|
| 620 |
+
<span className="text-xs font-bold text-indigo-600 uppercase tracking-wide bg-indigo-50 px-1.5 py-0.5 rounded">
|
| 621 |
+
{entry.category || 'DOC'}
|
| 622 |
+
</span>
|
| 623 |
+
<span className="text-[10px] text-slate-400">
|
| 624 |
+
{new Date(entry.created_at).toLocaleDateString()}
|
| 625 |
+
</span>
|
| 626 |
+
</div>
|
| 627 |
+
<p className="text-sm text-slate-700 line-clamp-2 leading-relaxed mb-2">
|
| 628 |
+
{entry.content}
|
| 629 |
+
</p>
|
| 630 |
+
<div className="flex items-center justify-between">
|
| 631 |
+
<span className="text-xs text-slate-500 font-medium bg-slate-50 px-2 py-1 rounded border border-slate-100">
|
| 632 |
+
{entry.source_type}
|
| 633 |
+
</span>
|
| 634 |
+
<button
|
| 635 |
+
onClick={() => deleteMutation.mutate(entry.id)}
|
| 636 |
+
className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors opacity-0 group-hover:opacity-100"
|
| 637 |
+
title="Удалить"
|
| 638 |
+
>
|
| 639 |
+
<Trash2 className="w-4 h-4" />
|
| 640 |
+
</button>
|
| 641 |
+
</div>
|
| 642 |
+
</div>
|
| 643 |
+
</div>
|
| 644 |
+
</motion.div>
|
| 645 |
+
))
|
| 646 |
+
) : (
|
| 647 |
+
<div className="flex flex-col items-center justify-center h-full text-center p-8">
|
| 648 |
+
<div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mb-4">
|
| 649 |
+
<FileText className="w-8 h-8 text-slate-300" />
|
| 650 |
+
</div>
|
| 651 |
+
<h3 className="font-bold text-slate-900 mb-1">Пусто</h3>
|
| 652 |
+
<p className="text-sm text-slate-500">Загрузите файлы, чтобы наполнить базу знаний</p>
|
| 653 |
+
</div>
|
| 654 |
+
)}
|
| 655 |
+
</div>
|
| 656 |
+
</motion.div>
|
| 657 |
+
</div>
|
| 658 |
+
</motion.div>
|
| 659 |
+
)}
|
| 660 |
+
|
| 661 |
{activeTab === 'persona' && (
|
| 662 |
<motion.div
|
| 663 |
variants={container}
|
frontend/components/Sidebar.tsx
CHANGED
|
@@ -75,25 +75,25 @@ export function Sidebar() {
|
|
| 75 |
initial="hidden"
|
| 76 |
animate="visible"
|
| 77 |
variants={sidebarVariants}
|
| 78 |
-
className="w-72 bg-[#
|
| 79 |
>
|
| 80 |
{/* Background Glow Effect - Removed for better visibility */}
|
| 81 |
|
| 82 |
{/* Logo Section */}
|
| 83 |
-
<div className="p-6 border-b border-
|
| 84 |
<div className="flex items-center justify-between gap-2">
|
| 85 |
<Link href="/dashboard" className="flex items-center gap-3 group flex-1">
|
| 86 |
<div className="relative">
|
| 87 |
<div className="absolute inset-0 bg-indigo-500/20 blur-xl rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
|
| 88 |
-
<div className="w-10 h-10 rounded-xl flex items-center justify-center relative z-10 group-hover:scale-105 transition-transform duration-300 overflow-hidden">
|
| 89 |
-
<img src="/logo-v2.png" alt="MicroFunnel Logo" className="w-full h-full object-contain" />
|
| 90 |
</div>
|
| 91 |
</div>
|
| 92 |
<div>
|
| 93 |
-
<h1 className="text-lg font-
|
| 94 |
MicroFunnel
|
| 95 |
</h1>
|
| 96 |
-
<p className="text-[10px] text-
|
| 97 |
</div>
|
| 98 |
</Link>
|
| 99 |
|
|
@@ -106,17 +106,17 @@ export function Sidebar() {
|
|
| 106 |
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10">
|
| 107 |
{[1, 2, 3].map((i) => (
|
| 108 |
<div key={i}>
|
| 109 |
-
<div className="h-3 w-20 bg-
|
| 110 |
<div className="space-y-2">
|
| 111 |
{[1, 2, 3].map((j) => (
|
| 112 |
-
<div key={j} className="h-10 w-full bg-
|
| 113 |
))}
|
| 114 |
</div>
|
| 115 |
</div>
|
| 116 |
))}
|
| 117 |
</nav>
|
| 118 |
) : (
|
| 119 |
-
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10 scrollbar-thin scrollbar-thumb-
|
| 120 |
|
| 121 |
{/* Main Navigation */}
|
| 122 |
<motion.div
|
|
@@ -124,68 +124,54 @@ export function Sidebar() {
|
|
| 124 |
animate="visible"
|
| 125 |
variants={itemVariants}
|
| 126 |
>
|
| 127 |
-
<p className="px-4 text-
|
| 128 |
-
|
| 129 |
</p>
|
| 130 |
<div className="space-y-1">
|
| 131 |
{/* Admin Link - Only for Superusers */}
|
| 132 |
{(user?.is_superuser || user?.role === 'admin') && (
|
| 133 |
<Link href="/admin" className={cn(
|
| 134 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 135 |
isActive('/admin')
|
| 136 |
-
? "text-white bg-
|
| 137 |
-
: "text-red-
|
| 138 |
)}>
|
| 139 |
-
{isActive('/admin')
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
className="absolute inset-0 bg-gradient-to-r from-red-600 to-red-500 rounded-xl -z-10"
|
| 143 |
-
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
| 144 |
-
/>
|
| 145 |
-
)}
|
| 146 |
-
<Shield className={cn("w-5 h-5 transition-colors", isActive('/admin') ? "text-white" : "text-red-400 group-hover:text-red-200")} />
|
| 147 |
-
<span>Admin Panel</span>
|
| 148 |
-
{isActive('/admin') && <div className="ml-auto w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
|
| 149 |
</Link>
|
| 150 |
)}
|
| 151 |
|
| 152 |
<Link href="/dashboard" className={cn(
|
| 153 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 154 |
isActive('/dashboard')
|
| 155 |
-
? "text-white bg-indigo-
|
| 156 |
-
: "text-
|
| 157 |
)}>
|
| 158 |
-
{isActive('/dashboard')
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
className="absolute inset-0 bg-indigo-600 rounded-xl -z-10"
|
| 162 |
-
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
| 163 |
-
/>
|
| 164 |
-
)}
|
| 165 |
-
<LayoutDashboard className={cn("w-5 h-5 transition-colors", isActive('/dashboard') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
|
| 166 |
-
<span>Дашборд</span>
|
| 167 |
-
{isActive('/dashboard') && <div className="ml-auto w-1.5 h-1.5 rounded-full bg-white animate-pulse" />}
|
| 168 |
</Link>
|
| 169 |
|
| 170 |
<Link href="/chats" className={cn(
|
| 171 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 172 |
isActive('/chats')
|
| 173 |
-
? "text-white bg-indigo-
|
| 174 |
-
: "text-
|
| 175 |
)}>
|
| 176 |
-
<MessageSquare className={cn("w-
|
| 177 |
-
<span>
|
| 178 |
{/* Badge for unread messages could go here */}
|
| 179 |
</Link>
|
| 180 |
|
| 181 |
<Link href="/appointments" className={cn(
|
| 182 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 183 |
isActive('/appointments')
|
| 184 |
-
? "text-white bg-indigo-
|
| 185 |
-
: "text-
|
| 186 |
)}>
|
| 187 |
-
<Calendar className={cn("w-
|
| 188 |
-
<span>
|
| 189 |
</Link>
|
| 190 |
|
| 191 |
|
|
@@ -198,28 +184,20 @@ export function Sidebar() {
|
|
| 198 |
animate="visible"
|
| 199 |
variants={itemVariants}
|
| 200 |
>
|
| 201 |
-
<p className="px-4 text-
|
| 202 |
-
|
| 203 |
</p>
|
| 204 |
<div className="space-y-1">
|
| 205 |
-
|
| 206 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 group relative",
|
| 207 |
-
isActive('/knowledge')
|
| 208 |
-
? "text-white bg-indigo-600 shadow-lg shadow-indigo-900/20"
|
| 209 |
-
: "text-white/80 hover:text-white hover:bg-white/5"
|
| 210 |
-
)}>
|
| 211 |
-
<Brain className={cn("w-5 h-5 transition-colors", isActive('/knowledge') ? "text-white" : "text-white/70 group-hover:text-indigo-400")} />
|
| 212 |
-
<span>База Знаний</span>
|
| 213 |
-
</Link>
|
| 214 |
|
| 215 |
<Link href="/channels" className={cn(
|
| 216 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 217 |
isActive('/channels')
|
| 218 |
-
? "text-white bg-indigo-
|
| 219 |
-
: "text-
|
| 220 |
)}>
|
| 221 |
-
<Plug className={cn("w-
|
| 222 |
-
<span>
|
| 223 |
</Link>
|
| 224 |
</div>
|
| 225 |
</motion.div>
|
|
@@ -230,80 +208,80 @@ export function Sidebar() {
|
|
| 230 |
animate="visible"
|
| 231 |
variants={itemVariants}
|
| 232 |
>
|
| 233 |
-
<p className="px-4 text-
|
| 234 |
-
|
| 235 |
</p>
|
| 236 |
<div className="space-y-1">
|
| 237 |
<Link href="/settings/brain" className={cn(
|
| 238 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 239 |
isActive('/settings/brain')
|
| 240 |
-
? "text-white bg-indigo-
|
| 241 |
-
: "text-
|
| 242 |
)}>
|
| 243 |
-
<Sparkles className={cn("w-
|
| 244 |
-
<span>
|
| 245 |
</Link>
|
| 246 |
|
| 247 |
<Link href="/settings/crm" className={cn(
|
| 248 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 249 |
isActive('/settings/crm')
|
| 250 |
-
? "text-white bg-indigo-
|
| 251 |
-
: "text-
|
| 252 |
)}>
|
| 253 |
-
<Database className={cn("w-
|
| 254 |
-
<span>CRM
|
| 255 |
</Link>
|
| 256 |
|
| 257 |
<Link href="/settings/playbook" className={cn(
|
| 258 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 259 |
isActive('/settings/playbook')
|
| 260 |
-
? "text-white bg-indigo-
|
| 261 |
-
: "text-
|
| 262 |
)}>
|
| 263 |
-
<Target className={cn("w-
|
| 264 |
-
<span>
|
| 265 |
</Link>
|
| 266 |
|
| 267 |
<Link href="/settings/team" className={cn(
|
| 268 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 269 |
isActive('/settings/team')
|
| 270 |
-
? "text-white bg-indigo-
|
| 271 |
-
: "text-
|
| 272 |
)}>
|
| 273 |
-
<Users className={cn("w-
|
| 274 |
-
<span>
|
| 275 |
</Link>
|
| 276 |
|
| 277 |
<Link href="/settings/notifications" className={cn(
|
| 278 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 279 |
isActive('/settings/notifications')
|
| 280 |
-
? "text-white bg-indigo-
|
| 281 |
-
: "text-
|
| 282 |
)}>
|
| 283 |
-
<Bell className={cn("w-
|
| 284 |
-
<span>
|
| 285 |
</Link>
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
<Link href="/settings/billing" className={cn(
|
| 290 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 291 |
isActive('/settings/billing')
|
| 292 |
-
? "text-white bg-indigo-
|
| 293 |
-
: "text-
|
| 294 |
)}>
|
| 295 |
-
<DollarSign className={cn("w-
|
| 296 |
-
<span>
|
| 297 |
</Link>
|
| 298 |
|
| 299 |
<Link href="/settings/account" className={cn(
|
| 300 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-
|
| 301 |
isActive('/settings/account')
|
| 302 |
-
? "text-white bg-indigo-
|
| 303 |
-
: "text-
|
| 304 |
)}>
|
| 305 |
-
<User className={cn("w-
|
| 306 |
-
<span>
|
| 307 |
</Link>
|
| 308 |
</div>
|
| 309 |
</motion.div>
|
|
@@ -311,20 +289,20 @@ export function Sidebar() {
|
|
| 311 |
)}
|
| 312 |
|
| 313 |
{/* Bottom Section */}
|
| 314 |
-
<div className="p-4 border-t border-
|
| 315 |
{/* Partner Program Link */}
|
| 316 |
<Link href="/partners" className="block mb-4 group">
|
| 317 |
-
<div className="relative overflow-hidden rounded-
|
| 318 |
<div className="absolute inset-0 bg-gradient-to-r from-indigo-500/10 to-purple-500/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
|
| 319 |
<div className="flex items-center gap-3 relative z-10">
|
| 320 |
-
<div className="w-8 h-8 rounded
|
| 321 |
<Zap className="w-4 h-4" />
|
| 322 |
</div>
|
| 323 |
<div>
|
| 324 |
-
<p className="text-xs font-bold text-indigo-100 group-hover:text-white transition-colors">
|
| 325 |
-
<p className="text-[10px] text-indigo-
|
| 326 |
</div>
|
| 327 |
-
<ChevronRight className="w-
|
| 328 |
</div>
|
| 329 |
</div>
|
| 330 |
</Link>
|
|
@@ -332,32 +310,32 @@ export function Sidebar() {
|
|
| 332 |
{/* User Profile */}
|
| 333 |
<div className="flex items-center gap-3 px-2">
|
| 334 |
<div className={cn(
|
| 335 |
-
"w-
|
| 336 |
getAvatarColor(user?.email)
|
| 337 |
)}>
|
| 338 |
{getInitials(user?.full_name, user?.email)}
|
| 339 |
</div>
|
| 340 |
<div className="flex-1 min-w-0">
|
| 341 |
<p className="text-sm font-medium text-white truncate">
|
| 342 |
-
{user?.full_name || '
|
| 343 |
</p>
|
| 344 |
<div className="flex items-center gap-2">
|
| 345 |
-
<span className="text-
|
| 346 |
{user?.email}
|
| 347 |
</span>
|
| 348 |
{user?.role === 'admin' && (
|
| 349 |
-
<span className="px-1
|
| 350 |
-
|
| 351 |
</span>
|
| 352 |
)}
|
| 353 |
</div>
|
| 354 |
</div>
|
| 355 |
<button
|
| 356 |
onClick={() => logout()}
|
| 357 |
-
className="p-
|
| 358 |
-
title="
|
| 359 |
>
|
| 360 |
-
<LogOut className="w-
|
| 361 |
</button>
|
| 362 |
</div>
|
| 363 |
</div>
|
|
|
|
| 75 |
initial="hidden"
|
| 76 |
animate="visible"
|
| 77 |
variants={sidebarVariants}
|
| 78 |
+
className="w-72 bg-[#020005] border-r border-white/10 flex flex-col font-['Inter'] relative shrink-0 h-screen sticky top-0"
|
| 79 |
>
|
| 80 |
{/* Background Glow Effect - Removed for better visibility */}
|
| 81 |
|
| 82 |
{/* Logo Section */}
|
| 83 |
+
<div className="p-6 border-b border-white/10 relative z-50">
|
| 84 |
<div className="flex items-center justify-between gap-2">
|
| 85 |
<Link href="/dashboard" className="flex items-center gap-3 group flex-1">
|
| 86 |
<div className="relative">
|
| 87 |
<div className="absolute inset-0 bg-indigo-500/20 blur-xl rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
|
| 88 |
+
<div className="w-10 h-10 rounded-xl flex items-center justify-center relative z-10 group-hover:scale-105 transition-transform duration-300 overflow-hidden bg-white/5 border border-white/10">
|
| 89 |
+
<img src="/logo-v2.png" alt="MicroFunnel Logo" className="w-full h-full object-contain p-1" />
|
| 90 |
</div>
|
| 91 |
</div>
|
| 92 |
<div>
|
| 93 |
+
<h1 className="text-lg font-black text-white tracking-widest group-hover:text-indigo-400 transition-colors uppercase">
|
| 94 |
MicroFunnel
|
| 95 |
</h1>
|
| 96 |
+
<p className="text-[10px] text-indigo-400 font-mono font-medium uppercase tracking-wider">System v2.0</p>
|
| 97 |
</div>
|
| 98 |
</Link>
|
| 99 |
|
|
|
|
| 106 |
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10">
|
| 107 |
{[1, 2, 3].map((i) => (
|
| 108 |
<div key={i}>
|
| 109 |
+
<div className="h-3 w-20 bg-white/10 rounded mb-3 animate-pulse" />
|
| 110 |
<div className="space-y-2">
|
| 111 |
{[1, 2, 3].map((j) => (
|
| 112 |
+
<div key={j} className="h-10 w-full bg-white/5 rounded-lg animate-pulse" />
|
| 113 |
))}
|
| 114 |
</div>
|
| 115 |
</div>
|
| 116 |
))}
|
| 117 |
</nav>
|
| 118 |
) : (
|
| 119 |
+
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10 scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent">
|
| 120 |
|
| 121 |
{/* Main Navigation */}
|
| 122 |
<motion.div
|
|
|
|
| 124 |
animate="visible"
|
| 125 |
variants={itemVariants}
|
| 126 |
>
|
| 127 |
+
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 128 |
+
/ MAIN_TERMINAL
|
| 129 |
</p>
|
| 130 |
<div className="space-y-1">
|
| 131 |
{/* Admin Link - Only for Superusers */}
|
| 132 |
{(user?.is_superuser || user?.role === 'admin') && (
|
| 133 |
<Link href="/admin" className={cn(
|
| 134 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-bold transition-all duration-200 group relative mb-2 border",
|
| 135 |
isActive('/admin')
|
| 136 |
+
? "text-white bg-red-500/10 border-red-500/50 shadow-[0_0_15px_-3px_rgba(220,38,38,0.3)]"
|
| 137 |
+
: "text-red-400 border-transparent hover:bg-red-500/5 hover:border-red-500/20"
|
| 138 |
)}>
|
| 139 |
+
<Shield className={cn("w-4 h-4 transition-colors", isActive('/admin') ? "text-red-500" : "text-red-400")} />
|
| 140 |
+
<span className="font-mono">ADMIN_ACCESS</span>
|
| 141 |
+
{isActive('/admin') && <div className="ml-auto w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
</Link>
|
| 143 |
)}
|
| 144 |
|
| 145 |
<Link href="/dashboard" className={cn(
|
| 146 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative overflow-hidden border",
|
| 147 |
isActive('/dashboard')
|
| 148 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 149 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 150 |
)}>
|
| 151 |
+
<LayoutDashboard className={cn("w-4 h-4 transition-colors", isActive('/dashboard') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 152 |
+
<span>Dashboard</span>
|
| 153 |
+
{isActive('/dashboard') && <div className="ml-auto w-1.5 h-1.5 rounded-full bg-indigo-500 animate-pulse" />}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
</Link>
|
| 155 |
|
| 156 |
<Link href="/chats" className={cn(
|
| 157 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 158 |
isActive('/chats')
|
| 159 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 160 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 161 |
)}>
|
| 162 |
+
<MessageSquare className={cn("w-4 h-4 transition-colors", isActive('/chats') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 163 |
+
<span>Live Chats</span>
|
| 164 |
{/* Badge for unread messages could go here */}
|
| 165 |
</Link>
|
| 166 |
|
| 167 |
<Link href="/appointments" className={cn(
|
| 168 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 169 |
isActive('/appointments')
|
| 170 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 171 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 172 |
)}>
|
| 173 |
+
<Calendar className={cn("w-4 h-4 transition-colors", isActive('/appointments') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 174 |
+
<span>Calendar</span>
|
| 175 |
</Link>
|
| 176 |
|
| 177 |
|
|
|
|
| 184 |
animate="visible"
|
| 185 |
variants={itemVariants}
|
| 186 |
>
|
| 187 |
+
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 188 |
+
/ NEURAL_NET
|
| 189 |
</p>
|
| 190 |
<div className="space-y-1">
|
| 191 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
<Link href="/channels" className={cn(
|
| 194 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 195 |
isActive('/channels')
|
| 196 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 197 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 198 |
)}>
|
| 199 |
+
<Plug className={cn("w-4 h-4 transition-colors", isActive('/channels') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 200 |
+
<span>Connections</span>
|
| 201 |
</Link>
|
| 202 |
</div>
|
| 203 |
</motion.div>
|
|
|
|
| 208 |
animate="visible"
|
| 209 |
variants={itemVariants}
|
| 210 |
>
|
| 211 |
+
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 212 |
+
/ SYSTEM_CONFIG
|
| 213 |
</p>
|
| 214 |
<div className="space-y-1">
|
| 215 |
<Link href="/settings/brain" className={cn(
|
| 216 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 217 |
isActive('/settings/brain')
|
| 218 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 219 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 220 |
)}>
|
| 221 |
+
<Sparkles className={cn("w-4 h-4 transition-colors", isActive('/settings/brain') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 222 |
+
<span>AI Brain</span>
|
| 223 |
</Link>
|
| 224 |
|
| 225 |
<Link href="/settings/crm" className={cn(
|
| 226 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 227 |
isActive('/settings/crm')
|
| 228 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 229 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 230 |
)}>
|
| 231 |
+
<Database className={cn("w-4 h-4 transition-colors", isActive('/settings/crm') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 232 |
+
<span>CRM Sync</span>
|
| 233 |
</Link>
|
| 234 |
|
| 235 |
<Link href="/settings/playbook" className={cn(
|
| 236 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 237 |
isActive('/settings/playbook')
|
| 238 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 239 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 240 |
)}>
|
| 241 |
+
<Target className={cn("w-4 h-4 transition-colors", isActive('/settings/playbook') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 242 |
+
<span>Sales Scripts</span>
|
| 243 |
</Link>
|
| 244 |
|
| 245 |
<Link href="/settings/team" className={cn(
|
| 246 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 247 |
isActive('/settings/team')
|
| 248 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 249 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 250 |
)}>
|
| 251 |
+
<Users className={cn("w-4 h-4 transition-colors", isActive('/settings/team') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 252 |
+
<span>Team</span>
|
| 253 |
</Link>
|
| 254 |
|
| 255 |
<Link href="/settings/notifications" className={cn(
|
| 256 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 257 |
isActive('/settings/notifications')
|
| 258 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 259 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 260 |
)}>
|
| 261 |
+
<Bell className={cn("w-4 h-4 transition-colors", isActive('/settings/notifications') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 262 |
+
<span>Alerts</span>
|
| 263 |
</Link>
|
| 264 |
|
| 265 |
|
| 266 |
|
| 267 |
<Link href="/settings/billing" className={cn(
|
| 268 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 269 |
isActive('/settings/billing')
|
| 270 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 271 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 272 |
)}>
|
| 273 |
+
<DollarSign className={cn("w-4 h-4 transition-colors", isActive('/settings/billing') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 274 |
+
<span>Billing</span>
|
| 275 |
</Link>
|
| 276 |
|
| 277 |
<Link href="/settings/account" className={cn(
|
| 278 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 279 |
isActive('/settings/account')
|
| 280 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 281 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 282 |
)}>
|
| 283 |
+
<User className={cn("w-4 h-4 transition-colors", isActive('/settings/account') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 284 |
+
<span>Profile</span>
|
| 285 |
</Link>
|
| 286 |
</div>
|
| 287 |
</motion.div>
|
|
|
|
| 289 |
)}
|
| 290 |
|
| 291 |
{/* Bottom Section */}
|
| 292 |
+
<div className="p-4 border-t border-white/10 bg-[#020005] relative z-10">
|
| 293 |
{/* Partner Program Link */}
|
| 294 |
<Link href="/partners" className="block mb-4 group">
|
| 295 |
+
<div className="relative overflow-hidden rounded-lg bg-indigo-900/10 border border-indigo-500/30 p-3 transition-all duration-300 hover:border-indigo-500/60 hover:shadow-[0_0_15px_-3px_rgba(99,102,241,0.2)]">
|
| 296 |
<div className="absolute inset-0 bg-gradient-to-r from-indigo-500/10 to-purple-500/10 opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
|
| 297 |
<div className="flex items-center gap-3 relative z-10">
|
| 298 |
+
<div className="w-8 h-8 rounded bg-indigo-500/10 flex items-center justify-center text-indigo-400 group-hover:text-white group-hover:scale-110 transition-all duration-300 border border-indigo-500/20">
|
| 299 |
<Zap className="w-4 h-4" />
|
| 300 |
</div>
|
| 301 |
<div>
|
| 302 |
+
<p className="text-xs font-bold text-indigo-100 group-hover:text-white transition-colors">Affiliate Program</p>
|
| 303 |
+
<p className="text-[10px] text-indigo-400 font-mono">EARN 50%</p>
|
| 304 |
</div>
|
| 305 |
+
<ChevronRight className="w-3 h-3 text-indigo-500/50 ml-auto group-hover:translate-x-1 transition-transform" />
|
| 306 |
</div>
|
| 307 |
</div>
|
| 308 |
</Link>
|
|
|
|
| 310 |
{/* User Profile */}
|
| 311 |
<div className="flex items-center gap-3 px-2">
|
| 312 |
<div className={cn(
|
| 313 |
+
"w-8 h-8 rounded flex items-center justify-center text-white font-bold text-xs shadow-lg border border-white/10",
|
| 314 |
getAvatarColor(user?.email)
|
| 315 |
)}>
|
| 316 |
{getInitials(user?.full_name, user?.email)}
|
| 317 |
</div>
|
| 318 |
<div className="flex-1 min-w-0">
|
| 319 |
<p className="text-sm font-medium text-white truncate">
|
| 320 |
+
{user?.full_name || 'User'}
|
| 321 |
</p>
|
| 322 |
<div className="flex items-center gap-2">
|
| 323 |
+
<span className="text-[10px] text-slate-500 truncate max-w-[80px] font-mono">
|
| 324 |
{user?.email}
|
| 325 |
</span>
|
| 326 |
{user?.role === 'admin' && (
|
| 327 |
+
<span className="px-1 py-0.5 rounded bg-red-500/20 text-[8px] font-bold text-red-400 border border-red-500/30">
|
| 328 |
+
SU
|
| 329 |
</span>
|
| 330 |
)}
|
| 331 |
</div>
|
| 332 |
</div>
|
| 333 |
<button
|
| 334 |
onClick={() => logout()}
|
| 335 |
+
className="p-1.5 text-slate-500 hover:text-red-400 hover:bg-red-500/10 rounded transition-colors"
|
| 336 |
+
title="Logout"
|
| 337 |
>
|
| 338 |
+
<LogOut className="w-3.5 h-3.5" />
|
| 339 |
</button>
|
| 340 |
</div>
|
| 341 |
</div>
|
frontend/components/Voice/LiveConversation.tsx
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import React, { useEffect, useState } from 'react';
|
| 2 |
+
import { useAudioStream } from '@/hooks/useAudioStream';
|
| 3 |
+
import { Mic, Phone, PhoneOff, Activity } from 'lucide-react';
|
| 4 |
+
import { cn } from '@/lib/utils'; // Assuming UI utils exist or simple class join
|
| 5 |
+
|
| 6 |
+
export const LiveConversation = ({ token }: { token: string }) => {
|
| 7 |
+
const {
|
| 8 |
+
isConnected,
|
| 9 |
+
isRecording,
|
| 10 |
+
isSpeaking,
|
| 11 |
+
status,
|
| 12 |
+
connect,
|
| 13 |
+
startRecording,
|
| 14 |
+
stopRecording
|
| 15 |
+
} = useAudioStream(token, "ws://localhost:8000");
|
| 16 |
+
|
| 17 |
+
const [hasInteracted, setHasInteracted] = useState(false);
|
| 18 |
+
|
| 19 |
+
useEffect(() => {
|
| 20 |
+
// Auto-connect if token provided
|
| 21 |
+
if (token && !isConnected && !hasInteracted) {
|
| 22 |
+
// Wait for user interaction first actually?
|
| 23 |
+
// Browsers block AudioContext if no interaction.
|
| 24 |
+
}
|
| 25 |
+
}, [token]);
|
| 26 |
+
|
| 27 |
+
const handleStart = () => {
|
| 28 |
+
setHasInteracted(true);
|
| 29 |
+
connect();
|
| 30 |
+
// Allow brief delay for connection then start mic?
|
| 31 |
+
// Better to let user click "Start Call"
|
| 32 |
+
};
|
| 33 |
+
|
| 34 |
+
const toggleMic = () => {
|
| 35 |
+
if (isRecording) {
|
| 36 |
+
stopRecording();
|
| 37 |
+
} else {
|
| 38 |
+
startRecording();
|
| 39 |
+
}
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
return (
|
| 43 |
+
<div className="flex flex-col items-center justify-center min-h-[600px] w-full bg-black/90 relative overflow-hidden rounded-3xl border border-white/10">
|
| 44 |
+
{/* Background Effects */}
|
| 45 |
+
<div className="absolute inset-0 bg-gradient-to-b from-blue-900/20 to-purple-900/20 pointer-events-none" />
|
| 46 |
+
|
| 47 |
+
{/* Status Header */}
|
| 48 |
+
<div className="absolute top-8 flex items-center gap-2 px-4 py-2 bg-white/5 rounded-full border border-white/10 backdrop-blur-md">
|
| 49 |
+
<div className={cn("w-2 h-2 rounded-full", isConnected ? "bg-green-500 animate-pulse" : "bg-red-500")} />
|
| 50 |
+
<span className="text-sm font-medium text-white/80 uppercase tracking-widest text-[10px]">
|
| 51 |
+
{status}
|
| 52 |
+
</span>
|
| 53 |
+
</div>
|
| 54 |
+
|
| 55 |
+
{/* NEBULA ORB VISUALIZATION */}
|
| 56 |
+
<div className="relative group cursor-pointer" onClick={toggleMic}>
|
| 57 |
+
{/* Core Orb */}
|
| 58 |
+
<div className={cn(
|
| 59 |
+
"w-48 h-48 rounded-full blur-xl transition-all duration-500",
|
| 60 |
+
isSpeaking ? "bg-purple-500/60 scale-125 animate-pulse" :
|
| 61 |
+
isRecording ? "bg-blue-500/40 scale-110" : "bg-gray-800/40 scale-100"
|
| 62 |
+
)} />
|
| 63 |
+
|
| 64 |
+
{/* Inner Core */}
|
| 65 |
+
<div className={cn(
|
| 66 |
+
"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 rounded-full border border-white/20 flex items-center justify-center transition-all duration-300 backdrop-blur-sm",
|
| 67 |
+
isSpeaking ? "bg-white/10 shadow-[0_0_50px_rgba(168,85,247,0.5)]" : "bg-black/40"
|
| 68 |
+
)}>
|
| 69 |
+
{isSpeaking ? (
|
| 70 |
+
<Activity className="w-12 h-12 text-white animate-bounce" />
|
| 71 |
+
) : (
|
| 72 |
+
<Mic className={cn("w-10 h-10 transition-colors", isRecording ? "text-blue-400" : "text-white/20")} />
|
| 73 |
+
)}
|
| 74 |
+
</div>
|
| 75 |
+
|
| 76 |
+
{/* Ripple Effect when Listening */}
|
| 77 |
+
{isRecording && !isSpeaking && (
|
| 78 |
+
<>
|
| 79 |
+
<div className="absolute inset-0 rounded-full border border-blue-500/30 animate-[ping_2s_linear_infinite]" />
|
| 80 |
+
<div className="absolute inset-(-10px) rounded-full border border-blue-500/20 animate-[ping_2s_linear_infinite_0.5s]" />
|
| 81 |
+
</>
|
| 82 |
+
)}
|
| 83 |
+
</div>
|
| 84 |
+
|
| 85 |
+
{/* Controls */}
|
| 86 |
+
<div className="absolute bottom-12 flex gap-6">
|
| 87 |
+
{!isConnected ? (
|
| 88 |
+
<button
|
| 89 |
+
onClick={handleStart}
|
| 90 |
+
className="flex items-center gap-2 px-8 py-4 bg-green-600 hover:bg-green-500 text-white rounded-full font-bold uppercase tracking-wider transition-all shadow-[0_0_30px_rgba(34,197,94,0.3)] hover:shadow-[0_0_50px_rgba(34,197,94,0.6)]"
|
| 91 |
+
>
|
| 92 |
+
<Phone className="w-5 h-5" />
|
| 93 |
+
Start Call
|
| 94 |
+
</button>
|
| 95 |
+
) : (
|
| 96 |
+
<div className="flex gap-4">
|
| 97 |
+
<button
|
| 98 |
+
onClick={toggleMic}
|
| 99 |
+
className={cn(
|
| 100 |
+
"p-4 rounded-full border transition-all",
|
| 101 |
+
isRecording ? "bg-white text-black border-white" : "bg-transparent text-white border-white/20 hover:bg-white/10"
|
| 102 |
+
)}
|
| 103 |
+
>
|
| 104 |
+
<Mic className="w-6 h-6" />
|
| 105 |
+
</button>
|
| 106 |
+
<button
|
| 107 |
+
onClick={() => window.location.reload()} // Disconnect hack for now
|
| 108 |
+
className="p-4 rounded-full bg-red-500/20 text-red-400 border border-red-500/50 hover:bg-red-500 hover:text-white transition-all"
|
| 109 |
+
>
|
| 110 |
+
<PhoneOff className="w-6 h-6" />
|
| 111 |
+
</button>
|
| 112 |
+
</div>
|
| 113 |
+
)}
|
| 114 |
+
</div>
|
| 115 |
+
|
| 116 |
+
<div className="absolute bottom-4 text-xs text-white/30">
|
| 117 |
+
MicroFunnel Voice Engine v1.0 • Low Latency
|
| 118 |
+
</div>
|
| 119 |
+
</div>
|
| 120 |
+
);
|
| 121 |
+
};
|
frontend/hooks/useAudioStream.ts
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useRef, useState, useEffect } from 'react';
|
| 2 |
+
|
| 3 |
+
// Configuration
|
| 4 |
+
const SAMPLE_RATE = 24000; // Match OpenAI/Standard
|
| 5 |
+
const CHUNK_SIZE = 4096;
|
| 6 |
+
|
| 7 |
+
export const useAudioStream = (token: string, backendUrl: string = 'ws://localhost:8000') => {
|
| 8 |
+
const [isConnected, setIsConnected] = useState(false);
|
| 9 |
+
const [isRecording, setIsRecording] = useState(false);
|
| 10 |
+
const [isSpeaking, setIsSpeaking] = useState(false); // AI is speaking
|
| 11 |
+
const [status, setStatus] = useState<string>('disconnected');
|
| 12 |
+
|
| 13 |
+
// Refs
|
| 14 |
+
const socketRef = useRef<WebSocket | null>(null);
|
| 15 |
+
const audioContextRef = useRef<AudioContext | null>(null);
|
| 16 |
+
const processorRef = useRef<ScriptProcessorNode | null>(null); // Deprecated but works everywhere. Use AudioWorklet for prod.
|
| 17 |
+
const inputRef = useRef<MediaStreamAudioSourceNode | null>(null);
|
| 18 |
+
const audioQueueRef = useRef<Blob[]>([]);
|
| 19 |
+
const isPlayingRef = useRef(false);
|
| 20 |
+
const nextPlayTimeRef = useRef(0);
|
| 21 |
+
|
| 22 |
+
// Initial Connection
|
| 23 |
+
const connect = () => {
|
| 24 |
+
if (!token) return;
|
| 25 |
+
const wsUrl = `${backendUrl}/ws/voice/stream?token=${token}`;
|
| 26 |
+
const ws = new WebSocket(wsUrl);
|
| 27 |
+
|
| 28 |
+
ws.onopen = () => {
|
| 29 |
+
setIsConnected(true);
|
| 30 |
+
setStatus('connected');
|
| 31 |
+
};
|
| 32 |
+
|
| 33 |
+
ws.onclose = () => {
|
| 34 |
+
setIsConnected(false);
|
| 35 |
+
setStatus('disconnected');
|
| 36 |
+
};
|
| 37 |
+
|
| 38 |
+
ws.onmessage = async (event) => {
|
| 39 |
+
const data = event.data;
|
| 40 |
+
|
| 41 |
+
if (data instanceof Blob) {
|
| 42 |
+
// Received Audio
|
| 43 |
+
console.log("🔊 Received audio chunk:", data.size);
|
| 44 |
+
playAudioChunk(data);
|
| 45 |
+
} else {
|
| 46 |
+
// Assume JSON Control Message
|
| 47 |
+
try {
|
| 48 |
+
const msg = JSON.parse(data);
|
| 49 |
+
if (msg.status) {
|
| 50 |
+
setStatus(msg.status);
|
| 51 |
+
if (msg.status === 'speaking') setIsSpeaking(true);
|
| 52 |
+
if (msg.status === 'listening') setIsSpeaking(false);
|
| 53 |
+
}
|
| 54 |
+
} catch (e) {
|
| 55 |
+
console.error("WS Parse error", e);
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
};
|
| 59 |
+
|
| 60 |
+
socketRef.current = ws;
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
const startRecording = async () => {
|
| 64 |
+
if (!socketRef.current || socketRef.current.readyState !== WebSocket.OPEN) return;
|
| 65 |
+
|
| 66 |
+
try {
|
| 67 |
+
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
| 68 |
+
const ctx = new (window.AudioContext || (window as any).webkitAudioContext)({ sampleRate: SAMPLE_RATE });
|
| 69 |
+
audioContextRef.current = ctx;
|
| 70 |
+
|
| 71 |
+
const source = ctx.createMediaStreamSource(stream);
|
| 72 |
+
inputRef.current = source;
|
| 73 |
+
|
| 74 |
+
// Create Processor
|
| 75 |
+
// BufferSize: 4096 is good balance ~170ms latency
|
| 76 |
+
const processor = ctx.createScriptProcessor(4096, 1, 1);
|
| 77 |
+
processor.onaudioprocess = (e) => {
|
| 78 |
+
if (!isRecording) return;
|
| 79 |
+
|
| 80 |
+
const inputData = e.inputBuffer.getChannelData(0);
|
| 81 |
+
// Convert Float32 to Int16 for simple transport (or send Float32 and decode on server)
|
| 82 |
+
// For MVP: Send raw bytes or convert.
|
| 83 |
+
// Let's Convert to Int16 PCM to save bandwidth and match standard containers
|
| 84 |
+
const pcmData = floatTo16BitPCM(inputData);
|
| 85 |
+
|
| 86 |
+
if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
|
| 87 |
+
socketRef.current.send(pcmData);
|
| 88 |
+
}
|
| 89 |
+
};
|
| 90 |
+
|
| 91 |
+
source.connect(processor);
|
| 92 |
+
processor.connect(ctx.destination); // Need connection to destination for Chrome to fire
|
| 93 |
+
|
| 94 |
+
processorRef.current = processor;
|
| 95 |
+
setIsRecording(true);
|
| 96 |
+
setStatus('listening');
|
| 97 |
+
|
| 98 |
+
} catch (e) {
|
| 99 |
+
console.error("Mic Error:", e);
|
| 100 |
+
}
|
| 101 |
+
};
|
| 102 |
+
|
| 103 |
+
const stopRecording = () => {
|
| 104 |
+
if (processorRef.current) {
|
| 105 |
+
processorRef.current.disconnect();
|
| 106 |
+
processorRef.current = null;
|
| 107 |
+
}
|
| 108 |
+
if (inputRef.current) {
|
| 109 |
+
inputRef.current.disconnect();
|
| 110 |
+
inputRef.current = null;
|
| 111 |
+
}
|
| 112 |
+
if (audioContextRef.current) {
|
| 113 |
+
audioContextRef.current.close();
|
| 114 |
+
audioContextRef.current = null;
|
| 115 |
+
}
|
| 116 |
+
setIsRecording(false);
|
| 117 |
+
// Send commit signal
|
| 118 |
+
if (socketRef.current) {
|
| 119 |
+
socketRef.current.send(JSON.stringify({ type: "commit" }));
|
| 120 |
+
}
|
| 121 |
+
};
|
| 122 |
+
|
| 123 |
+
const playAudioChunk = async (blob: Blob) => {
|
| 124 |
+
// Use a shared AudioContext for playback
|
| 125 |
+
const ctx = new (window.AudioContext || (window as any).webkitAudioContext)();
|
| 126 |
+
|
| 127 |
+
const arrayBuffer = await blob.arrayBuffer();
|
| 128 |
+
const audioBuffer = await ctx.decodeAudioData(arrayBuffer);
|
| 129 |
+
|
| 130 |
+
const source = ctx.createBufferSource();
|
| 131 |
+
source.buffer = audioBuffer;
|
| 132 |
+
source.connect(ctx.destination);
|
| 133 |
+
source.start(0);
|
| 134 |
+
};
|
| 135 |
+
|
| 136 |
+
// Helper: Float32 to Int16
|
| 137 |
+
const floatTo16BitPCM = (output: Float32Array) => {
|
| 138 |
+
const offset = 0;
|
| 139 |
+
const buffer = new ArrayBuffer(output.length * 2);
|
| 140 |
+
const view = new DataView(buffer);
|
| 141 |
+
for (let i = 0; i < output.length; i++, offset += 2) {
|
| 142 |
+
let s = Math.max(-1, Math.min(1, output[i]));
|
| 143 |
+
view.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
|
| 144 |
+
}
|
| 145 |
+
return buffer;
|
| 146 |
+
};
|
| 147 |
+
|
| 148 |
+
return {
|
| 149 |
+
isConnected,
|
| 150 |
+
isRecording,
|
| 151 |
+
isSpeaking,
|
| 152 |
+
status,
|
| 153 |
+
connect,
|
| 154 |
+
startRecording,
|
| 155 |
+
stopRecording
|
| 156 |
+
};
|
| 157 |
+
};
|