fix: timezone and Monthly call
Some checks failed
Deploy / deploy (push) Has been cancelled

This commit is contained in:
2026-03-13 17:51:12 -03:00
parent d0783499e1
commit 337cca2ea5
2 changed files with 170 additions and 140 deletions

View File

@@ -203,7 +203,7 @@
}, },
"gridPos": { "gridPos": {
"h": 7, "h": 7,
"w": 4, "w": 5,
"x": 8, "x": 8,
"y": 4 "y": 4
}, },
@@ -270,7 +270,7 @@
"gridPos": { "gridPos": {
"h": 7, "h": 7,
"w": 4, "w": 4,
"x": 12, "x": 13,
"y": 4 "y": 4
}, },
"id": 7, "id": 7,
@@ -382,8 +382,8 @@
}, },
"gridPos": { "gridPos": {
"h": 7, "h": 7,
"w": 8, "w": 7,
"x": 16, "x": 17,
"y": 4 "y": 4
}, },
"id": 8, "id": 8,
@@ -588,132 +588,6 @@
], ],
"type": "table" "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": { "fieldConfig": {
"defaults": { "defaults": {
@@ -855,6 +729,132 @@
], ],
"type": "table" "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": { "datasource": {
"type": "prometheus", "type": "prometheus",
@@ -932,7 +932,7 @@
"properties": [ "properties": [
{ {
"id": "custom.width", "id": "custom.width",
"value": 860 "value": 1004
} }
] ]
} }
@@ -1012,8 +1012,8 @@
"to": "now" "to": "now"
}, },
"timepicker": {}, "timepicker": {},
"timezone": "", "timezone": "browser",
"title": "Monitoramento de Atendimento", "title": "Monitoramento de Atendimento",
"uid": "monitoring-tickets", "uid": "monitoring-tickets",
"version": 6 "version": 14
} }

View File

@@ -1,12 +1,42 @@
import logging import logging
from typing import List, Dict, Any, Optional 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__) 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: class DataFormatter:
"""Formats ticket data for Grafana consumption""" """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 @staticmethod
def format_tickets_for_json(tickets: List[Dict[str, Any]]) -> Dict[str, Any]: 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 list: Formatted list sorted by lower score first
""" """
formatted_tickets = [] formatted_tickets = []
today = datetime.now().date() today = datetime.now(LOCAL_TIMEZONE).date()
for ticket in tickets: for ticket in tickets:
try: try:
@@ -349,10 +379,10 @@ class DataFormatter:
if only_today: if only_today:
closed_date = None closed_date = None
try: parsed_closed_datetime = DataFormatter._parse_api_datetime(updated_at)
closed_datetime = datetime.fromisoformat(updated_at.replace('Z', '+00:00')) if parsed_closed_datetime:
closed_date = closed_datetime.date() closed_date = parsed_closed_datetime.astimezone(LOCAL_TIMEZONE).date()
except (ValueError, AttributeError): else:
# Fallback for unexpected formats that still start with YYYY-MM-DD. # Fallback for unexpected formats that still start with YYYY-MM-DD.
if isinstance(updated_at, str) and len(updated_at) >= 10: if isinstance(updated_at, str) and len(updated_at) >= 10:
try: try:
@@ -392,7 +422,7 @@ class DataFormatter:
'user_name': user_name, 'user_name': user_name,
'queue': queue_name or 'Sem fila', 'queue': queue_name or 'Sem fila',
'rate': rate_value, 'rate': rate_value,
'updated_at': updated_at 'updated_at': DataFormatter._to_local_iso(updated_at)
}) })
except Exception as e: except Exception as e:
logger.error(f"Error formatting low-rated closed ticket {ticket.get('id')}: {str(e)}") logger.error(f"Error formatting low-rated closed ticket {ticket.get('id')}: {str(e)}")