chore(cleanup): remove contact-related files and update JWT expiration time settings

This commit is contained in:
Davidson Gomes
2025-05-07 11:43:00 -03:00
parent 8979251541
commit 0e3c331a72
21 changed files with 151 additions and 744 deletions

View File

@@ -10,54 +10,56 @@ import argparse
from dotenv import load_dotenv
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# Import seeders
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from scripts.seeders.admin_seeder import create_admin_user
from scripts.seeders.client_seeder import create_demo_client_and_user
from scripts.seeders.agent_seeder import create_demo_agents
from scripts.seeders.mcp_server_seeder import create_mcp_servers
from scripts.seeders.tool_seeder import create_tools
from scripts.seeders.contact_seeder import create_demo_contacts
def setup_environment():
"""Configure the environment for seeders"""
load_dotenv()
# Check if essential environment variables are defined
required_vars = ["POSTGRES_CONNECTION_STRING"]
missing_vars = [var for var in required_vars if not os.getenv(var)]
if missing_vars:
logger.error(f"Required environment variables not defined: {', '.join(missing_vars)}")
logger.error(
f"Required environment variables not defined: {', '.join(missing_vars)}"
)
return False
return True
def run_seeders(seeders):
"""
Run the specified seeders
Args:
seeders (list): List of seeders to run
Returns:
bool: True if all seeders were executed successfully, False otherwise
"""
all_seeders = {
"admin": create_admin_user,
"client": create_demo_client_and_user,
"agents": create_demo_agents,
"mcp_servers": create_mcp_servers,
"tools": create_tools,
"contacts": create_demo_contacts
}
# Define the correct execution order (dependencies)
seeder_order = ["admin", "client", "mcp_servers", "tools", "agents", "contacts"]
seeder_order = ["admin", "client", "mcp_servers", "tools"]
# If no seeder is specified, run all
if not seeders:
seeders = seeder_order
@@ -68,15 +70,15 @@ def run_seeders(seeders):
logger.error(f"Invalid seeders: {', '.join(invalid_seeders)}")
logger.info(f"Available seeders: {', '.join(all_seeders.keys())}")
return False
# Ensure seeders are executed in the correct order
seeders = [s for s in seeder_order if s in seeders]
# Run seeders
success = True
for seeder_name in seeders:
logger.info(f"Running seeder: {seeder_name}")
try:
seeder_func = all_seeders[seeder_name]
if not seeder_func():
@@ -85,22 +87,27 @@ def run_seeders(seeders):
except Exception as e:
logger.error(f"Error running seeder {seeder_name}: {str(e)}")
success = False
return success
def main():
"""Main function"""
parser = argparse.ArgumentParser(description='Run seeders to populate the database')
parser.add_argument('--seeders', nargs='+', help='Seeders to run (admin, client, agents, mcp_servers, tools, contacts)')
parser = argparse.ArgumentParser(description="Run seeders to populate the database")
parser.add_argument(
"--seeders",
nargs="+",
help="Seeders to run (admin, client, mcp_servers, tools)",
)
args = parser.parse_args()
# Configure environment
if not setup_environment():
sys.exit(1)
# Run seeders
success = run_seeders(args.seeders)
# Output
if success:
logger.info("All seeders were executed successfully")
@@ -109,5 +116,6 @@ def main():
logger.error("There were errors running the seeders")
sys.exit(1)
if __name__ == "__main__":
main()
main()

View File

