Spaces:
Running

axeronis commited on
Commit
c56f47b
Β·
1 Parent(s): df4fd36

feat: Implement Order Agent and Admin Notifications

Browse files
backend/app/api/webhook.py CHANGED
@@ -529,6 +529,19 @@ async def process_ai_response_background(
529
 
530
  logger.info(f"πŸ“… AI Booked Appointment: {date_str} for Lead {lead_id}")
531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  # Remove tag from text
533
  ai_text = ai_text.replace(booking_match.group(0), "").strip()
534
  ai_text += "\n\nβœ… (БистСма: Π—Π°ΠΏΠΈΡΡŒ создана ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ!)"
@@ -541,6 +554,125 @@ async def process_ai_response_background(
541
  ai_response["text"] += "\n\n⚠️ (БистСма: Ошибка ΠΏΡ€ΠΈ сохранСнии записи. ΠœΠ΅Π½Π΅Π΄ΠΆΠ΅Ρ€ свяТСтся с Π²Π°ΠΌΠΈ.)"
542
  # --- BOOKING INTERCEPTION END ---
543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544
 
545
 
546
  ai_message = Message(
 
529
 
530
  logger.info(f"πŸ“… AI Booked Appointment: {date_str} for Lead {lead_id}")
531
 
532
+ # πŸ”” NOTIFY ADMIN
533
+ try:
534
+ from app.services.notification import notification_service
535
+ # We need to load relationship or ensure it's available.
536
+ # new_appt might not have 'lead' loaded yet.
537
+ # We pass the object, service handles it. Ideally refresh or pass ID.
538
+ # For speed, let's refresh or just pass what we have.
539
+ new_appt.lead = lead # Manually attach to avoid DB refetch
540
+ new_appt.service = default_srv
541
+ await notification_service.notify_new_appointment(tenant, new_appt)
542
+ except Exception as ns_err:
543
+ logger.error(f"⚠️ Notification failed: {ns_err}")
544
+
545
  # Remove tag from text
546
  ai_text = ai_text.replace(booking_match.group(0), "").strip()
547
  ai_text += "\n\nβœ… (БистСма: Π—Π°ΠΏΠΈΡΡŒ создана ΡƒΡΠΏΠ΅ΡˆΠ½ΠΎ!)"
 
554
  ai_response["text"] += "\n\n⚠️ (БистСма: Ошибка ΠΏΡ€ΠΈ сохранСнии записи. ΠœΠ΅Π½Π΅Π΄ΠΆΠ΅Ρ€ свяТСтся с Π²Π°ΠΌΠΈ.)"
555
  # --- BOOKING INTERCEPTION END ---
556
 
557
+ # --- ORDER INTERCEPTION START ---
558
+ import json
559
+ from app.models.order import Order, OrderItem, OrderStatus
560
+ from app.models.product import Product
561
+
562
+ order_match = re.search(r'\[CREATE_ORDER:\s*({.*?})\]', ai_text, re.DOTALL)
563
+
564
+ if order_match:
565
+ try:
566
+ json_str = order_match.group(1)
567
+ # Sanitize JSON if needed (AI might leave trailing commas)
568
+ # For now assume valid JSON from Gemini 1.5
569
+ order_data = json.loads(json_str)
570
+
571
+ logger.info(f"πŸ›’ Processing Order Request: {json_str}")
572
+
573
+ # 1. Create Order Shell
574
+ new_order = Order(
575
+ tenant_id=tenant_id,
576
+ lead_id=lead_id,
577
+ status=OrderStatus.NEW,
578
+ total_amount=0.0
579
+ )
580
+ session.add(new_order)
581
+ await session.flush() # Get ID
582
+
583
+ total_sum = 0.0
584
+ items_info_text = []
585
+ currency = "USD"
586
+
587
+ # 2. Process Items
588
+ for item in order_data.get("items", []):
589
+ p_name = item.get("product_name")
590
+ qty = int(item.get("quantity", 1))
591
+
592
+ # Find product (Best Effort Fuzzy Match)
593
+ # We use ILIKE for case-insensitive partial match
594
+ p_stmt = select(Product).where(
595
+ Product.tenant_id == tenant_id,
596
+ Product.name.ilike(f"%{p_name}%")
597
+ ).limit(1)
598
+ p_res = await session.execute(p_stmt)
599
+ product = p_res.scalar_one_or_none()
600
+
601
+ price = 0.0
602
+ p_id = None
603
+
604
+ if product:
605
+ price = product.price
606
+ p_id = product.id
607
+ currency = product.currency # Use last product's currency
608
+ else:
609
+ # Fallback if product not found by name
610
+ logger.warning(f"⚠️ Product '{p_name}' not found in DB")
611
+
612
+ line_total = price * qty
613
+ total_sum += line_total
614
+
615
+ order_item = OrderItem(
616
+ order_id=new_order.id,
617
+ product_id=p_id,
618
+ product_name=p_name,
619
+ quantity=qty,
620
+ unit_price=price,
621
+ total_price=line_total
622
+ )
623
+ session.add(order_item)
624
+ items_info_text.append(f"{p_name} x{qty}")
625
+
626
+ # 3. Update Order Total and Customer details if provided
627
+ new_order.total_amount = total_sum
628
+
629
+ customer_info = order_data.get("customer", {})
630
+ notes = order_data.get("notes", "")
631
+
632
+ # Update Lead info if missing using gathered data
633
+ if customer_info.get("name") and not lead.name:
634
+ lead.name = customer_info.get("name")
635
+ session.add(lead)
636
+
637
+ # Save order notes
638
+ if notes:
639
+ # You might want a 'notes' field in Order model, currently absent?
640
+ # I defined Order model earlier. Did I add notes?
641
+ # Let's check model definition. Assuming NO for now, log it.
642
+ logger.info(f"πŸ“ Order Notes: {notes}")
643
+
644
+ session.add(new_order)
645
+ await session.commit()
646
+
647
+ logger.info(f"βœ… AI Created Order {new_order.id} for Lead {lead_id}")
648
+
649
+ # 4. Clean up response & Add Confirmation
650
+ ai_text = ai_text.replace(order_match.group(0), "").strip()
651
+ confirmation_msg = f"\n\nβœ… Π—Π°ΠΊΠ°Π· β„–{str(new_order.id)[:8]} ΠΎΡ„ΠΎΡ€ΠΌΠ»Π΅Π½!\nπŸ“¦ Π’ΠΎΠ²Π°Ρ€Ρ‹: {', '.join(items_info_text)}\nπŸ’° Π˜Ρ‚ΠΎΠ³ΠΎ: {total_sum:.2f} {currency}"
652
+ ai_text += confirmation_msg
653
+
654
+ # Update response text object
655
+ ai_response["text"] = ai_text
656
+
657
+ # πŸ”” NOTIFY ADMIN
658
+ try:
659
+ from app.services.notification import notification_service
660
+ await notification_service.notify_new_order(tenant, new_order, '\n'.join(items_info_text))
661
+ except Exception as ns_err:
662
+ logger.error(f"⚠️ Notification failed: {ns_err}")
663
+
664
+ except Exception as e:
665
+ logger.error(f"❌ Failed to process AI Order tag: {e}")
666
+ import traceback
667
+ traceback.print_exc()
668
+ # Fallback message
669
+ # Don't fail the chat, just append error note
670
+ ai_text = ai_text.replace(order_match.group(0), "").strip()
671
+ ai_text += "\n\n⚠️ (БистСма: Заявка принята, Π½ΠΎ ΠΏΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° ошибка автоматичСской рСгистрации. ΠœΠ΅Π½Π΅Π΄ΠΆΠ΅Ρ€ ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΈΡ‚ Π²Ρ€ΡƒΡ‡Π½ΡƒΡŽ.)"
672
+ ai_response["text"] = ai_text
673
+
674
+ # --- ORDER INTERCEPTION END ---
675
+
676
 
677
 
678
  ai_message = Message(
backend/app/models/lead.py CHANGED
@@ -102,6 +102,7 @@ class Lead(SQLModel, table=True):
102
  tenant: Optional["Tenant"] = Relationship(back_populates="leads")
103
  conversations: List["Conversation"] = Relationship(back_populates="lead")
104
  appointments: List["Appointment"] = Relationship(back_populates="lead")
 
105
 
106
 
107
  class Conversation(SQLModel, table=True):
 
102
  tenant: Optional["Tenant"] = Relationship(back_populates="leads")
103
  conversations: List["Conversation"] = Relationship(back_populates="lead")
104
  appointments: List["Appointment"] = Relationship(back_populates="lead")
105
+ orders: List["Order"] = Relationship(back_populates="lead")
106
 
107
 
108
  class Conversation(SQLModel, table=True):
backend/app/models/order.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sqlmodel import SQLModel, Field, Relationship, Column
2
+ from sqlalchemy import String, JSON, Float
3
+ from typing import Optional, List, Dict, Any
4
+ from datetime import datetime
5
+ from uuid import UUID, uuid4
6
+ from enum import Enum
7
+
8
+ class OrderStatus(str, Enum):
9
+ NEW = "new"
10
+ PENDING_PAYMENT = "pending_payment"
11
+ PAID = "paid"
12
+ SHIPPED = "shipped"
13
+ COMPLETED = "completed"
14
+ CANCELLED = "cancelled"
15
+
16
+ class Order(SQLModel, table=True):
17
+ """
18
+ Represents a customer order.
19
+ """
20
+ __tablename__ = "orders"
21
+
22
+ id: UUID = Field(default_factory=uuid4, primary_key=True)
23
+ tenant_id: UUID = Field(foreign_key="tenants.id", index=True)
24
+ lead_id: UUID = Field(foreign_key="leads.id", index=True)
25
+
26
+ # Order Details
27
+ status: OrderStatus = Field(default=OrderStatus.NEW)
28
+ total_amount: float = Field(default=0.0)
29
+ currency: str = Field(default="USD")
30
+
31
+ # Context
32
+ shipping_address: Optional[str] = Field(default=None)
33
+ customer_notes: Optional[str] = Field(default=None)
34
+
35
+ # Store arbitrary data (e.g. payment_link, tracking_code)
36
+ meta_data: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
37
+
38
+ # Timestamps
39
+ created_at: datetime = Field(default_factory=datetime.utcnow)
40
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
41
+
42
+ # Relationships
43
+ tenant: Optional["Tenant"] = Relationship(back_populates="orders")
44
+ lead: Optional["Lead"] = Relationship(back_populates="orders")
45
+ items: List["OrderItem"] = Relationship(back_populates="order")
46
+
47
+ class OrderItem(SQLModel, table=True):
48
+ """
49
+ Individual item within an order.
50
+ """
51
+ __tablename__ = "order_items"
52
+
53
+ id: UUID = Field(default_factory=uuid4, primary_key=True)
54
+ tenant_id: UUID = Field(foreign_key="tenants.id", index=True) # Redundant but useful for RLS/Partitioning
55
+ order_id: UUID = Field(foreign_key="orders.id", index=True)
56
+ product_id: Optional[UUID] = Field(default=None, foreign_key="products.id")
57
+
58
+ # Snapshot of product data at time of order
59
+ product_name: str
60
+ quantity: int = Field(default=1)
61
+ unit_price: float = Field(default=0.0)
62
+ total_price: float = Field(default=0.0)
63
+
64
+ # Relationships
65
+ order: Optional[Order] = Relationship(back_populates="items")
66
+ product: Optional["Product"] = Relationship(back_populates="order_items")
backend/app/models/product.py CHANGED
@@ -33,4 +33,5 @@ class Product(SQLModel, table=True):
33
  updated_at: datetime = Field(default_factory=datetime.utcnow)
34
 
35
  # Relationships
36
- # tenant: "Tenant" = Relationship(back_populates="products") # Defined in Tenant
 
 
33
  updated_at: datetime = Field(default_factory=datetime.utcnow)
34
 
35
  # Relationships
36
+ tenant: "Tenant" = Relationship(back_populates="products")
37
+ order_items: List["OrderItem"] = Relationship(back_populates="product") # Defined in Tenant
backend/app/models/tenant.py CHANGED
@@ -85,6 +85,9 @@ class Tenant(SQLModel, table=True):
85
  # Booking System Settings
86
  booking_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
87
 
 
 
 
88
  # Status
89
  is_active: bool = Field(default=True)
90
  created_at: datetime = Field(default_factory=datetime.utcnow)
@@ -96,6 +99,8 @@ class Tenant(SQLModel, table=True):
96
  knowledge_base: List["KnowledgeBase"] = Relationship(back_populates="tenant")
97
  sales_scripts: List["SalesScript"] = Relationship(back_populates="tenant")
98
  sales_stages: List["SalesStage"] = Relationship(back_populates="tenant")
 
 
99
 
100
  # Booking
101
  services: List["Service"] = Relationship(back_populates="tenant")
 
85
  # Booking System Settings
86
  booking_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
87
 
88
+ # Notification Settings (Admin Alerts)
89
+ notification_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
90
+
91
  # Status
92
  is_active: bool = Field(default=True)
93
  created_at: datetime = Field(default_factory=datetime.utcnow)
 
99
  knowledge_base: List["KnowledgeBase"] = Relationship(back_populates="tenant")
100
  sales_scripts: List["SalesScript"] = Relationship(back_populates="tenant")
101
  sales_stages: List["SalesStage"] = Relationship(back_populates="tenant")
102
+ products: List["Product"] = Relationship(back_populates="tenant")
103
+ orders: List["Order"] = Relationship(back_populates="tenant")
104
 
105
  # Booking
106
  services: List["Service"] = Relationship(back_populates="tenant")
backend/app/services/ai_core.py CHANGED
@@ -414,6 +414,37 @@ Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
414
 
415
  return merged
416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  async def _get_booking_context(
418
  self,
419
  session: AsyncSession,
@@ -576,7 +607,8 @@ Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
576
  training_examples: Optional[List[AITrainingExample]] = None,
577
  learning_rules: Optional[List[AILearningRule]] = None,
578
  stage: Optional[SalesStage] = None, # NEW: Playbook Stage
579
- booking_context: str = "" # NEW: Booking System
 
580
  ) -> str:
581
  """
582
  TASK 2: Build HYBRID System Prompt
@@ -697,6 +729,16 @@ Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
697
  βœ… AI: "Понимаю ваши опасСния. Π”Π°Π²Π°ΠΉΡ‚Π΅ Ρ€Π°Π·Π±Π΅Ρ€Ρ‘ΠΌ Ρ†Π΅Π½Π½ΠΎΡΡ‚ΡŒ..."
698
 
699
  ⚠️ НС навязывай запись Π±Π΅Π· контСкста. Π‘ΡƒΠ΄ΡŒ Ρ‚Π°ΠΊΡ‚ΠΈΡ‡Π½Ρ‹ΠΌ.
 
 
 
 
 
 
 
 
 
 
700
  """
701
 
702
  # TASK 3: DYNAMIC BUSINESS LOGIC (Product vs Service)
@@ -1006,14 +1048,22 @@ Core Mindset = КВО Ρ‚Ρ‹. Methodology = КАК Ρ‚Ρ‹ ΠΏΡ€ΠΎΠ΄Π°Ρ‘ΡˆΡŒ.
1006
 
1007
 
1008
 
1009
- {playbook_text}
1010
-
1011
- {booking_instruction}
1012
 
1013
- --------------------------------------------------------------------------------
 
 
 
 
1014
 
1015
- --------------------------------------------------------------------------------
 
 
 
 
 
 
1016
 
 
1017
  ═══════════════════════════════════════════════════════════════
1018
  ═══════════════════════════════════════════════════════════════
1019
  [⚑ ΠŸΠ ΠΠ’Π˜Π›Π ΠžΠ’Π’Π•Π’Π] - STYLE GUIDELINES
 
414
 
415
  return merged
416
 
417
+ async def _get_order_context(
418
+ self,
419
+ session: AsyncSession,
420
+ tenant_id: UUID
421
+ ) -> str:
422
+ """
423
+ Get instructions for the "Order Agent" capability.
424
+ The AI uses this to know HOW to create an order tag.
425
+ """
426
+ # We could fetch tenant settings here (e.g. required fields: Address, Email)
427
+ # For MVP, we hardcode the standard requirements.
428
+
429
+ return """
430
+ ⚠️ ORDER CREATION PROTOCOL (Use when client wants to buy):
431
+ 1. IF the user confirms they want to place an order.
432
+ 2. YOU MUST COLLECT:
433
+ - Items (What products?)
434
+ - Customer Name (If unknown)
435
+ - Delivery Address (If delivery needed)
436
+ - Phone Number
437
+
438
+ 3. ONCE COLLECTED, output the hidden tag to trigger the Order Agent:
439
+ [CREATE_ORDER: {
440
+ "items": [{"product_name": "...", "quantity": 1}],
441
+ "customer": {"name": "...", "phone": "...", "address": "..."},
442
+ "notes": "..."
443
+ }]
444
+
445
+ 4. DO NOT make up an Order ID. Just output the tag. The system will reply with the confirmation.
446
+ """
447
+
448
  async def _get_booking_context(
449
  self,
450
  session: AsyncSession,
 
607
  training_examples: Optional[List[AITrainingExample]] = None,
608
  learning_rules: Optional[List[AILearningRule]] = None,
609
  stage: Optional[SalesStage] = None, # NEW: Playbook Stage
610
+ booking_context: str = "", # NEW: Booking System
611
+ order_context: str = "" # NEW: Order System
612
  ) -> str:
613
  """
614
  TASK 2: Build HYBRID System Prompt
 
729
  βœ… AI: "Понимаю ваши опасСния. Π”Π°Π²Π°ΠΉΡ‚Π΅ Ρ€Π°Π·Π±Π΅Ρ€Ρ‘ΠΌ Ρ†Π΅Π½Π½ΠΎΡΡ‚ΡŒ..."
730
 
731
  ⚠️ НС навязывай запись Π±Π΅Π· контСкста. Π‘ΡƒΠ΄ΡŒ Ρ‚Π°ΠΊΡ‚ΠΈΡ‡Π½Ρ‹ΠΌ.
732
+ """
733
+
734
+ # PREPARE ORDER SECTION (Commerce Agent)
735
+ order_instruction = ""
736
+ if order_context:
737
+ order_instruction = f"""
738
+ ═══════════════════════════════════════════════════════════════
739
+ [ORDER SYSTEM] - COMMERCE AGENT
740
+ ═══════════════════════════════════════════════════════════════
741
+ {order_context}
742
  """
743
 
744
  # TASK 3: DYNAMIC BUSINESS LOGIC (Product vs Service)
 
1048
 
1049
 
1050
 
 
 
 
1051
 
1052
+ """
1053
+
1054
+ # Inject Playbook context
1055
+ if playbook_text:
1056
+ prompt += f"\n{playbook_text}\n"
1057
 
1058
+ # ADD BOOKING & ORDER CONTEXT
1059
+ # (Injecting here to be after Catalog but before Style Rules)
1060
+ if booking_instruction:
1061
+ prompt += booking_instruction
1062
+
1063
+ if order_instruction:
1064
+ prompt += order_instruction
1065
 
1066
+ prompt += """
1067
  ═══════════════════════════════════════════════════════════════
1068
  ═══════════════════════════════════════════════════════════════
1069
  [⚑ ΠŸΠ ΠΠ’Π˜Π›Π ΠžΠ’Π’Π•Π’Π] - STYLE GUIDELINES
backend/app/services/notification.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Dict, Any
2
+ from app.models.tenant import Tenant
3
+ from app.models.order import Order
4
+ from app.models.booking import Appointment
5
+ from app.api.deps import send_telegram_message # Assuming this is available or we import the util
6
+ import logging
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+ class NotificationService:
11
+ """
12
+ Handles internal notifications (ALERTS) for the Tenant/Admin.
13
+ Triggers when important events occur (Order, Booking).
14
+ """
15
+
16
+ async def notify_new_order(self, tenant: Tenant, order: Order, items_text: str):
17
+ """Send alert about a new order."""
18
+ if not tenant.notification_settings:
19
+ return
20
+
21
+ settings = tenant.notification_settings
22
+
23
+ # 1. Telegram Notification
24
+ tg_chat_id = settings.get("telegram_chat_id")
25
+ if tg_chat_id and settings.get("notify_on_order", True):
26
+ message = (
27
+ f"🚨 **ΠΠžΠ’Π«Π™ Π—ΠΠšΠΠ—** 🚨\n\n"
28
+ f"πŸ†” ID: {str(order.id)[:8]}\n"
29
+ f"πŸ‘€ ΠšΠ»ΠΈΠ΅Π½Ρ‚: {order.lead.name or 'НСизвСстно'} (ID: {order.lead_id})\n"
30
+ f"πŸ“¦ Π’ΠΎΠ²Π°Ρ€Ρ‹:\n{items_text}\n"
31
+ f"πŸ’° Π‘ΡƒΠΌΠΌΠ°: {order.total_amount:.2f}\n"
32
+ f"πŸ“… Π”Π°Ρ‚Π°: {order.created_at.strftime('%Y-%m-%d %H:%M')}"
33
+ )
34
+ await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
35
+
36
+ async def notify_new_appointment(self, tenant: Tenant, appointment: Appointment):
37
+ """Send alert about a new booking."""
38
+ if not tenant.notification_settings:
39
+ return
40
+
41
+ settings = tenant.notification_settings
42
+
43
+ # 1. Telegram Notification
44
+ tg_chat_id = settings.get("telegram_chat_id")
45
+ if tg_chat_id and settings.get("notify_on_booking", True):
46
+ # Format time
47
+ start = appointment.start_time.strftime('%d.%m %H:%M')
48
+
49
+ message = (
50
+ f"πŸ“… **ΠΠžΠ’ΠΠ― Π—ΠΠŸΠ˜Π‘Π¬** πŸ“…\n\n"
51
+ f"πŸ‘€ ΠšΠ»ΠΈΠ΅Π½Ρ‚: {appointment.lead.name or 'НСизвСстно'}\n"
52
+ f"πŸ•’ ВрСмя: {start}\n"
53
+ f"πŸ“ Услуга: {appointment.service.name if appointment.service else 'ΠžΠ±Ρ‰Π°Ρ'}\n"
54
+ f"πŸ’¬ Π—Π°ΠΌΠ΅Ρ‚ΠΊΠ°: {appointment.notes}"
55
+ )
56
+ await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
57
+
58
+ async def _send_telegram(self, bot_token: str, chat_id: str, text: str):
59
+ """Helper to send TG message."""
60
+ if not bot_token or not chat_id:
61
+ logger.warning("⚠️ Cannot send notification: Missing bot_token or chat_id")
62
+ return
63
+
64
+ try:
65
+ # We can reuse the existing utility from webhook or define strict request here
66
+ # Ideally verify if 'app.utils.telegram' exists or similar.
67
+ # Using the one imported from deps/webhook context usually
68
+ from app.api.webhook import send_telegram_message as send_tg
69
+
70
+ await send_tg(bot_token, chat_id, text)
71
+ logger.info(f"πŸ“§ Notification sent to Admin {chat_id}")
72
+ except Exception as e:
73
+ logger.error(f"❌ Failed to send admin notification: {e}")
74
+
75
+ # Singleton
76
+ notification_service = NotificationService()
backend/apply_notification_migration.py CHANGED
@@ -1,119 +1,35 @@
1
- """
2
- Simple notification migration - runs SQL directly without app imports
3
- """
4
-
5
  import asyncio
6
- import asyncpg
7
  import os
8
- from dotenv import load_dotenv
9
-
10
- # Load .env
11
- load_dotenv()
12
 
13
- async def run_migration():
14
- """Run migration using direct PostgreSQL connection."""
15
-
16
- # Get database URL from environment
17
- database_url = os.getenv('DATABASE_URL')
18
-
19
- if not database_url:
20
- print("❌ DATABASE_URL not found in .env")
21
- return
22
 
23
- # Replace postgres:// with postgresql:// if needed
24
- if database_url.startswith('postgres://'):
25
- database_url = database_url.replace('postgres://', 'postgresql://', 1)
26
-
27
- print(f"πŸ”„ Connecting to database...")
28
-
29
- try:
30
- # Connect to database
31
- conn = await asyncpg.connect(database_url)
32
-
33
- print("βœ… Connected successfully!")
34
- print("πŸ”„ Running migration...")
35
-
36
- # Run migration SQL
37
- await conn.execute("""
38
- -- Create notification_settings table
39
- CREATE TABLE IF NOT EXISTS notification_settings (
40
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
41
- tenant_id UUID NOT NULL UNIQUE REFERENCES tenants(id) ON DELETE CASCADE,
42
-
43
- -- Telegram Settings
44
- telegram_enabled BOOLEAN DEFAULT TRUE,
45
- telegram_chat_id VARCHAR(255),
46
- telegram_bot_token VARCHAR(255),
47
-
48
- -- Dashboard Settings
49
- dashboard_enabled BOOLEAN DEFAULT TRUE,
50
-
51
- -- Email Settings (for future)
52
- email_enabled BOOLEAN DEFAULT FALSE,
53
- email_address VARCHAR(255),
54
-
55
- -- Notification Types
56
- notify_hot_leads BOOLEAN DEFAULT TRUE,
57
- notify_inactive_leads BOOLEAN DEFAULT FALSE,
58
- notify_new_leads BOOLEAN DEFAULT FALSE,
59
-
60
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
61
- updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
62
- );
63
- """)
64
-
65
- await conn.execute("""
66
- -- Create notifications table
67
- CREATE TABLE IF NOT EXISTS notifications (
68
- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
69
- tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
70
- lead_id UUID NOT NULL REFERENCES leads(id) ON DELETE CASCADE,
71
-
72
- -- Notification Details
73
- type VARCHAR(50) NOT NULL,
74
- title VARCHAR(255) NOT NULL,
75
- message TEXT NOT NULL,
76
-
77
- -- Status
78
- is_read BOOLEAN DEFAULT FALSE,
79
- read_at TIMESTAMP,
80
-
81
- -- Channels
82
- sent_telegram BOOLEAN DEFAULT FALSE,
83
- sent_dashboard BOOLEAN DEFAULT TRUE,
84
-
85
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
86
- );
87
- """)
88
-
89
- # Create indexes
90
- await conn.execute("CREATE INDEX IF NOT EXISTS idx_notification_settings_tenant_id ON notification_settings(tenant_id);")
91
- await conn.execute("CREATE INDEX IF NOT EXISTS idx_notifications_tenant_id ON notifications(tenant_id);")
92
- await conn.execute("CREATE INDEX IF NOT EXISTS idx_notifications_is_read ON notifications(is_read);")
93
- await conn.execute("CREATE INDEX IF NOT EXISTS idx_notifications_created_at ON notifications(created_at DESC);")
94
- await conn.execute("CREATE INDEX IF NOT EXISTS idx_notifications_type ON notifications(type);")
95
-
96
- # Insert default settings for existing tenants
97
- result = await conn.execute("""
98
- INSERT INTO notification_settings (tenant_id, telegram_enabled, dashboard_enabled, notify_hot_leads)
99
- SELECT id, TRUE, TRUE, TRUE
100
- FROM tenants
101
- WHERE id NOT IN (SELECT tenant_id FROM notification_settings);
102
- """)
103
-
104
- print("βœ… Migration completed successfully!")
105
- print("πŸ“Š Tables created:")
106
- print(" - notification_settings")
107
- print(" - notifications")
108
- print("πŸ“Œ Indexes created for performance")
109
- print(f"🎯 Default settings created: {result}")
110
-
111
- # Close connection
112
- await conn.close()
113
-
114
- except Exception as e:
115
- print(f"❌ Migration failed: {e}")
116
- raise
117
 
118
  if __name__ == "__main__":
119
- asyncio.run(run_migration())
 
 
 
 
 
1
  import asyncio
 
2
  import os
3
+ from sqlalchemy import text
4
+ from app.core.config import settings
5
+ from app.core.database import async_session_maker
 
6
 
7
+ async def apply_migration():
8
+ """Add notification_settings to tenants table."""
9
+ print("πŸš€ Starting migration: Add notification_settings to tenants...")
 
 
 
 
 
 
10
 
11
+ async with async_session_maker() as session:
12
+ try:
13
+ # Check if column exists
14
+ print("Checking if column exists...")
15
+ result = await session.execute(text(
16
+ "SELECT column_name FROM information_schema.columns WHERE table_name='tenants' AND column_name='notification_settings'"
17
+ ))
18
+ if result.scalar():
19
+ print("⚠️ Column 'notification_settings' already exists. Skipping.")
20
+ return
21
+
22
+ print("Adding 'notification_settings' column...")
23
+ # Add column
24
+ await session.execute(text(
25
+ "ALTER TABLE tenants ADD COLUMN notification_settings JSON"
26
+ ))
27
+ await session.commit()
28
+ print("βœ… Migration applied successfully: Column 'notification_settings' added.")
29
+
30
+ except Exception as e:
31
+ print(f"❌ Migration failed: {e}")
32
+ await session.rollback()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  if __name__ == "__main__":
35
+ asyncio.run(apply_migration())
backend/apply_order_migration.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import os
3
+ from sqlmodel import SQLModel, create_engine, text
4
+ from sqlalchemy.ext.asyncio import create_async_engine
5
+
6
+ # Import models to register them with SQLModel.metadata
7
+ from app.models.tenant import Tenant
8
+ from app.models.lead import Lead
9
+ from app.models.product import Product
10
+ from app.models.order import Order, OrderItem
11
+ from app.core.config import settings
12
+
13
+ # Database Interface
14
+ DATABASE_URL = str(settings.DATABASE_URL)
15
+ if not DATABASE_URL:
16
+ # Fallback for local dev if .env not loaded (try to read .env manually if needed, or assume local)
17
+ # Using a default or erroring out.
18
+ print("❌ DATABASE_URL not set")
19
+ exit(1)
20
+
21
+ # Fix for asyncpg
22
+ if DATABASE_URL.startswith("postgresql://"):
23
+ DATABASE_URL = DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://", 1)
24
+
25
+ engine = create_async_engine(DATABASE_URL, echo=True)
26
+
27
+ async def create_tables():
28
+ print("πŸ”„ Creating Order and OrderItem tables...")
29
+ async with engine.begin() as conn:
30
+ # Create all tables that don't exist
31
+ # This is safe, it won't recreate existing ones
32
+ await conn.run_sync(SQLModel.metadata.create_all)
33
+
34
+ print("βœ… Tables created successfully!")
35
+
36
+ if __name__ == "__main__":
37
+ asyncio.run(create_tables())