421 lines
14 KiB
Python
421 lines
14 KiB
Python
import requests
|
|
import logging
|
|
from typing import Optional, Dict, Any, List
|
|
from config import Config
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class APIClient:
|
|
"""Client for interacting with the PersonalizeIT API"""
|
|
|
|
def __init__(self):
|
|
self.base_url = Config.API_BASE_URL
|
|
self.token = None
|
|
self.session = requests.Session()
|
|
self.session.verify = True # Verify SSL certificates
|
|
|
|
def login(self) -> bool:
|
|
"""
|
|
Authenticate with the API and obtain a bearer token
|
|
|
|
Returns:
|
|
bool: True if authentication was successful, False otherwise
|
|
"""
|
|
try:
|
|
login_url = f"{self.base_url}{Config.API_LOGIN_ENDPOINT}"
|
|
|
|
payload = {
|
|
"email": Config.API_USERNAME,
|
|
"password": Config.API_PASSWORD
|
|
}
|
|
|
|
logger.info(f"Attempting to authenticate at {login_url}")
|
|
response = self.session.post(
|
|
login_url,
|
|
json=payload,
|
|
timeout=10
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
data = response.json()
|
|
self.token = data.get('token') or data.get('access_token')
|
|
|
|
if self.token:
|
|
logger.info("Successfully authenticated")
|
|
self._set_auth_header()
|
|
return True
|
|
else:
|
|
logger.error("Token not found in login response")
|
|
return False
|
|
else:
|
|
logger.error(f"Login failed with status code {response.status_code}: {response.text}")
|
|
return False
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Error during login: {str(e)}")
|
|
return False
|
|
|
|
def _set_auth_header(self):
|
|
"""Set the authorization header with the bearer token"""
|
|
if self.token:
|
|
self.session.headers.update({
|
|
'Authorization': f'Bearer {self.token}',
|
|
'Content-Type': 'application/json'
|
|
})
|
|
|
|
def get_tickets(self,
|
|
page_number: int = 1,
|
|
status: str = 'pending',
|
|
sort_dir: str = 'DESC',
|
|
queue_ids: Optional[List[int]] = None,
|
|
is_group: bool = False) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Fetch tickets from the API
|
|
|
|
Args:
|
|
page_number: Page number (default: 1)
|
|
status: Ticket status filter (default: 'pending')
|
|
sort_dir: Sort direction (default: 'DESC')
|
|
queue_ids: List of queue IDs to filter (default: from Config)
|
|
is_group: Whether to fetch group tickets (default: False)
|
|
|
|
Returns:
|
|
dict: Response data if successful, None otherwise
|
|
"""
|
|
if not self.token:
|
|
logger.error("Not authenticated. Please login first.")
|
|
return None
|
|
|
|
try:
|
|
import json
|
|
|
|
if queue_ids is None:
|
|
queue_ids = Config.get_queue_ids_list()
|
|
|
|
tickets_url = f"{self.base_url}{Config.API_TICKETS_ENDPOINT}"
|
|
|
|
# Format queueIds as JSON string for API compatibility
|
|
params = {
|
|
'pageNumber': page_number,
|
|
'status': status,
|
|
'showAll': 'false',
|
|
'queueIds': json.dumps(queue_ids),
|
|
'tagIds': '[]',
|
|
'isGroup': 'true' if is_group else 'false',
|
|
'sortDir': sort_dir,
|
|
'isSearching': 'false'
|
|
}
|
|
|
|
logger.info(f"Fetching tickets from {tickets_url} with params: {params}")
|
|
response = self.session.get(
|
|
tickets_url,
|
|
params=params,
|
|
timeout=15
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
logger.info(f"Successfully fetched tickets")
|
|
return response.json()
|
|
else:
|
|
logger.error(f"Failed to fetch tickets: {response.status_code} - {response.text}")
|
|
return None
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Error fetching tickets: {str(e)}")
|
|
return None
|
|
|
|
def get_all_tickets(self) -> List[Dict[str, Any]]:
|
|
"""
|
|
Fetch all pending, open and group tickets
|
|
|
|
Returns:
|
|
list: List of ticket dictionaries
|
|
"""
|
|
all_tickets = []
|
|
|
|
# Fetch pending tickets
|
|
logger.info("Fetching pending tickets...")
|
|
page = 1
|
|
while True:
|
|
result = self.get_tickets(page_number=page, status='pending', is_group=False)
|
|
|
|
if not result or not result.get('tickets'):
|
|
break
|
|
|
|
all_tickets.extend(result.get('tickets', []))
|
|
|
|
if not result.get('hasMore', False):
|
|
break
|
|
|
|
page += 1
|
|
|
|
logger.info(f"Fetched {len(all_tickets)} pending tickets")
|
|
|
|
# Fetch open tickets
|
|
logger.info("Fetching open tickets...")
|
|
page = 1
|
|
while True:
|
|
result = self.get_tickets(page_number=page, status='open', is_group=False)
|
|
|
|
if not result or not result.get('tickets'):
|
|
break
|
|
|
|
all_tickets.extend(result.get('tickets', []))
|
|
|
|
if not result.get('hasMore', False):
|
|
break
|
|
|
|
page += 1
|
|
|
|
logger.info(f"Fetched {len(all_tickets)} open tickets (total so far: {len(all_tickets)})")
|
|
|
|
# Fetch group tickets
|
|
logger.info("Fetching group tickets...")
|
|
page = 1
|
|
while True:
|
|
result = self.get_tickets(page_number=page, status='group', is_group=True)
|
|
|
|
if not result or not result.get('tickets'):
|
|
break
|
|
|
|
all_tickets.extend(result.get('tickets', []))
|
|
|
|
if not result.get('hasMore', False):
|
|
break
|
|
|
|
page += 1
|
|
|
|
logger.info(f"Total tickets fetched (pending + open + group): {len(all_tickets)}")
|
|
return all_tickets
|
|
def get_dashboard_resume(self, date_from: str, date_to: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Fetch dashboard resume data from the API
|
|
|
|
Args:
|
|
date_from: Start date in format YYYY-MM-DD
|
|
date_to: End date in format YYYY-MM-DD
|
|
|
|
Returns:
|
|
dict: Dashboard resume data if successful, None otherwise
|
|
"""
|
|
if not self.token:
|
|
logger.error("Not authenticated. Please login first.")
|
|
return None
|
|
|
|
try:
|
|
resume_url = f"{self.base_url}{Config.API_DASHBOARD_RESUME_ENDPOINT}"
|
|
|
|
params = {
|
|
'dateFrom': date_from,
|
|
'dateTo': date_to
|
|
}
|
|
|
|
logger.info(f"Fetching dashboard resume from {resume_url} with params: {params}")
|
|
response = self.session.get(
|
|
resume_url,
|
|
params=params,
|
|
timeout=15
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
logger.info(f"Successfully fetched dashboard resume")
|
|
return response.json()
|
|
else:
|
|
logger.error(f"Failed to fetch dashboard resume: {response.status_code} - {response.text}")
|
|
return None
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Error fetching dashboard resume: {str(e)}")
|
|
return None
|
|
|
|
def get_open_tickets(self) -> List[Dict[str, Any]]:
|
|
"""
|
|
Fetch all open tickets sorted by duration (ascending)
|
|
|
|
Returns:
|
|
list: List of open ticket dictionaries
|
|
"""
|
|
if not self.token:
|
|
logger.error("Not authenticated. Please login first.")
|
|
return []
|
|
|
|
all_tickets = []
|
|
page = 1
|
|
expected_total = None
|
|
|
|
try:
|
|
import json
|
|
|
|
queue_ids = Config.get_queue_ids_list()
|
|
tickets_url = f"{self.base_url}{Config.API_TICKETS_ENDPOINT}"
|
|
|
|
while True:
|
|
# Use showAll=true and paginate until all open tickets are fetched
|
|
params = {
|
|
'pageNumber': page,
|
|
'status': 'open',
|
|
'showAll': 'true',
|
|
'queueIds': json.dumps(queue_ids),
|
|
'tagIds': '[]',
|
|
'isGroup': 'false',
|
|
'sortDir': 'ASC',
|
|
'isSearching': 'false'
|
|
}
|
|
|
|
logger.info(f"Fetching open tickets from {tickets_url} with params: {params}")
|
|
response = self.session.get(
|
|
tickets_url,
|
|
params=params,
|
|
timeout=15
|
|
)
|
|
|
|
if response.status_code != 200:
|
|
logger.error(f"Failed to fetch open tickets: {response.status_code} - {response.text}")
|
|
break
|
|
|
|
result = response.json()
|
|
page_tickets = result.get('tickets', [])
|
|
|
|
if expected_total is None and isinstance(result.get('count'), int):
|
|
expected_total = result.get('count')
|
|
|
|
if not page_tickets:
|
|
break
|
|
|
|
all_tickets.extend(page_tickets)
|
|
|
|
has_more = result.get('hasMore')
|
|
if isinstance(has_more, bool):
|
|
if not has_more:
|
|
break
|
|
elif expected_total is not None:
|
|
if len(all_tickets) >= expected_total:
|
|
break
|
|
else:
|
|
break
|
|
|
|
page += 1
|
|
|
|
logger.info(f"Fetched {len(all_tickets)} open tickets (all pages)")
|
|
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Error fetching open tickets: {str(e)}")
|
|
|
|
return all_tickets
|
|
|
|
def get_total_open_tickets(self) -> int:
|
|
"""
|
|
Fetch total number of open tickets using full pagination
|
|
|
|
Returns:
|
|
int: Total number of open tickets
|
|
"""
|
|
if not self.token:
|
|
logger.error("Not authenticated. Please login first.")
|
|
return 0
|
|
|
|
open_tickets = self.get_open_tickets()
|
|
total_open = len(open_tickets)
|
|
logger.info(f"Fetched total open tickets: {total_open}")
|
|
return total_open
|
|
|
|
def get_closed_tickets_with_low_rate(
|
|
self,
|
|
min_rate: float = 5,
|
|
limit: int = 30,
|
|
max_pages: int = 15
|
|
) -> List[Dict[str, Any]]:
|
|
"""
|
|
Fetch recent closed tickets with customer rate below a threshold.
|
|
|
|
Args:
|
|
min_rate: Maximum accepted score is min_rate - epsilon (default: < 5)
|
|
limit: Maximum number of tickets to return
|
|
max_pages: Maximum number of API pages to scan
|
|
|
|
Returns:
|
|
list: Closed tickets with low ratings
|
|
"""
|
|
if not self.token:
|
|
logger.error("Not authenticated. Please login first.")
|
|
return []
|
|
|
|
low_rated_tickets: List[Dict[str, Any]] = []
|
|
page = 1
|
|
expected_total = None
|
|
|
|
try:
|
|
import json
|
|
|
|
queue_ids = Config.get_queue_ids_list()
|
|
tickets_url = f"{self.base_url}{Config.API_TICKETS_ENDPOINT}"
|
|
|
|
while page <= max_pages and len(low_rated_tickets) < limit:
|
|
params = {
|
|
'pageNumber': page,
|
|
'status': 'closed',
|
|
'showAll': 'true',
|
|
'queueIds': json.dumps(queue_ids),
|
|
'tagIds': '[]',
|
|
'isGroup': 'false',
|
|
'sortDir': 'DESC',
|
|
'isSearching': 'false'
|
|
}
|
|
|
|
logger.info(f"Fetching closed tickets from {tickets_url} with params: {params}")
|
|
response = self.session.get(
|
|
tickets_url,
|
|
params=params,
|
|
timeout=15
|
|
)
|
|
|
|
if response.status_code != 200:
|
|
logger.error(f"Failed to fetch closed tickets: {response.status_code} - {response.text}")
|
|
break
|
|
|
|
result = response.json()
|
|
page_tickets = result.get('tickets', [])
|
|
|
|
if expected_total is None and isinstance(result.get('count'), int):
|
|
expected_total = result.get('count')
|
|
|
|
if not page_tickets:
|
|
break
|
|
|
|
for ticket in page_tickets:
|
|
rate = ticket.get('rate')
|
|
if rate is None:
|
|
continue
|
|
|
|
try:
|
|
numeric_rate = float(rate)
|
|
except (TypeError, ValueError):
|
|
continue
|
|
|
|
if numeric_rate < min_rate:
|
|
low_rated_tickets.append(ticket)
|
|
if len(low_rated_tickets) >= limit:
|
|
break
|
|
|
|
has_more = result.get('hasMore')
|
|
if isinstance(has_more, bool):
|
|
if not has_more:
|
|
break
|
|
elif expected_total is not None:
|
|
scanned = page * len(page_tickets)
|
|
if scanned >= expected_total:
|
|
break
|
|
else:
|
|
break
|
|
|
|
page += 1
|
|
|
|
logger.info(
|
|
f"Fetched {len(low_rated_tickets)} closed tickets with rate below {min_rate} "
|
|
f"(scanned up to page {page})"
|
|
)
|
|
except requests.exceptions.RequestException as e:
|
|
logger.error(f"Error fetching closed tickets with low rate: {str(e)}")
|
|
|
|
return low_rated_tickets
|