@@ -1,171 +0,0 @@
"""
Script to create example agents for the demo client:
- Agent Support: configured to answer general questions
- Agent Sales: configured to answer about products
- Agent FAQ: configured to answer frequently asked questions
Each agent with pre-defined instructions and configurations
"""
import os
import sys
import logging
import uuid
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from dotenv import load_dotenv
from src.models.models import Agent, Client, User
# Configurar logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def create_demo_agents():
"""Create example agents for the demo client"""
try:
# Load environment variables
load_dotenv()
# Get database settings
db_url = os.getenv("POSTGRES_CONNECTION_STRING")
if not db_url:
logger.error("Environment variable POSTGRES_CONNECTION_STRING not defined")
return False
# Connect to the database
engine = create_engine(db_url)
Session = sessionmaker(bind=engine)
session = Session()
try:
# Obter o cliente demo pelo email do usuário
demo_email = os.getenv("DEMO_EMAIL", "demo@exemplo.com")
demo_user = session.query(User).filter(User.email == demo_email).first()
if not demo_user or not demo_user.client_id:
logger.error(
f"Demo user not found or not associated with a client: {demo_email}"
)
return False
client_id = demo_user.client_id
# Verificar se já existem agentes para este cliente
existing_agents = (
session.query(Agent).filter(Agent.client_id == client_id).all()
)
if existing_agents:
logger.info(
f"There are already {len(existing_agents)} agents for the client {client_id}"
)
return True
# Example agent definitions
agents = [
{
"name": "Support_Agent",
"description": "Agent for general support and basic questions",
"type": "llm",
"model": "gpt-4.1-nano",
"api_key": "your-api-key-here",
"instruction": """
You are a customer support agent.
Be friendly, objective and efficient. Answer customer questions
in a clear and concise manner. If you don't know the answer,
inform that you will consult a specialist and return soon.
""",
"config": {
"api_key": uuid.uuid4(),
"tools": [],
"mcp_servers": [],
"custom_tools": [],
"sub_agents": [],
},
},
{
"name": "Sales_Products",
"description": "Specialized agent in sales and information about products",
"type": "llm",
"model": "gpt-4.1-nano",
"api_key": "your-api-key-here",
"instruction": """
You are a sales specialist.
Your goal is to provide detailed information about products,
compare different options, highlight benefits and competitive advantages.
Use a persuasive but honest language, and always seek to understand
the customer's needs before recommending a product.
""",
"config": {
"api_key": uuid.uuid4(),
"tools": [],
"mcp_servers": [],
"custom_tools": [],
"sub_agents": [],
},
},
{
"name": "FAQ_Bot",
"description": "Agent for answering frequently asked questions",
"type": "llm",
"model": "gpt-4.1-nano",
"api_key": "your-api-key-here",
"instruction": """
You are a specialized agent for answering frequently asked questions.
Your answers should be direct, objective and based on the information
of the company. Use a simple and accessible language. If the question
is not related to the available FAQs, redirect the client to the
appropriate support channel.
""",
"config": {
"api_key": uuid.uuid4(),
"tools": [],
"mcp_servers": [],
"custom_tools": [],
"sub_agents": [],
},
},
]
# Create the agents
for agent_data in agents:
# Create the agent
agent = Agent(
client_id=client_id,
name=agent_data["name"],
description=agent_data["description"],
type=agent_data["type"],
model=agent_data["model"],
api_key=agent_data["api_key"],
instruction=agent_data["instruction"].strip(),
config=agent_data["config"],
)
session.add(agent)
logger.info(
f"Agent '{agent_data['name']}' created for the client {client_id}"
)
session.commit()
logger.info(
f"All example agents were created successfully for the client {client_id}"
)
return True
except SQLAlchemyError as e:
session.rollback()
logger.error(f"Database error when creating example agents: {str(e)}")
return False
except Exception as e:
logger.error(f"Error when creating example agents: {str(e)}")
return False
finally:
session.close()
if __name__ == "__main__":
success = create_demo_agents()
sys.exit(0 if success else 1)

View File

@@ -20,45 +20,48 @@ from src.models.models import User, Client
from src.utils.security import get_password_hash
# Configurar logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def create_demo_client_and_user():
"""Create a demo client and user in the system"""
try:
# Load environment variables
load_dotenv()
# Get database settings
db_url = os.getenv("POSTGRES_CONNECTION_STRING")
if not db_url:
logger.error("Environment variable POSTGRES_CONNECTION_STRING not defined")
return False
# Get demo user password (or use default)
demo_password = os.getenv("DEMO_PASSWORD", "demo123")
# Demo client and user settings
demo_client_name = os.getenv("DEMO_CLIENT_NAME", "Demo Client")
demo_email = os.getenv("DEMO_EMAIL", "demo@example.com")
# Connect to the database
engine = create_engine(db_url)
Session = sessionmaker(bind=engine)
session = Session()
try:
# Check if the user already exists
existing_user = session.query(User).filter(User.email == demo_email).first()
if existing_user:
logger.info(f"Demo user with email {demo_email} already exists")
return True
# Create demo client
demo_client = Client(name=demo_client_name)
demo_client = Client(name=demo_client_name, email=demo_email)
session.add(demo_client)
session.flush() # Get the client ID
# Create demo user associated with the client
demo_user = User(
email=demo_email,
@@ -66,28 +69,29 @@ def create_demo_client_and_user():
client_id=demo_client.id,
is_admin=False,
is_active=True,
email_verified=True
email_verified=True,
)
# Add and commit
session.add(demo_user)
session.commit()
logger.info(f"Demo client '{demo_client_name}' created successfully")
logger.info(f"Demo user created successfully: {demo_email}")
return True
except SQLAlchemyError as e:
session.rollback()
logger.error(f"Database error when creating demo client/user: {str(e)}")
return False
except Exception as e:
logger.error(f"Error when creating demo client/user: {str(e)}")
return False
finally:
session.close()
if __name__ == "__main__":
success = create_demo_client_and_user()
sys.exit(0 if success else 1)
sys.exit(0 if success else 1)

