diff --git a/grafana/provisioning/dashboards/monitoring-dashboard.json b/grafana/provisioning/dashboards/monitoring-dashboard.json index 98d6b8e..c38804f 100644 --- a/grafana/provisioning/dashboards/monitoring-dashboard.json +++ b/grafana/provisioning/dashboards/monitoring-dashboard.json @@ -203,7 +203,7 @@ }, "gridPos": { "h": 7, - "w": 4, + "w": 5, "x": 8, "y": 4 }, @@ -270,7 +270,7 @@ "gridPos": { "h": 7, "w": 4, - "x": 12, + "x": 13, "y": 4 }, "id": 7, @@ -382,8 +382,8 @@ }, "gridPos": { "h": 7, - "w": 8, - "x": 16, + "w": 7, + "x": 17, "y": 4 }, "id": 8, @@ -588,132 +588,6 @@ ], "type": "table" }, - { - "datasource": { - "type": "prometheus", - "uid": "PBFA97CFB590B2093" - }, - "fieldConfig": { - "defaults": { - "custom": { - "align": "center", - "cellOptions": { - "type": "auto" - }, - "footer": { - "reducers": [] - }, - "inspect": false - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "red", - "value": 0 - }, - { - "color": "orange", - "value": 3 - }, - { - "color": "yellow", - "value": 4 - }, - { - "color": "green", - "value": 5 - } - ] - } - }, - "overrides": [ - { - "matcher": { - "id": "byName", - "options": "Value" - }, - "properties": [ - { - "id": "custom.cellOptions", - "value": { - "type": "color-background" - } - }, - { - "id": "decimals", - "value": 1 - }, - { - "id": "custom.width", - "value": 90 - } - ] - } - ] - }, - "gridPos": { - "h": 4, - "w": 12, - "x": 0, - "y": 19 - }, - "id": 13, - "options": { - "cellHeight": "sm", - "showHeader": true, - "sortBy": [ - { - "desc": false, - "displayName": "Nota" - } - ] - }, - "pluginVersion": "12.3.2", - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "PBFA97CFB590B2093" - }, - "expr": "closed_ticket_rate_below_5", - "format": "table", - "instant": true, - "refId": "A" - } - ], - "title": "Avaliações abaixo de 5 (Hoje)", - "transformations": [ - { - "id": "organize", - "options": { - "excludeByName": { - "Time": true, - "__name__": true, - "instance": true, - "job": true, - "ticket_id": true - }, - "indexByName": { - "Value": 3, - "closed_at": 4, - "contact_name": 0, - "queue": 2, - "user_name": 1 - }, - "renameByName": { - "Value": "Nota", - "closed_at": "Fechado em", - "contact_name": "Cliente", - "queue": "TAG", - "user_name": "Atendente" - } - } - } - ], - "type": "table" - }, { "fieldConfig": { "defaults": { @@ -855,6 +729,132 @@ ], "type": "table" }, + { + "datasource": { + "type": "prometheus", + "uid": "PBFA97CFB590B2093" + }, + "fieldConfig": { + "defaults": { + "custom": { + "align": "center", + "cellOptions": { + "type": "auto" + }, + "footer": { + "reducers": [] + }, + "inspect": false + }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "red", + "value": 0 + }, + { + "color": "orange", + "value": 3 + }, + { + "color": "yellow", + "value": 4 + }, + { + "color": "green", + "value": 5 + } + ] + } + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "Value" + }, + "properties": [ + { + "id": "custom.cellOptions", + "value": { + "type": "color-background" + } + }, + { + "id": "decimals", + "value": 1 + }, + { + "id": "custom.width", + "value": 90 + } + ] + } + ] + }, + "gridPos": { + "h": 4, + "w": 12, + "x": 0, + "y": 19 + }, + "id": 13, + "options": { + "cellHeight": "sm", + "showHeader": true, + "sortBy": [ + { + "desc": true, + "displayName": "Fechado em" + } + ] + }, + "pluginVersion": "12.3.2", + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "PBFA97CFB590B2093" + }, + "expr": "closed_ticket_rate_below_5", + "format": "table", + "instant": true, + "refId": "A" + } + ], + "title": "Avaliações abaixo de 5 (Hoje)", + "transformations": [ + { + "id": "organize", + "options": { + "excludeByName": { + "Time": true, + "__name__": true, + "instance": true, + "job": true, + "ticket_id": true + }, + "indexByName": { + "Value": 3, + "closed_at": 4, + "contact_name": 0, + "queue": 2, + "user_name": 1 + }, + "renameByName": { + "Value": "Nota", + "closed_at": "Fechado em", + "contact_name": "Cliente", + "queue": "TAG", + "user_name": "Atendente" + } + } + } + ], + "type": "table" + }, { "datasource": { "type": "prometheus", @@ -932,7 +932,7 @@ "properties": [ { "id": "custom.width", - "value": 860 + "value": 1004 } ] } @@ -1012,8 +1012,8 @@ "to": "now" }, "timepicker": {}, - "timezone": "", + "timezone": "browser", "title": "Monitoramento de Atendimento", "uid": "monitoring-tickets", - "version": 6 + "version": 14 } \ No newline at end of file diff --git a/src/data_formatter.py b/src/data_formatter.py index 31d8303..f702f0b 100644 --- a/src/data_formatter.py +++ b/src/data_formatter.py @@ -1,11 +1,41 @@ import logging from typing import List, Dict, Any, Optional -from datetime import datetime +from datetime import datetime, timedelta, timezone +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError logger = logging.getLogger(__name__) +try: + LOCAL_TIMEZONE = ZoneInfo('America/Sao_Paulo') +except ZoneInfoNotFoundError: + logger.warning("Timezone database unavailable, using UTC-03:00 fallback") + LOCAL_TIMEZONE = timezone(timedelta(hours=-3)) + class DataFormatter: """Formats ticket data for Grafana consumption""" + + @staticmethod + def _parse_api_datetime(value: Any) -> Optional[datetime]: + """Parse API datetime strings as timezone-aware UTC values.""" + if not isinstance(value, str) or not value: + return None + + try: + parsed = datetime.fromisoformat(value.replace('Z', '+00:00')) + except ValueError: + return None + + if parsed.tzinfo is None: + return parsed.replace(tzinfo=timezone.utc) + return parsed + + @staticmethod + def _to_local_iso(value: Any) -> Any: + """Convert API datetime strings to local timezone ISO format.""" + parsed = DataFormatter._parse_api_datetime(value) + if not parsed: + return value + return parsed.astimezone(LOCAL_TIMEZONE).isoformat(timespec='seconds') @staticmethod def format_tickets_for_json(tickets: List[Dict[str, Any]]) -> Dict[str, Any]: @@ -320,7 +350,7 @@ class DataFormatter: list: Formatted list sorted by lower score first """ formatted_tickets = [] - today = datetime.now().date() + today = datetime.now(LOCAL_TIMEZONE).date() for ticket in tickets: try: @@ -349,10 +379,10 @@ class DataFormatter: if only_today: closed_date = None - try: - closed_datetime = datetime.fromisoformat(updated_at.replace('Z', '+00:00')) - closed_date = closed_datetime.date() - except (ValueError, AttributeError): + parsed_closed_datetime = DataFormatter._parse_api_datetime(updated_at) + if parsed_closed_datetime: + closed_date = parsed_closed_datetime.astimezone(LOCAL_TIMEZONE).date() + else: # Fallback for unexpected formats that still start with YYYY-MM-DD. if isinstance(updated_at, str) and len(updated_at) >= 10: try: @@ -392,7 +422,7 @@ class DataFormatter: 'user_name': user_name, 'queue': queue_name or 'Sem fila', 'rate': rate_value, - 'updated_at': updated_at + 'updated_at': DataFormatter._to_local_iso(updated_at) }) except Exception as e: logger.error(f"Error formatting low-rated closed ticket {ticket.get('id')}: {str(e)}")