feat: paginate emails list in API and admin UI

Return total count with offset/limit from GET /messages and add
Anterior/Seguinte controls showing 25 rows per page.
This commit is contained in:
1sonhador committed 2026-07-01 09:19:17 +01:00
1 parent b070af8503
commit f55a38c032
4 files changed
+160 -79

No files matched your search

+10 -3
View File
@@ -58,6 +58,13 @@ export interface Message {
forwarded_at: string | null
}
export interface MessageList {
items: Message[]
total: number
limit: number
offset: number
}
export interface Stats {
accounts_total: number
accounts_active: number
@@ -131,9 +138,9 @@ export const api = {
const q = new URLSearchParams()
if (params?.account_id) q.set('account_id', String(params.account_id))
if (params?.status) q.set('status', params.status)
if (params?.limit) q.set('limit', String(params.limit))
if (params?.offset) q.set('offset', String(params.offset))
return request<Message[]>(`/messages${q.toString() ? '?' + q : ''}`)
if (params?.limit != null) q.set('limit', String(params.limit))
if (params?.offset != null) q.set('offset', String(params.offset))
return request<MessageList>(`/messages${q.toString() ? '?' + q : ''}`)
},
retry: (id: number) => request<void>(`/messages/${id}/retry`, { method: 'POST' }),
},
+112 -59
View File
@@ -1,19 +1,39 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { api, Message } from '../lib/api'
import { useAsync } from '../hooks/useApi'
import Spinner from '../components/Spinner'
import StatusBadge from '../components/StatusBadge'
import { RefreshCw, RotateCcw } from 'lucide-react'
import { ChevronLeft, ChevronRight, RefreshCw, RotateCcw } from 'lucide-react'
const PAGE_SIZE = 25
export default function Emails() {
const [filterStatus, setFilterStatus] = useState('')
const [page, setPage] = useState(0)
const [retryingId, setRetryingId] = useState<number | null>(null)
const { data: messages, loading, error, reload } = useAsync<Message[]>(
() => api.messages.list({ status: filterStatus || undefined, limit: 100 }),
[filterStatus],
useEffect(() => {
setPage(0)
}, [filterStatus])
const { data, loading, error, reload } = useAsync(
() =>
api.messages.list({
status: filterStatus || undefined,
limit: PAGE_SIZE,
offset: page * PAGE_SIZE,
}),
[filterStatus, page],
)
const messages = data?.items
const total = data?.total ?? 0
const pageStart = total === 0 ? 0 : page * PAGE_SIZE + 1
const pageEnd = Math.min((page + 1) * PAGE_SIZE, total)
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
const canPrev = page > 0
const canNext = (page + 1) * PAGE_SIZE < total
const handleRetry = async (id: number) => {
setRetryingId(id)
try {
@@ -62,67 +82,100 @@ export default function Emails() {
</div>
)}
{messages && messages.length === 0 && (
{messages && messages.length === 0 && !loading && (
<div className="text-center py-12 text-gray-400 text-sm">
Nenhuma mensagem{filterStatus ? ` com estado "${filterStatus}"` : ''}.
</div>
)}
{messages && messages.length > 0 && (
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Recebido</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{messages.map((m) => (
<tr key={m.id} className="hover:bg-gray-50">
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
<td className="px-4 py-3 font-medium truncate max-w-xs" title={m.subject}>
{m.subject || '(sem assunto)'}
</td>
<td className="px-4 py-3 text-gray-600 text-xs truncate max-w-[180px]">{m.sender}</td>
<td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
{new Date(m.received_at).toLocaleString('pt-PT')}
</td>
<td className="px-4 py-3">
<div>
<StatusBadge status={m.status} />
{m.error && (
<p className="text-xs text-red-500 mt-0.5 truncate max-w-xs" title={m.error}>
{m.error}
</p>
)}
</div>
</td>
<td className="px-4 py-3 text-right">
{m.status === 'failed' && (
<button
title="Tentar novamente"
onClick={() => handleRetry(m.id)}
disabled={retryingId === m.id}
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
>
{retryingId === m.id ? (
<Spinner className="h-4 w-4" />
) : (
<RotateCcw size={14} />
)}
</button>
)}
</td>
<>
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Recebido</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
</tr>
))}
</tbody>
</table>
</div>
</thead>
<tbody className="divide-y divide-gray-100">
{messages.map((m: Message) => (
<tr key={m.id} className="hover:bg-gray-50">
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
<td className="px-4 py-3 font-medium truncate max-w-xs" title={m.subject}>
{m.subject || '(sem assunto)'}
</td>
<td className="px-4 py-3 text-gray-600 text-xs truncate max-w-[180px]">{m.sender}</td>
<td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
{new Date(m.received_at).toLocaleString('pt-PT')}
</td>
<td className="px-4 py-3">
<div>
<StatusBadge status={m.status} />
{m.error && (
<p className="text-xs text-red-500 mt-0.5 truncate max-w-xs" title={m.error}>
{m.error}
</p>
)}
</div>
</td>
<td className="px-4 py-3 text-right">
{m.status === 'failed' && (
<button
title="Tentar novamente"
onClick={() => handleRetry(m.id)}
disabled={retryingId === m.id}
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
>
{retryingId === m.id ? (
<Spinner className="h-4 w-4" />
) : (
<RotateCcw size={14} />
)}
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="flex items-center justify-between mt-4 text-sm text-gray-600">
<span>
{total === 0
? '0 mensagens'
: `${pageStart}–${pageEnd} de ${total} mensagem${total === 1 ? '' : 's'}`}
</span>
<div className="flex items-center gap-2">
<span className="text-xs text-gray-400">
Página {page + 1} de {totalPages}
</span>
<button
type="button"
onClick={() => setPage((p) => p - 1)}
disabled={!canPrev || loading}
className="flex items-center gap-1 px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
>
<ChevronLeft size={14} />
Anterior
</button>
<button
type="button"
onClick={() => setPage((p) => p + 1)}
disabled={!canNext || loading}
className="flex items-center gap-1 px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
>
Seguinte
<ChevronRight size={14} />
</button>
</div>
</div>
</>
)}
</div>
)
+31 -17
View File
@@ -1,9 +1,10 @@
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Query
from sqlalchemy import func
from forwarder.api.deps import CurrentUser, DbSession
from forwarder.api.schemas import MessageResponse
from forwarder.api.schemas import MessageListResponse, MessageResponse
from forwarder.db.models import Account, Message, MessageStatus
from forwarder.services.sync_service import retry_single_message
@@ -39,33 +40,46 @@ def _build_message_response(m: Message, account_name: str) -> MessageResponse:
)
@router.get("", response_model=list[MessageResponse])
@router.get("", response_model=MessageListResponse)
def list_messages(
db: DbSession,
_user: CurrentUser,
account_id: int | None = Query(default=None),
status: str | None = Query(default=None),
limit: int = Query(default=100, ge=1, le=500),
limit: int = Query(default=50, ge=1, le=500),
offset: int = Query(default=0, ge=0),
) -> list[MessageResponse]:
query = (
db.query(Message, Account.name)
.join(Account, Message.account_id == Account.id)
.order_by(Message.id.desc())
)
if account_id is not None:
query = query.filter(Message.account_id == account_id)
) -> MessageListResponse:
status_enum: MessageStatus | None = None
if status is not None:
try:
status_enum = MessageStatus(status)
except ValueError:
return []
query = query.filter(Message.status == status_enum)
return MessageListResponse(items=[], total=0, limit=limit, offset=offset)
rows = query.offset(offset).limit(limit).all()
return [_build_message_response(m, name) for m, name in rows]
filters = []
if account_id is not None:
filters.append(Message.account_id == account_id)
if status_enum is not None:
filters.append(Message.status == status_enum)
total = db.query(func.count(Message.id)).filter(*filters).scalar() or 0
rows = (
db.query(Message, Account.name)
.join(Account, Message.account_id == Account.id)
.filter(*filters)
.order_by(Message.id.desc())
.offset(offset)
.limit(limit)
.all()
)
return MessageListResponse(
items=[_build_message_response(m, name) for m, name in rows],
total=total,
limit=limit,
offset=offset,
)
@router.post("/{message_id}/retry", response_model=MessageResponse)
+7
View File
@@ -145,6 +145,13 @@ class MessageResponse(BaseModel):
updated_at: datetime
class MessageListResponse(BaseModel):
items: list[MessageResponse]
total: int
limit: int
offset: int
class SyncRunResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)