View File

@@ -1,184 +0,0 @@
"""
Script to create example contacts for the demo client:
- Contacts with conversation history
- Different client profiles
- Fake data for demonstration
"""
import os
import sys
import logging
import json
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
from dotenv import load_dotenv
from src.models.models import Contact, User, Client
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def create_demo_contacts():
"""Create example contacts for the demo client"""
try:
# Load environment variables
load_dotenv()
# Get database settings
db_url = os.getenv("POSTGRES_CONNECTION_STRING")
if not db_url:
logger.error("Environment variable POSTGRES_CONNECTION_STRING not defined")
return False
# Connect to the database
engine = create_engine(db_url)
Session = sessionmaker(bind=engine)
session = Session()
try:
# Get demo client by user email
demo_email = os.getenv("DEMO_EMAIL", "demo@example.com")
demo_user = session.query(User).filter(User.email == demo_email).first()
if not demo_user or not demo_user.client_id:
logger.error(
f"Demo user not found or not associated with a client: {demo_email}"
)
return False
client_id = demo_user.client_id
# Check if there are already contacts for this client
existing_contacts = (
session.query(Contact).filter(Contact.client_id == client_id).all()
)
if existing_contacts:
logger.info(
f"There are already {len(existing_contacts)} contacts for the client {client_id}"
)
return True
# Example contact definitions
contacts = [
{
"name": "Maria Silva",
"ext_id": "5511999998888",
"meta": {
"source": "whatsapp",
"tags": ["cliente_vip", "suporte_premium"],
"location": "São Paulo, SP",
"last_contact": "2023-08-15T14:30:00Z",
"account_details": {
"customer_since": "2020-03-10",
"plan": "Enterprise",
"payment_status": "active",
},
},
},
{
"name": "João Santos",
"ext_id": "5511988887777",
"meta": {
"source": "whatsapp",
"tags": ["prospecção", "demo_solicitada"],
"location": "Rio de Janeiro, RJ",
"last_contact": "2023-09-20T10:15:00Z",
"interests": ["automação", "marketing", "chatbots"],
},
},
{
"name": "Ana Oliveira",
"ext_id": "5511977776666",
"meta": {
"source": "telegram",
"tags": ["suporte_técnico", "problema_resolvido"],
"location": "Belo Horizonte, MG",
"last_contact": "2023-09-25T16:45:00Z",
"support_cases": [
{
"id": "SUP-2023-1234",
"status": "closed",
"priority": "high",
},
{
"id": "SUP-2023-1567",
"status": "open",
"priority": "medium",
},
],
},
},
{
"name": "Carlos Pereira",
"ext_id": "5511966665555",
"meta": {
"source": "whatsapp",
"tags": ["cancelamento", "retenção"],
"location": "Porto Alegre, RS",
"last_contact": "2023-09-10T09:30:00Z",
"account_details": {
"customer_since": "2019-05-22",
"plan": "Professional",
"payment_status": "overdue",
"invoice_pending": True,
},
},
},
{
"name": "Fernanda Lima",
"ext_id": "5511955554444",
"meta": {
"source": "telegram",
"tags": ["parceiro", "integrador"],
"location": "Curitiba, PR",
"last_contact": "2023-09-18T14:00:00Z",
"partner_details": {
"company": "TechSolutions Ltda",
"partner_level": "Gold",
"certified": True,
},
},
},
]
# Create the contacts
for contact_data in contacts:
contact = Contact(
client_id=client_id,
name=contact_data["name"],
ext_id=contact_data["ext_id"],
meta=contact_data["meta"],
)
session.add(contact)
logger.info(
f"Contact '{contact_data['name']}' created for the client {client_id}"
)
session.commit()
logger.info(
f"All example contacts were created successfully for the client {client_id}"
)
return True
except SQLAlchemyError as e:
session.rollback()
logger.error(
f"Database error when creating example contacts: {str(e)}"
)
return False
except Exception as e:
logger.error(f"Error when creating example contacts: {str(e)}")
return False
finally:
session.close()
if __name__ == "__main__":
success = create_demo_contacts()
sys.exit(0 if success else 1)