Merge branch 'main' into task/BIT-26141-fix-test-endpoint
This commit is contained in:
commit
f165f411d9
7 files changed
+141
-20
No files matched your search
@@ -160,10 +160,17 @@ export const api = {
|
||||
},
|
||||
},
|
||||
messages: {
|
||||
list: (params?: { account_id?: number; status?: string; limit?: number; offset?: number }) => {
|
||||
list: (params?: {
|
||||
account_id?: number
|
||||
status?: string
|
||||
q?: string
|
||||
limit?: number
|
||||
offset?: number
|
||||
}) => {
|
||||
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?.q) q.set('q', params.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 : ''}`)
|
||||
|
||||
@@ -9,7 +9,11 @@ const DEFAULT_TEST_BATCH = 5
|
||||
|
||||
function formatSyncResult(r: import('../lib/api').SyncRunResult): string {
|
||||
const mode = r.dry_run ? 'Dry-run' : 'Sync'
|
||||
return `${mode}: ${r.messages_forwarded} enviados, ${r.messages_failed} falhas, ${r.messages_matched} match (${r.messages_scanned} lidos)`
|
||||
const limit =
|
||||
r.max_emails != null ? ` (limite teste: ${r.max_emails} lidos)` : ' (completo)'
|
||||
const skipped =
|
||||
r.messages_skipped > 0 ? `, ${r.messages_skipped} já conhecidos` : ''
|
||||
return `${mode}${limit}: ${r.messages_forwarded} enviados, ${r.messages_failed} falhas, ${r.messages_matched} match${skipped} — ${r.messages_scanned} lidos`
|
||||
}
|
||||
|
||||
const EMPTY_FORM: AccountCreate = {
|
||||
@@ -305,11 +309,12 @@ export default function Accounts() {
|
||||
{accounts && accounts.length > 0 && (
|
||||
<div className="mb-4 flex flex-wrap items-center gap-3 text-sm text-gray-600 bg-blue-50 border border-blue-100 rounded-md px-4 py-3">
|
||||
<span>
|
||||
O worker automático só corre com <strong>Conta activa</strong>. Os botões ▶/🧪/↻
|
||||
abaixo são sync <strong>manual</strong> (funcionam mesmo com conta inactiva).
|
||||
O worker automático só corre com <strong>Conta activa</strong>.{' '}
|
||||
<strong>▶</strong> testa os primeiros N emails;{' '}
|
||||
<strong>↻</strong> sync completo (toda a mailbox).
|
||||
</span>
|
||||
<label className="flex items-center gap-1.5 ml-auto">
|
||||
Limite teste:
|
||||
Emails no teste ▶:
|
||||
<input
|
||||
type="number"
|
||||
min={1}
|
||||
@@ -372,7 +377,7 @@ export default function Accounts() {
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center justify-end gap-1 flex-wrap">
|
||||
<button
|
||||
title={`Sync teste (${testBatchSize})`}
|
||||
title={`Teste: ler no máximo ${testBatchSize} emails (não é sync completo)`}
|
||||
onClick={() => handleSync(a.id, { max_emails: testBatchSize })}
|
||||
disabled={syncingId === a.id}
|
||||
className="p-1.5 text-gray-400 hover:text-green-600 disabled:opacity-40"
|
||||
@@ -394,7 +399,7 @@ export default function Accounts() {
|
||||
<FlaskConical size={14} />
|
||||
</button>
|
||||
<button
|
||||
title="Sync completo"
|
||||
title="Sync completo — percorre todas as pastas IMAP"
|
||||
onClick={() => handleSync(a.id, {}, true)}
|
||||
disabled={syncingId === a.id}
|
||||
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
|
||||
|
||||
@@ -3,7 +3,7 @@ import { api, Message } from '../lib/api'
|
||||
import { useAsync } from '../hooks/useApi'
|
||||
import Spinner from '../components/Spinner'
|
||||
import StatusBadge from '../components/StatusBadge'
|
||||
import { ChevronLeft, ChevronRight, RefreshCw, RotateCcw } from 'lucide-react'
|
||||
import { ChevronLeft, ChevronRight, RefreshCw, RotateCcw, Search, X } from 'lucide-react'
|
||||
|
||||
const PAGE_SIZE = 25
|
||||
|
||||
@@ -17,6 +17,8 @@ function formatMessageKey(key: string): string {
|
||||
|
||||
export default function Emails() {
|
||||
const [filterStatus, setFilterStatus] = useState('')
|
||||
const [searchInput, setSearchInput] = useState('')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [page, setPage] = useState(0)
|
||||
const [retryingId, setRetryingId] = useState<number | null>(null)
|
||||
const [actionMsg, setActionMsg] = useState<{ ok: boolean; text: string } | null>(null)
|
||||
@@ -35,16 +37,22 @@ export default function Emails() {
|
||||
loadQueueStatus()
|
||||
const t = setInterval(loadQueueStatus, 30_000)
|
||||
return () => clearInterval(t)
|
||||
}, [filterStatus, page])
|
||||
}, [filterStatus, page, searchQuery])
|
||||
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setSearchQuery(searchInput.trim()), 300)
|
||||
return () => clearTimeout(t)
|
||||
}, [searchInput])
|
||||
|
||||
const { data, loading, error, reload } = useAsync(
|
||||
() =>
|
||||
api.messages.list({
|
||||
status: filterStatus || undefined,
|
||||
q: searchQuery || undefined,
|
||||
limit: PAGE_SIZE,
|
||||
offset: page * PAGE_SIZE,
|
||||
}),
|
||||
[filterStatus, page],
|
||||
[filterStatus, page, searchQuery],
|
||||
)
|
||||
|
||||
const messages = data?.items
|
||||
@@ -100,7 +108,7 @@ export default function Emails() {
|
||||
|
||||
useEffect(() => {
|
||||
setPage(0)
|
||||
}, [filterStatus])
|
||||
}, [filterStatus, searchQuery])
|
||||
|
||||
const handleRequeueAll = async () => {
|
||||
const forwarded = queueInfo
|
||||
@@ -237,6 +245,34 @@ export default function Emails() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4 flex items-center gap-2 max-w-xl">
|
||||
<div className="relative flex-1">
|
||||
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||
<input
|
||||
type="search"
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
placeholder="Pesquisar assunto, remetente, pasta, Message-ID ou #id…"
|
||||
className="w-full pl-9 pr-9 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||
/>
|
||||
{searchInput && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSearchInput('')}
|
||||
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600"
|
||||
title="Limpar pesquisa"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{searchQuery && (
|
||||
<span className="text-xs text-gray-500 whitespace-nowrap">
|
||||
{total} resultado{total === 1 ? '' : 's'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{queueInfo && (queueInfo.pending > 0 || queueInfo.forwards_used_last_hour > 0) && (
|
||||
<div className="mb-4 px-4 py-3 rounded-md text-sm border bg-sky-50 border-sky-200 text-sky-900">
|
||||
<strong>Fila de reenvio:</strong> {queueInfo.pending} pendente
|
||||
@@ -278,7 +314,9 @@ export default function Emails() {
|
||||
|
||||
{messages && messages.length === 0 && !loading && (
|
||||
<div className="text-center py-12 text-gray-400 text-sm">
|
||||
Nenhuma mensagem{filterStatus ? ` com estado "${filterStatus}"` : ''}.
|
||||
Nenhuma mensagem
|
||||
{searchQuery ? ` para "${searchQuery}"` : ''}
|
||||
{filterStatus ? ` com estado "${filterStatus}"` : ''}.
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ from sqlalchemy import func
|
||||
from forwarder.api.deps import CurrentUser, DbSession
|
||||
from forwarder.api.schemas import MessageListResponse, MessageResponse
|
||||
from forwarder.db.models import Account, Message, MessageStatus
|
||||
from forwarder.services.message_search import build_message_search_filter
|
||||
from forwarder.services.forward_queue_service import (
|
||||
get_queue_status,
|
||||
process_forward_queue,
|
||||
@@ -59,6 +60,7 @@ def list_messages(
|
||||
_user: CurrentUser,
|
||||
account_id: int | None = Query(default=None),
|
||||
status: str | None = Query(default=None),
|
||||
q: str | None = Query(default=None, min_length=1, max_length=200),
|
||||
limit: int = Query(default=50, ge=1, le=500),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
) -> MessageListResponse:
|
||||
@@ -74,6 +76,9 @@ def list_messages(
|
||||
filters.append(Message.account_id == account_id)
|
||||
if status_enum is not None:
|
||||
filters.append(Message.status == status_enum)
|
||||
search_filter = build_message_search_filter(q)
|
||||
if search_filter is not None:
|
||||
filters.append(search_filter)
|
||||
|
||||
total = db.query(func.count(Message.id)).filter(*filters).scalar() or 0
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Message list search helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import ColumnElement, or_
|
||||
|
||||
from forwarder.db.models import Message
|
||||
|
||||
|
||||
def build_message_search_filter(term: str | None) -> ColumnElement[bool] | None:
|
||||
if term is None:
|
||||
return None
|
||||
cleaned = term.strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
|
||||
escaped = cleaned.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
pattern = f"%{escaped}%"
|
||||
clauses = [
|
||||
Message.subject.like(pattern, escape="\\"),
|
||||
Message.from_addr.like(pattern, escape="\\"),
|
||||
Message.folder.like(pattern, escape="\\"),
|
||||
Message.message_key.like(pattern, escape="\\"),
|
||||
Message.uid.like(pattern, escape="\\"),
|
||||
]
|
||||
if cleaned.isdigit():
|
||||
clauses.append(Message.id == int(cleaned))
|
||||
return or_(*clauses)
|
||||
@@ -170,7 +170,6 @@ def sync_account(
|
||||
|
||||
allowed_extensions = set(account.allowed_extensions or [])
|
||||
processed_keys = _get_known_message_keys(db, account_id)
|
||||
handled_count = 0
|
||||
stop_all = False
|
||||
|
||||
imap = connect_imap(imap_config)
|
||||
@@ -208,7 +207,7 @@ def sync_account(
|
||||
uids = data[0].split()
|
||||
|
||||
for uid in uids:
|
||||
if max_emails is not None and handled_count >= max_emails:
|
||||
if max_emails is not None and result.messages_scanned >= max_emails:
|
||||
stop_all = True
|
||||
break
|
||||
|
||||
@@ -261,7 +260,6 @@ def sync_account(
|
||||
)
|
||||
processed_keys.add(message_key)
|
||||
result.messages_forwarded += 1
|
||||
handled_count += 1
|
||||
logger.info("DRY_RUN matched: %s", subject)
|
||||
continue
|
||||
|
||||
@@ -291,12 +289,33 @@ def sync_account(
|
||||
)
|
||||
processed_keys.add(message_key)
|
||||
result.messages_forwarded += 1
|
||||
handled_count += 1
|
||||
logger.info("Forwarded: %s", subject)
|
||||
except ForwardRateLimitError as exc:
|
||||
logger.warning("Hourly forward limit reached, stopping sync: %s", exc)
|
||||
stop_all = True
|
||||
break
|
||||
logger.warning(
|
||||
"Hourly forward limit reached, skipping forward (scan continues): %s",
|
||||
exc,
|
||||
)
|
||||
message_row = _upsert_message(
|
||||
db,
|
||||
account_id=account_id,
|
||||
message_key=message_key,
|
||||
folder=folder,
|
||||
uid=uid_str,
|
||||
subject=subject,
|
||||
from_addr=from_addr,
|
||||
date=date,
|
||||
status=MessageStatus.failed,
|
||||
error_message=str(exc),
|
||||
)
|
||||
_record_forward_attempt(
|
||||
db,
|
||||
message=message_row,
|
||||
success=False,
|
||||
dry_run=False,
|
||||
error_message=str(exc),
|
||||
)
|
||||
processed_keys.add(message_key)
|
||||
result.messages_failed += 1
|
||||
except Exception as exc:
|
||||
error_text = str(exc)
|
||||
logger.error("Forward failed for %s: %s", subject, error_text)
|
||||
@@ -366,7 +385,7 @@ def sync_account(
|
||||
db.commit()
|
||||
db.refresh(sync_run)
|
||||
|
||||
return msg
|
||||
return sync_run
|
||||
|
||||
|
||||
def _mark_missing_from_mailbox(db: Session, message: Message, reason: str) -> Message:
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Message search filter tests."""
|
||||
|
||||
from forwarder.services.message_search import build_message_search_filter
|
||||
|
||||
|
||||
def test_build_message_search_filter_empty():
|
||||
assert build_message_search_filter(None) is None
|
||||
assert build_message_search_filter("") is None
|
||||
assert build_message_search_filter(" ") is None
|
||||
|
||||
|
||||
def test_build_message_search_filter_returns_clause():
|
||||
clause = build_message_search_filter("fatura")
|
||||
assert clause is not None
|
||||
|
||||
|
||||
def test_build_message_search_filter_numeric_id():
|
||||
clause = build_message_search_filter("767")
|
||||
assert clause is not None
|
||||
Reference in new issue
Block a user