Spaces:
Paused

nexus / seeds /seed_data.py
dushyantsingh0
Beta 1.0: Pure Backend Release (Excluding Frontend)
5eb4857
Raw History Blame Contribute Delete
8.85 kB
import asyncio
import uuid
import traceback
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from core.config import get_settings
from models.workspace import Workspace
from models.user import User, UserRole
from models.project import Project
from models.ticket import Ticket, TicketStatus, TicketPriority
from models.kb_article import KBArticle
from models.kb_article import KBArticle
from models.message import Message
from models.notification import Notification
from models.feedback import Feedback
from models.escalation_rule import EscalationRule
from core.security import get_password_hash
from core.llm import get_embeddings
settings = get_settings()
# Create local engine for seeding
engine = create_async_engine(settings.DATABASE_URL, echo=True)
async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def seed_data():
print(f"DEBUG: Using DATABASE_URL: {settings.DATABASE_URL}")
print(f"DEBUG: Engine Dialect: {engine.name}")
try:
async with async_session_factory() as db:
# Use naive UTC for seed data
now = datetime.now()
# Ensure tables are fresh
async with engine.begin() as conn:
from sqlalchemy import text
from core.database import Base
import models # noqa
await conn.run_sync(Base.metadata.drop_all)
await conn.execute(text("CREATE EXTENSION IF NOT EXISTS vector"))
await conn.run_sync(Base.metadata.create_all)
print("Fresh database tables created.")
print("Step 1: Workspace")
workspace_id = uuid.uuid4()
workspace = Workspace(
id=workspace_id,
name="Snowball Dev Workspace",
branding={"primary_color": "#4F46E5", "logo_url": "https://example.com/logo.png"}
)
db.add(workspace)
await db.flush() # Ensure workspace exists for FKs
print(f"Added workspace: {workspace_id}")
print("Step 2: Users")
admin_id = uuid.uuid4()
admin = User(
id=admin_id,
email="admin@snowball.dev",
full_name="Admin User",
hashed_password=get_password_hash("admin123"),
role=UserRole.SC_ADMIN,
workspace_id=workspace_id,
is_active=True
)
db.add(admin)
agent_id = uuid.uuid4()
agent = User(
id=agent_id,
email="agent@snowball.dev",
full_name="Support Agent",
hashed_password=get_password_hash("agent123"),
role=UserRole.SC_AGENT,
workspace_id=workspace_id,
is_active=True
)
db.add(agent)
customer_id = uuid.uuid4()
customer = User(
id=customer_id,
email="customer@client.com",
full_name="John Client",
hashed_password=get_password_hash("client123"),
role=UserRole.CUSTOMER_USER,
workspace_id=workspace_id,
is_active=True
)
db.add(customer)
await db.flush()
print(f"Added users: Admin={admin_id}, Agent={agent_id}, Customer={customer_id}")
print("Step 3: Project")
project_id = uuid.uuid4()
project = Project(
id=project_id,
workspace_id=workspace_id,
name="Cloud Infrastructure Migration",
description="Phase 2 of the cloud migration project.",
metadata_json={}
)
db.add(project)
print(f"Added project: {project_id}")
print("Step 4: KB Article")
kb_title = "How to reset your cloud password"
kb_content = "To reset your password, navigate to the settings pane and click 'Reset'. Follow the email instructions."
embed_model = get_embeddings()
kb_embedding = await embed_model.aembed_query(f"{kb_title} {kb_content}")
kb_article_id = uuid.uuid4()
kb_article = KBArticle(
id=kb_article_id,
workspace_id=workspace_id,
author_id=agent_id,
project_id=project_id,
title=kb_title,
content=kb_content,
category="Security",
embedding=kb_embedding,
is_published=True
)
db.add(kb_article)
print(f"Added KB: {kb_article_id}")
print("Step 5: Tickets")
ticket1_id = uuid.uuid4()
ticket1 = Ticket(
id=ticket1_id,
workspace_id=workspace_id,
created_by=customer_id,
project_id=project_id,
title="Unable to access AWS console",
description="Getting a 403 Forbidden error when trying to log in.",
category="Technical Support",
priority=TicketPriority.P1,
status=TicketStatus.OPEN
)
db.add(ticket1)
msg1 = Message(
id=uuid.uuid4(),
workspace_id=workspace_id,
ticket_id=ticket1_id,
sender_id=customer_id,
content="I've already tried clearing my cookies.",
is_internal=False
)
db.add(msg1)
ticket2_id = uuid.uuid4()
ticket2 = Ticket(
id=ticket2_id,
workspace_id=workspace_id,
created_by=customer_id,
project_id=project_id,
title="Feature request: Auto-scaling",
description="We need auto-scaling enabled for the staging environment.",
category="Feature Request",
priority=TicketPriority.P2,
status=TicketStatus.RESOLVED,
assigned_to=agent_id
)
db.add(ticket2)
print("Step 6: Feedback")
feedback_obj = Feedback(
id=uuid.uuid4(),
workspace_id=workspace_id,
ticket_id=ticket2_id,
user_id=customer_id,
rating=5,
comment="Great support, very fast!"
)
db.add(feedback_obj)
print("Step 7: Escalation")
e_rule = EscalationRule(
id=uuid.uuid4(),
workspace_id=workspace_id,
name="High Priority Escalation",
priority_level="P1",
threshold_minutes=30,
action="NOTIFY_LEAD"
)
db.add(e_rule)
print("Step 8: Remediation Hooks")
from models.remediation import RemediationHook, RemediationActionType
hook1 = RemediationHook(
id=uuid.uuid4(),
workspace_id=workspace_id,
trigger_category="Technical Support",
action_type=RemediationActionType.WEBHOOK,
target="https://api.snowball.dev/webhooks/remediate",
payload_template={"ticket_id": "{{ticket_id}}", "action": "restart_service"},
description="Auto-remedy common technical support issues via webhook."
)
db.add(hook1)
hook2 = RemediationHook(
id=uuid.uuid4(),
workspace_id=workspace_id,
trigger_category="Security",
action_type=RemediationActionType.NOTIFICATION_ONLY,
description="Security issues require manual review and an automatic alert."
)
db.add(hook2)
print("Step 9: Notification")
note = Notification(
id=uuid.uuid4(),
workspace_id=workspace_id,
user_id=agent_id,
title="New Ticket Assigned",
message=f"You have been assigned ticket: {ticket2.title}",
is_read=False
)
db.add(note)
print("Committing seed data...")
await db.commit()
print("Seed data committed successfully.")
except Exception as e:
print(f"Error seeding data: {e}")
traceback.print_exc()
try:
await db.rollback()
except:
pass
except Exception as e:
print(f"Error seeding data: {e}")
traceback.print_exc()
if __name__ == "__main__":
asyncio.run(seed_data())