|
| 1 | +from typing import List, Optional |
| 2 | +from app.database import database |
| 3 | +from .schemas import Integration, IntegrationUpdate |
| 4 | + |
| 5 | +collection_name = "integrations" |
| 6 | + |
| 7 | + |
| 8 | +async def list_integrations() -> List[Integration]: |
| 9 | + """Get all integrations.""" |
| 10 | + cursor = database[collection_name].find() |
| 11 | + integrations = await cursor.to_list(length=None) |
| 12 | + return [Integration(**integration) for integration in integrations] |
| 13 | + |
| 14 | + |
| 15 | +async def get_integration(id: str) -> Optional[Integration]: |
| 16 | + """Get a specific integration by ID.""" |
| 17 | + integration = await database[collection_name].find_one({"id": id}) |
| 18 | + if integration: |
| 19 | + return Integration(**integration) |
| 20 | + return None |
| 21 | + |
| 22 | + |
| 23 | +async def update_integration( |
| 24 | + id: str, integration: IntegrationUpdate |
| 25 | +) -> Optional[Integration]: |
| 26 | + """Update an integration's status and settings.""" |
| 27 | + update_data = integration.model_dump(exclude_unset=True) |
| 28 | + |
| 29 | + result = await database[collection_name].find_one_and_update( |
| 30 | + {"id": id}, |
| 31 | + {"$set": update_data}, |
| 32 | + return_document=True, |
| 33 | + ) |
| 34 | + |
| 35 | + if result: |
| 36 | + return Integration(**result) |
| 37 | + return None |
| 38 | + |
| 39 | + |
| 40 | +async def ensure_default_integrations(): |
| 41 | + """Ensure default integrations exist in the database.""" |
| 42 | + default_integrations = [ |
| 43 | + { |
| 44 | + "id": "facebook", |
| 45 | + "name": "Facebook Messenger", |
| 46 | + "description": "Connect with Facebook Messenger", |
| 47 | + "status": False, |
| 48 | + "settings": { |
| 49 | + "verify": "ai-chatbot-framework", |
| 50 | + "secret": "", |
| 51 | + "page_access_token": "", |
| 52 | + }, |
| 53 | + }, |
| 54 | + { |
| 55 | + "id": "chat_widget", |
| 56 | + "name": "Chat Widget", |
| 57 | + "description": "Add a chat widget to your website", |
| 58 | + "status": True, |
| 59 | + "settings": {}, |
| 60 | + }, |
| 61 | + ] |
| 62 | + |
| 63 | + for integration in default_integrations: |
| 64 | + await database[collection_name].update_one( |
| 65 | + {"id": integration["id"]}, |
| 66 | + {"$setOnInsert": integration}, |
| 67 | + upsert=True, |
| 68 | + ) |
0 commit comments