feat: BizDocs API delivery, WebDAV source, and invoice validation

Add optional API upload alongside SMTP, Nextcloud/WebDAV as a document source with the same dedup/retry flow as IMAP, stricter invoice file checks for images, and admin UI for source and delivery modes.
This commit is contained in:
1sonhador committed 2026-07-02 19:21:01 +01:00
1 parent 6840e521dd
commit 0f4bb5f522
28 files changed
+2801 -174

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ ADMIN_PASSWORD=change_me
# Worker # Worker
SYNC_INTERVAL_MINUTES=15 SYNC_INTERVAL_MINUTES=15
# Max successful SMTP forwards per rolling hour (0 = unlimited) # Max successful SMTP forwards per rolling hour (0 = unlimited)
MAX_FORWARDS_PER_HOUR=200 MAX_FORWARDS_PER_HOUR=400
# Forward queue: process at most N failed messages per tick # Forward queue: process at most N failed messages per tick
FORWARD_QUEUE_BATCH_SIZE=5 FORWARD_QUEUE_BATCH_SIZE=5
FORWARD_QUEUE_INTERVAL_SECONDS=60 FORWARD_QUEUE_INTERVAL_SECONDS=60
+20 -7
View File
@@ -27,13 +27,22 @@ export interface Account {
id: number id: number
name: string name: string
email: string email: string
imap_host: string source_type: 'imap' | 'webdav'
imap_host: string | null
imap_port: number imap_port: number
imap_user: string imap_user: string | null
smtp_host: string webdav_url: string | null
webdav_path: string | null
webdav_user: string | null
webdav_verify_ssl: boolean
delivery_mode: 'api' | 'smtp'
smtp_host: string | null
smtp_port: number smtp_port: number
smtp_user: string smtp_user: string | null
destination_email: string destination_email: string | null
bizdocs_email: string | null
bizdocs_company_id: string | null
bizdocs_api_base_url: string | null
sync_interval_minutes: number sync_interval_minutes: number
active: boolean active: boolean
created_at: string created_at: string
@@ -41,8 +50,10 @@ export interface Account {
} }
export type AccountCreate = Omit<Account, 'id' | 'created_at' | 'updated_at'> & { export type AccountCreate = Omit<Account, 'id' | 'created_at' | 'updated_at'> & {
imap_password: string imap_password?: string
smtp_password: string webdav_password?: string
smtp_password?: string
bizdocs_password?: string
} }
export interface Message { export interface Message {
@@ -103,6 +114,8 @@ export interface Stats {
export interface ConnectionTestResult { export interface ConnectionTestResult {
imap_ok: boolean imap_ok: boolean
imap_error: string | null imap_error: string | null
webdav_ok: boolean
webdav_error: string | null
smtp_ok: boolean smtp_ok: boolean
smtp_error: string | null smtp_error: string | null
bizdocs_ok: boolean bizdocs_ok: boolean
+205 -58
View File
@@ -19,14 +19,25 @@ function formatSyncResult(r: import('../lib/api').SyncRunResult): string {
const EMPTY_FORM: AccountCreate = { const EMPTY_FORM: AccountCreate = {
name: '', name: '',
email: '', email: '',
source_type: 'imap',
imap_host: '', imap_host: '',
imap_port: 993, imap_port: 993,
imap_user: '', imap_user: '',
imap_password: '', imap_password: '',
webdav_url: '',
webdav_path: '',
webdav_user: '',
webdav_password: '',
webdav_verify_ssl: true,
delivery_mode: 'smtp',
smtp_host: '', smtp_host: '',
smtp_port: 587, smtp_port: 587,
smtp_user: '', smtp_user: '',
smtp_password: '', smtp_password: '',
bizdocs_email: '',
bizdocs_password: '',
bizdocs_company_id: '',
bizdocs_api_base_url: '',
destination_email: DEFAULT_DESTINATION_EMAIL, destination_email: DEFAULT_DESTINATION_EMAIL,
sync_interval_minutes: 15, sync_interval_minutes: 15,
active: false, active: false,
@@ -44,6 +55,7 @@ function AccountModal({
const [form, setForm] = useState<AccountCreate>({ ...EMPTY_FORM, ...initial }) const [form, setForm] = useState<AccountCreate>({ ...EMPTY_FORM, ...initial })
const [saving, setSaving] = useState(false) const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null)
const isWebdav = form.source_type === 'webdav'
const set = (k: keyof AccountCreate, v: string | number | boolean) => const set = (k: keyof AccountCreate, v: string | number | boolean) =>
setForm((f) => ({ ...f, [k]: v })) setForm((f) => ({ ...f, [k]: v }))
@@ -52,18 +64,57 @@ function AccountModal({
e.preventDefault() e.preventDefault()
setSaving(true) setSaving(true)
setError(null) setError(null)
const imapUser = form.imap_user.trim() || form.email.trim()
const smtpUser = form.smtp_user.trim() || form.email.trim() const sourceEmail = form.email.trim()
if (!imapUser) { const imapUser = form.imap_user.trim() || sourceEmail
setError('Indica o email de origem ou o utilizador IMAP.') const webdavUser = form.webdav_user.trim() || sourceEmail
setSaving(false) const smtpUser = form.smtp_user.trim() || sourceEmail || imapUser || webdavUser
return const bizdocsEmail = form.bizdocs_email.trim() || imapUser || webdavUser
if (isWebdav) {
if (!webdavUser) {
setError('Indica o utilizador WebDAV ou email de origem.')
setSaving(false)
return
}
if (!form.webdav_url?.trim()) {
setError('URL WebDAV é obrigatória.')
setSaving(false)
return
}
if (!form.webdav_password?.trim()) {
setError('Password WebDAV é obrigatória.')
setSaving(false)
return
}
} else {
if (!imapUser) {
setError('Indica o email de origem ou o utilizador IMAP.')
setSaving(false)
return
}
} }
if (form.delivery_mode === 'api') {
if (!form.bizdocs_password?.trim()) {
setError('Password BizDocs é obrigatória para upload via API.')
setSaving(false)
return
}
if (!form.bizdocs_company_id?.trim()) {
setError('Company ID BizDocs é obrigatório.')
setSaving(false)
return
}
}
const payload: AccountCreate = { const payload: AccountCreate = {
...form, ...form,
imap_user: imapUser, imap_user: isWebdav ? '' : imapUser,
webdav_user: isWebdav ? webdavUser : '',
smtp_user: smtpUser, smtp_user: smtpUser,
destination_email: form.destination_email.trim() || DEFAULT_DESTINATION_EMAIL, bizdocs_email: bizdocsEmail,
destination_email: form.destination_email?.trim() || DEFAULT_DESTINATION_EMAIL,
} }
try { try {
await onSave(payload) await onSave(payload)
@@ -85,7 +136,7 @@ function AccountModal({
<label className="block text-xs font-medium text-gray-700 mb-1">{label}</label> <label className="block text-xs font-medium text-gray-700 mb-1">{label}</label>
<input <input
type={type} type={type}
value={String(form[key])} value={String(form[key] ?? '')}
placeholder={placeholder} placeholder={placeholder}
onChange={(e) => set(key, type === 'number' ? Number(e.target.value) : e.target.value)} onChange={(e) => set(key, type === 'number' ? Number(e.target.value) : e.target.value)}
className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500" className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
@@ -105,46 +156,122 @@ function AccountModal({
<form onSubmit={handleSubmit} className="p-5 space-y-4"> <form onSubmit={handleSubmit} className="p-5 space-y-4">
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
{field('Nome', 'name', 'text', 'ex. Empresa X')} {field('Nome', 'name', 'text', 'ex. Empresa X')}
{field('Email de origem', 'email', 'email', 'noreply@empresa.pt')} {field('Email / identificador', 'email', 'email', 'user@empresa.pt')}
</div> </div>
<fieldset className="border border-gray-200 rounded-md p-3"> <div>
<legend className="text-xs font-semibold text-gray-500 px-1">IMAP</legend> <label className="block text-xs font-medium text-gray-700 mb-1">Origem dos documentos</label>
<div className="grid grid-cols-3 gap-3 mt-1"> <select
{field('Host', 'imap_host', 'text', 'imap.gmail.com')} value={form.source_type}
{field('Porto', 'imap_port', 'number')} onChange={(e) => set('source_type', e.target.value as 'imap' | 'webdav')}
{field('Utilizador', 'imap_user', 'text')} className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm"
<div className="col-span-3"> >
{field('Password', 'imap_password', 'password')} <option value="imap">Email (IMAP)</option>
<option value="webdav">WebDAV / Nextcloud</option>
</select>
</div>
{isWebdav ? (
<fieldset className="border border-gray-200 rounded-md p-3">
<legend className="text-xs font-semibold text-gray-500 px-1">WebDAV / Nextcloud</legend>
<div className="grid grid-cols-1 gap-3 mt-1">
{field(
'URL base',
'webdav_url',
'text',
'https://cloud.exemplo.pt/remote.php/dav/files/USER',
)}
{field('Pasta (opcional)', 'webdav_path', 'text', '/Faturas')}
<div className="grid grid-cols-2 gap-3">
{field('Utilizador', 'webdav_user', 'text')}
{field('Password', 'webdav_password', 'password')}
</div>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={form.webdav_verify_ssl}
onChange={(e) => set('webdav_verify_ssl', e.target.checked)}
className="rounded"
/>
<span className="text-sm">Verificar certificado SSL</span>
</label>
<p className="text-xs text-gray-500">
Lista recursivamente todos os ficheiros PDF, XML, ZIP, PNG e JPG na pasta.
Ficheiros já reencaminhados são ignorados (mesma lógica que emails).
</p>
</div> </div>
</div> </fieldset>
</fieldset> ) : (
<fieldset className="border border-gray-200 rounded-md p-3">
<legend className="text-xs font-semibold text-gray-500 px-1">IMAP</legend>
<div className="grid grid-cols-3 gap-3 mt-1">
{field('Host', 'imap_host', 'text', 'imap.gmail.com')}
{field('Porto', 'imap_port', 'number')}
{field('Utilizador', 'imap_user', 'text')}
<div className="col-span-3">
{field('Password', 'imap_password', 'password')}
</div>
</div>
</fieldset>
)}
<fieldset className="border border-gray-200 rounded-md p-3"> <fieldset className="border border-gray-200 rounded-md p-3">
<legend className="text-xs font-semibold text-gray-500 px-1">SMTP</legend> <legend className="text-xs font-semibold text-gray-500 px-1">Entrega BizDocs</legend>
<div className="grid grid-cols-3 gap-3 mt-1"> <div className="mb-3">
{field('Host', 'smtp_host', 'text', 'smtp.gmail.com')} <label className="block text-xs font-medium text-gray-700 mb-1">Modo</label>
{field('Porto', 'smtp_port', 'number')} <select
{field('Utilizador', 'smtp_user', 'text')} value={form.delivery_mode}
<div className="col-span-3"> onChange={(e) => set('delivery_mode', e.target.value as 'api' | 'smtp')}
{field('Password', 'smtp_password', 'password')} className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm"
</div> >
<option value="smtp">Email SMTP (inbox.arquivodigital@…)</option>
<option value="api">API directa (login BizDocs)</option>
</select>
</div> </div>
</fieldset>
<fieldset className="border border-gray-200 rounded-md p-3"> {form.delivery_mode === 'api' ? (
<legend className="text-xs font-semibold text-gray-500 px-1">BizDocs (destino)</legend> <div className="grid grid-cols-2 gap-3">
<p className="text-xs text-gray-500 mb-2"> {field('Email BizDocs', 'bizdocs_email', 'email')}
Email para onde são enviados os anexos de fatura (PDF/XML/ZIP) — email limpo, sem reencaminhar o original. {field('Password BizDocs', 'bizdocs_password', 'password')}
</p> {field('Company ID', 'bizdocs_company_id', 'text', 'UUID da empresa')}
{field( <div className="col-span-2">
'Email destino', {field(
'destination_email', 'API base URL (opcional)',
'email', 'bizdocs_api_base_url',
DEFAULT_DESTINATION_EMAIL, 'text',
'Só se o identity router falhar',
)}
</div>
<p className="col-span-2 text-xs text-gray-500">
Envia PDF, XML, ZIP, PNG e JPG (máx. 10 MB) directamente para a Inbox via API.
</p>
</div>
) : (
<>
<div className="grid grid-cols-3 gap-3 mt-1 mb-3">
{field('Host SMTP', 'smtp_host', 'text', 'smtp.gmail.com')}
{field('Porto', 'smtp_port', 'number')}
{field('Utilizador', 'smtp_user', 'text')}
<div className="col-span-3">
{field('Password SMTP', 'smtp_password', 'password')}
</div>
</div>
{field(
'Email destino',
'destination_email',
'email',
DEFAULT_DESTINATION_EMAIL,
)}
</>
)} )}
</fieldset> </fieldset>
{form.delivery_mode === 'smtp' && (
<p className="text-xs text-gray-500 -mt-2">
O remetente SMTP tem de estar autorizado como mailbox no portal BizDocs.
</p>
)}
<label className="flex items-center gap-2 cursor-pointer"> <label className="flex items-center gap-2 cursor-pointer">
<input <input
type="checkbox" type="checkbox"
@@ -222,11 +349,16 @@ export default function Accounts() {
setTestingId(id) setTestingId(id)
try { try {
const r = await api.connection.testAccount(id) const r = await api.connection.testAccount(id)
const ok = r.imap_ok && r.smtp_ok && r.bizdocs_ok const account = accounts?.find((a) => a.id === id)
const isApi = account?.delivery_mode === 'api'
const isWebdav = account?.source_type === 'webdav'
const sourceOk = isWebdav ? r.webdav_ok : r.imap_ok
const ok = isApi ? sourceOk && r.bizdocs_ok : sourceOk && r.smtp_ok
const parts: string[] = [] const parts: string[] = []
if (!r.imap_ok) parts.push(`IMAP: ${r.imap_error}`) if (isWebdav && !r.webdav_ok) parts.push(`WebDAV: ${r.webdav_error}`)
if (!r.smtp_ok) parts.push(`SMTP: ${r.smtp_error}`) if (!isWebdav && !r.imap_ok) parts.push(`IMAP: ${r.imap_error}`)
if (!r.bizdocs_ok) parts.push(`BizDocs: ${r.bizdocs_error}`) if (!isApi && !r.smtp_ok) parts.push(`SMTP: ${r.smtp_error}`)
if (isApi && !r.bizdocs_ok) parts.push(`BizDocs: ${r.bizdocs_error}`)
setTestResults((prev) => ({ setTestResults((prev) => ({
...prev, ...prev,
[id]: { ok, msg: ok ? 'Ligação OK' : parts.join(' | ') }, [id]: { ok, msg: ok ? 'Ligação OK' : parts.join(' | ') },
@@ -246,9 +378,13 @@ export default function Accounts() {
opts: { dry_run?: boolean; max_emails?: number }, opts: { dry_run?: boolean; max_emails?: number },
confirmFull = false, confirmFull = false,
) => { ) => {
const account = accounts?.find((a) => a.id === id)
const isWebdav = account?.source_type === 'webdav'
if (confirmFull) { if (confirmFull) {
const ok = confirm( const ok = confirm(
'Sync completo processa todo o histórico IMAP com anexos PDF/XML/ZIP. Continuar?', isWebdav
? 'Sync completo percorre todos os ficheiros WebDAV com extensões permitidas. Continuar?'
: 'Sync completo processa todo o histórico IMAP com anexos PDF/XML/ZIP. Continuar?',
) )
if (!ok) return if (!ok) return
} }
@@ -285,7 +421,7 @@ export default function Accounts() {
<div className="flex items-center justify-between mb-6"> <div className="flex items-center justify-between mb-6">
<div> <div>
<h2 className="text-xl font-semibold">Contas</h2> <h2 className="text-xl font-semibold">Contas</h2>
<p className="text-sm text-gray-500 mt-0.5">Contas IMAP configuradas</p> <p className="text-sm text-gray-500 mt-0.5">Contas IMAP ou WebDAV configuradas</p>
</div> </div>
<button <button
onClick={openNew} onClick={openNew}
@@ -310,11 +446,11 @@ export default function Accounts() {
<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"> <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> <span>
O worker automático só corre com <strong>Conta activa</strong>.{' '} O worker automático só corre com <strong>Conta activa</strong>.{' '}
<strong>▶</strong> testa os primeiros N emails;{' '} <strong>▶</strong> testa os primeiros N itens;{' '}
<strong>↻</strong> sync completo (toda a mailbox). <strong>↻</strong> sync completo (toda a origem).
</span> </span>
<label className="flex items-center gap-1.5 ml-auto"> <label className="flex items-center gap-1.5 ml-auto">
Emails no teste ▶: Itens no teste ▶:
<input <input
type="number" type="number"
min={1} min={1}
@@ -339,7 +475,8 @@ export default function Accounts() {
<thead className="bg-gray-50 border-b border-gray-200"> <thead className="bg-gray-50 border-b border-gray-200">
<tr> <tr>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Nome</th> <th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Nome</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Email</th> <th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Origem</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Identificador</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Destino BizDocs</th> <th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Destino BizDocs</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</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> <th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
@@ -349,9 +486,10 @@ export default function Accounts() {
{accounts.map((a) => ( {accounts.map((a) => (
<tr key={a.id} className="hover:bg-gray-50"> <tr key={a.id} className="hover:bg-gray-50">
<td className="px-4 py-3 font-medium">{a.name}</td> <td className="px-4 py-3 font-medium">{a.name}</td>
<td className="px-4 py-3 text-gray-600 capitalize">{a.source_type}</td>
<td className="px-4 py-3 text-gray-600">{a.email}</td> <td className="px-4 py-3 text-gray-600">{a.email}</td>
<td className="px-4 py-3 text-gray-500 text-xs truncate max-w-[200px]" title={a.destination_email}> <td className="px-4 py-3 text-gray-500 text-xs truncate max-w-[200px]" title={a.destination_email || ''}>
{a.destination_email} {a.delivery_mode === 'api' ? 'API BizDocs' : a.destination_email}
</td> </td>
<td className="px-4 py-3"> <td className="px-4 py-3">
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
@@ -377,7 +515,7 @@ export default function Accounts() {
<td className="px-4 py-3"> <td className="px-4 py-3">
<div className="flex items-center justify-end gap-1 flex-wrap"> <div className="flex items-center justify-end gap-1 flex-wrap">
<button <button
title={`Teste: ler no máximo ${testBatchSize} emails (não é sync completo)`} title={`Teste: ler no máximo ${testBatchSize} itens (não é sync completo)`}
onClick={() => handleSync(a.id, { max_emails: testBatchSize })} onClick={() => handleSync(a.id, { max_emails: testBatchSize })}
disabled={syncingId === a.id} disabled={syncingId === a.id}
className="p-1.5 text-gray-400 hover:text-green-600 disabled:opacity-40" className="p-1.5 text-gray-400 hover:text-green-600 disabled:opacity-40"
@@ -399,7 +537,7 @@ export default function Accounts() {
<FlaskConical size={14} /> <FlaskConical size={14} />
</button> </button>
<button <button
title="Sync completo — percorre todas as pastas IMAP" title={a.source_type === 'webdav' ? 'Sync completo — todos os ficheiros WebDAV' : 'Sync completo — percorre todas as pastas IMAP'}
onClick={() => handleSync(a.id, {}, true)} onClick={() => handleSync(a.id, {}, true)}
disabled={syncingId === a.id} disabled={syncingId === a.id}
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40" className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
@@ -444,13 +582,22 @@ export default function Accounts() {
? { ? {
name: modal.account.name, name: modal.account.name,
email: modal.account.email, email: modal.account.email,
imap_host: modal.account.imap_host, source_type: modal.account.source_type || 'imap',
imap_host: modal.account.imap_host || '',
imap_port: modal.account.imap_port, imap_port: modal.account.imap_port,
imap_user: modal.account.imap_user, imap_user: modal.account.imap_user || '',
smtp_host: modal.account.smtp_host, webdav_url: modal.account.webdav_url || '',
webdav_path: modal.account.webdav_path || '',
webdav_user: modal.account.webdav_user || '',
webdav_verify_ssl: modal.account.webdav_verify_ssl,
delivery_mode: modal.account.delivery_mode || 'smtp',
smtp_host: modal.account.smtp_host || '',
smtp_port: modal.account.smtp_port, smtp_port: modal.account.smtp_port,
smtp_user: modal.account.smtp_user, smtp_user: modal.account.smtp_user || '',
destination_email: modal.account.destination_email, destination_email: modal.account.destination_email || DEFAULT_DESTINATION_EMAIL,
bizdocs_email: modal.account.bizdocs_email || modal.account.email,
bizdocs_company_id: modal.account.bizdocs_company_id || '',
bizdocs_api_base_url: modal.account.bizdocs_api_base_url || '',
sync_interval_minutes: modal.account.sync_interval_minutes, sync_interval_minutes: modal.account.sync_interval_minutes,
active: modal.account.active, active: modal.account.active,
} }
+3 -3
View File
@@ -89,7 +89,7 @@ export default function Emails() {
setActionMsg({ setActionMsg({
ok, ok,
text: r.rate_limited text: r.rate_limited
? `Fila pausada — limite horário (${r.max_forwards_per_hour ?? 200}/h). ${r.pending_total ?? r.pending ?? '?'} ainda pendentes.` ? `Fila pausada — limite horário (${r.max_forwards_per_hour ?? 400}/h). ${r.pending_total ?? r.pending ?? '?'} ainda pendentes.`
: r.attempted === 0 : r.attempted === 0
? 'Fila vazia — nada a reenviar.' ? 'Fila vazia — nada a reenviar.'
: `Fila: ${r.succeeded}/${r.attempted} enviados neste tick (${r.pending_total ?? '?'} pendentes).`, : `Fila: ${r.succeeded}/${r.attempted} enviados neste tick (${r.pending_total ?? '?'} pendentes).`,
@@ -117,7 +117,7 @@ export default function Emails() {
const ok = confirm( const ok = confirm(
`Colocar todas as mensagens reencaminhadas na fila para reenvio?\n\n` + `Colocar todas as mensagens reencaminhadas na fila para reenvio?\n\n` +
`O worker envia no máximo ${queueInfo?.batch_size_per_tick ?? 5} por minuto ` + `O worker envia no máximo ${queueInfo?.batch_size_per_tick ?? 5} por minuto ` +
`(limite ${queueInfo?.max_forwards_per_hour ?? 200}/hora). ` + `(limite ${queueInfo?.max_forwards_per_hour ?? 400}/hora). ` +
`BizDocs ignora duplicados.\n\n` + `BizDocs ignora duplicados.\n\n` +
(forwarded != null ? `${forwarded} mensagens serão reenviadas gradualmente.` : ''), (forwarded != null ? `${forwarded} mensagens serão reenviadas gradualmente.` : ''),
) )
@@ -157,7 +157,7 @@ export default function Emails() {
return return
} }
const batch = queueInfo?.batch_size_per_tick ?? 5 const batch = queueInfo?.batch_size_per_tick ?? 5
const maxHour = queueInfo?.max_forwards_per_hour ?? 200 const maxHour = queueInfo?.max_forwards_per_hour ?? 400
const ok = confirm( const ok = confirm(
`Enfileirar ${failedCount} mensagens falhadas para reenvio gradual?\n\n` + `Enfileirar ${failedCount} mensagens falhadas para reenvio gradual?\n\n` +
`O worker envia no máximo ${batch}/min (máx. ${maxHour}/hora). Não há envio em massa.`, `O worker envia no máximo ${batch}/min (máx. ${maxHour}/hora). Não há envio em massa.`,
@@ -0,0 +1,98 @@
"""BizDocs API delivery mode and credentials
Revision ID: 003_bizdocs_api
Revises: 002_missing_from_mailbox
Create Date: 2026-07-01
"""
from typing import Sequence, Union
import json
import sqlalchemy as sa
from alembic import op
from sqlalchemy import text
revision: str = "003_bizdocs_api"
down_revision: Union[str, None] = "002_missing_from_mailbox"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
_IMAGE_EXTENSIONS = (".png", ".jpg", ".jpeg")
def _merge_image_extensions(existing: object) -> list[str]:
if isinstance(existing, str):
try:
existing = json.loads(existing)
except json.JSONDecodeError:
existing = []
if not isinstance(existing, list):
existing = []
merged = [str(item).lower() for item in existing]
for ext in _IMAGE_EXTENSIONS:
if ext not in merged:
merged.append(ext)
return merged
def _extend_account_extensions() -> None:
conn = op.get_bind()
rows = conn.execute(text("SELECT id, allowed_extensions FROM accounts")).fetchall()
for row in rows:
merged = _merge_image_extensions(row.allowed_extensions)
conn.execute(
text("UPDATE accounts SET allowed_extensions = :exts WHERE id = :id"),
{"exts": json.dumps(merged), "id": row.id},
)
def upgrade() -> None:
op.add_column(
"accounts",
sa.Column(
"delivery_mode",
sa.Enum("smtp", "api", name="deliverymode"),
nullable=False,
server_default="smtp",
),
)
op.add_column(
"accounts",
sa.Column("bizdocs_email", sa.String(length=255), nullable=True),
)
op.add_column(
"accounts",
sa.Column("bizdocs_password_encrypted", sa.Text(), nullable=True),
)
op.add_column(
"accounts",
sa.Column("bizdocs_company_id", sa.String(length=100), nullable=True),
)
op.add_column(
"accounts",
sa.Column("bizdocs_api_base_url", sa.String(length=512), nullable=True),
)
op.add_column(
"messages",
sa.Column("bizdocs_doc_id", sa.String(length=255), nullable=True),
)
op.alter_column("accounts", "smtp_host", existing_type=sa.String(length=255), nullable=True)
op.alter_column("accounts", "smtp_user", existing_type=sa.String(length=255), nullable=True)
op.alter_column("accounts", "smtp_password_encrypted", existing_type=sa.Text(), nullable=True)
op.alter_column("accounts", "destination_email", existing_type=sa.String(length=255), nullable=True)
_extend_account_extensions()
def downgrade() -> None:
op.alter_column("accounts", "destination_email", existing_type=sa.String(length=255), nullable=False)
op.alter_column("accounts", "smtp_password_encrypted", existing_type=sa.Text(), nullable=False)
op.alter_column("accounts", "smtp_user", existing_type=sa.String(length=255), nullable=False)
op.alter_column("accounts", "smtp_host", existing_type=sa.String(length=255), nullable=False)
op.drop_column("messages", "bizdocs_doc_id")
op.drop_column("accounts", "bizdocs_api_base_url")
op.drop_column("accounts", "bizdocs_company_id")
op.drop_column("accounts", "bizdocs_password_encrypted")
op.drop_column("accounts", "bizdocs_email")
op.drop_column("accounts", "delivery_mode")
op.execute("DROP TYPE IF EXISTS deliverymode")
+64
View File
@@ -0,0 +1,64 @@
"""Add WebDAV/Nextcloud as document source
Revision ID: 004_webdav
Revises: 003_bizdocs_api
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "004_webdav"
down_revision: Union[str, None] = "003_bizdocs_api"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column(
"accounts",
sa.Column(
"source_type",
sa.Enum("imap", "webdav", name="sourcetype"),
nullable=False,
server_default="imap",
),
)
op.add_column("accounts", sa.Column("webdav_url", sa.String(length=512), nullable=True))
op.add_column("accounts", sa.Column("webdav_path", sa.String(length=512), nullable=True))
op.add_column("accounts", sa.Column("webdav_user", sa.String(length=255), nullable=True))
op.add_column("accounts", sa.Column("webdav_password_encrypted", sa.Text(), nullable=True))
op.add_column(
"accounts",
sa.Column(
"webdav_verify_ssl",
sa.Boolean(),
nullable=False,
server_default=sa.text("1"),
),
)
op.alter_column("accounts", "imap_host", existing_type=sa.String(length=255), nullable=True)
op.alter_column("accounts", "imap_user", existing_type=sa.String(length=255), nullable=True)
op.alter_column("accounts", "imap_password_encrypted", existing_type=sa.Text(), nullable=True)
op.execute(
"ALTER TABLE connection_tests MODIFY COLUMN test_type "
"ENUM('imap', 'smtp', 'send', 'webdav') NOT NULL"
)
def downgrade() -> None:
op.execute(
"ALTER TABLE connection_tests MODIFY COLUMN test_type "
"ENUM('imap', 'smtp', 'send') NOT NULL"
)
op.alter_column("accounts", "imap_password_encrypted", existing_type=sa.Text(), nullable=False)
op.alter_column("accounts", "imap_user", existing_type=sa.String(length=255), nullable=False)
op.alter_column("accounts", "imap_host", existing_type=sa.String(length=255), nullable=False)
op.drop_column("accounts", "webdav_verify_ssl")
op.drop_column("accounts", "webdav_password_encrypted")
op.drop_column("accounts", "webdav_user")
op.drop_column("accounts", "webdav_path")
op.drop_column("accounts", "webdav_url")
op.drop_column("accounts", "source_type")
op.execute("DROP TYPE IF EXISTS sourcetype")
+1
View File
@@ -20,6 +20,7 @@ dependencies = [
"pydantic-settings>=2.6.0", "pydantic-settings>=2.6.0",
"python-multipart>=0.0.17", "python-multipart>=0.0.17",
"bcrypt>=4.0.0", "bcrypt>=4.0.0",
"httpx>=0.28.0",
] ]
[project.optional-dependencies] [project.optional-dependencies]
+132 -23
View File
@@ -1,7 +1,5 @@
from __future__ import annotations from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from fastapi import APIRouter, HTTPException, Query, status from fastapi import APIRouter, HTTPException, Query, status
from forwarder.api.deps import CurrentUser, DbSession from forwarder.api.deps import CurrentUser, DbSession
@@ -15,6 +13,7 @@ from forwarder.api.schemas import (
SyncRunResponse, SyncRunResponse,
) )
from forwarder.crypto import decrypt_password from forwarder.crypto import decrypt_password
from forwarder.db.models import ConnectionTestType, SourceType
from forwarder.email.imap_client import ImapConfig, test_imap_connection from forwarder.email.imap_client import ImapConfig, test_imap_connection
from forwarder.email.smtp_client import SmtpConfig, test_smtp_connection from forwarder.email.smtp_client import SmtpConfig, test_smtp_connection
from forwarder.services import account_service from forwarder.services import account_service
@@ -73,6 +72,24 @@ def test_send_presave(
return ConnectionTestResponse(success=success, message=message) return ConnectionTestResponse(success=success, message=message)
@router.post("/test/webdav", response_model=ConnectionTestResponse)
def test_webdav_presave(
inline: InlineConnectionConfig,
db: DbSession,
_user: CurrentUser,
) -> ConnectionTestResponse:
data = inline.model_dump(exclude_unset=True)
required = ("webdav_url", "webdav_user", "webdav_password")
for field in required:
if not data.get(field):
raise HTTPException(status_code=400, detail=f"{field} is required")
try:
success, message = account_service.run_webdav_test(db, None, data)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return ConnectionTestResponse(success=success, message=message)
@router.get("", response_model=list[AccountResponse]) @router.get("", response_model=list[AccountResponse])
def list_accounts(db: DbSession, _user: CurrentUser) -> list[AccountResponse]: def list_accounts(db: DbSession, _user: CurrentUser) -> list[AccountResponse]:
return [_to_response(a) for a in account_service.list_accounts(db)] return [_to_response(a) for a in account_service.list_accounts(db)]
@@ -134,39 +151,81 @@ def test_account(
db: DbSession, db: DbSession,
_user: CurrentUser, _user: CurrentUser,
) -> ConnectionTestResult: ) -> ConnectionTestResult:
"""Run IMAP + SMTP tests for a saved account (combined result for the UI).""" """Run source + delivery tests for a saved account (combined result for the UI)."""
try: try:
account = account_service.get_account(db, account_id) account = account_service.get_account(db, account_id)
except account_service.AccountNotFoundError as exc: except account_service.AccountNotFoundError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc raise HTTPException(status_code=404, detail=str(exc)) from exc
imap_cfg = ImapConfig( is_webdav = account.source_type == SourceType.webdav
host=account.imap_host, imap_ok = True
port=account.imap_port, imap_msg = None
user=account.imap_user, webdav_ok = True
password=decrypt_password(account.imap_password_encrypted), webdav_msg = None
)
smtp_cfg = SmtpConfig(
host=account.smtp_host,
port=account.smtp_port,
user=account.smtp_user,
password=decrypt_password(account.smtp_password_encrypted),
use_tls=account.smtp_use_tls,
)
with ThreadPoolExecutor(max_workers=2) as executor: if is_webdav:
imap_future = executor.submit(test_imap_connection, imap_cfg) try:
smtp_future = executor.submit(test_smtp_connection, smtp_cfg) webdav_ok, webdav_msg = account_service.run_webdav_test(db, account_id, None)
imap_ok, imap_msg = imap_future.result() except ValueError as exc:
smtp_ok, smtp_msg = smtp_future.result() webdav_ok, webdav_msg = False, str(exc)
else:
if not account.imap_host or not account.imap_user or not account.imap_password_encrypted:
imap_ok, imap_msg = False, "IMAP not configured"
else:
imap_cfg = ImapConfig(
host=account.imap_host,
port=account.imap_port,
user=account.imap_user,
password=decrypt_password(account.imap_password_encrypted),
)
imap_ok, imap_msg = test_imap_connection(imap_cfg)
account_service.record_connection_test(
db,
account_id=account_id,
test_type=ConnectionTestType.imap,
success=imap_ok,
message=imap_msg or "",
)
smtp_cfg = None
if account.smtp_host and account.smtp_user and account.smtp_password_encrypted:
smtp_cfg = SmtpConfig(
host=account.smtp_host,
port=account.smtp_port,
user=account.smtp_user,
password=decrypt_password(account.smtp_password_encrypted),
use_tls=account.smtp_use_tls,
)
if account.delivery_mode.value == "api":
smtp_ok, smtp_msg = True, None
try:
bizdocs_ok, bizdocs_msg = account_service.run_bizdocs_test(db, account_id, None)
except ValueError as exc:
bizdocs_ok, bizdocs_msg = False, str(exc)
else:
if smtp_cfg is None:
smtp_ok, smtp_msg = False, "SMTP not configured"
else:
smtp_ok, smtp_msg = test_smtp_connection(smtp_cfg)
account_service.record_connection_test(
db,
account_id=account_id,
test_type=ConnectionTestType.smtp,
success=smtp_ok,
message=smtp_msg or "",
)
bizdocs_ok, bizdocs_msg = True, None
return ConnectionTestResult( return ConnectionTestResult(
imap_ok=imap_ok, imap_ok=imap_ok,
imap_error=None if imap_ok else imap_msg, imap_error=None if imap_ok else imap_msg,
webdav_ok=webdav_ok,
webdav_error=None if webdav_ok else webdav_msg,
smtp_ok=smtp_ok, smtp_ok=smtp_ok,
smtp_error=None if smtp_ok else smtp_msg, smtp_error=None if smtp_ok else smtp_msg,
bizdocs_ok=True, bizdocs_ok=bizdocs_ok,
bizdocs_error=None, bizdocs_error=None if bizdocs_ok else bizdocs_msg,
) )
@@ -219,6 +278,56 @@ def test_send(
return ConnectionTestResponse(success=success, message=message) return ConnectionTestResponse(success=success, message=message)
@router.post("/test/bizdocs", response_model=ConnectionTestResponse)
def test_bizdocs_presave(
inline: InlineConnectionConfig,
db: DbSession,
_user: CurrentUser,
) -> ConnectionTestResponse:
data = inline.model_dump(exclude_unset=True)
if not data.get("bizdocs_password"):
raise HTTPException(status_code=400, detail="bizdocs_password is required")
if not data.get("bizdocs_company_id"):
raise HTTPException(status_code=400, detail="bizdocs_company_id is required")
try:
success, message = account_service.run_bizdocs_test(db, None, data)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return ConnectionTestResponse(success=success, message=message)
@router.post("/{account_id}/test/bizdocs", response_model=ConnectionTestResponse)
def test_bizdocs(
account_id: int,
db: DbSession,
_user: CurrentUser,
inline: InlineConnectionConfig | None = None,
) -> ConnectionTestResponse:
try:
success, message = account_service.run_bizdocs_test(
db, account_id, _inline_dict(inline)
)
except (account_service.AccountNotFoundError, ValueError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return ConnectionTestResponse(success=success, message=message)
@router.post("/{account_id}/test/webdav", response_model=ConnectionTestResponse)
def test_webdav(
account_id: int,
db: DbSession,
_user: CurrentUser,
inline: InlineConnectionConfig | None = None,
) -> ConnectionTestResponse:
try:
success, message = account_service.run_webdav_test(
db, account_id, _inline_dict(inline)
)
except (account_service.AccountNotFoundError, ValueError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return ConnectionTestResponse(success=success, message=message)
@router.post("/{account_id}/sync", response_model=SyncRunResponse) @router.post("/{account_id}/sync", response_model=SyncRunResponse)
def trigger_sync( def trigger_sync(
account_id: int, account_id: int,
+3 -1
View File
@@ -26,8 +26,10 @@ class ConnectionTestPayload(BaseModel):
class ConnectionTestResult(BaseModel): class ConnectionTestResult(BaseModel):
imap_ok: bool imap_ok: bool = True
imap_error: str | None = None imap_error: str | None = None
webdav_ok: bool = True
webdav_error: str | None = None
smtp_ok: bool smtp_ok: bool
smtp_error: str | None = None smtp_error: str | None = None
bizdocs_ok: bool = True bizdocs_ok: bool = True
+90 -14
View File
@@ -5,30 +5,41 @@ from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator
DEFAULT_BIZDOCS_DESTINATION = "[email protected]" DEFAULT_BIZDOCS_DESTINATION = "[email protected]"
DEFAULT_ALLOWED_EXTENSIONS = [".pdf", ".xml", ".zip", ".png", ".jpg", ".jpeg"]
class AccountBase(BaseModel): class AccountBase(BaseModel):
name: str name: str
enabled: bool = True enabled: bool = True
sync_interval_minutes: int = 15 sync_interval_minutes: int = 15
imap_host: str source_type: str = "imap"
imap_host: str | None = None
imap_port: int = 993 imap_port: int = 993
imap_user: str imap_user: str | None = None
smtp_host: str webdav_url: str | None = None
webdav_path: str | None = None
webdav_user: str | None = None
webdav_verify_ssl: bool = True
delivery_mode: str = "smtp"
smtp_host: str | None = None
smtp_port: int = 587 smtp_port: int = 587
smtp_user: str smtp_user: str | None = None
smtp_use_tls: bool = True smtp_use_tls: bool = True
destination_email: str destination_email: str | None = None
bizdocs_email: str | None = None
bizdocs_company_id: str | None = None
bizdocs_api_base_url: str | None = None
include_all_attachments: bool = False include_all_attachments: bool = False
allowed_extensions: list[str] = Field(default_factory=lambda: [".pdf", ".xml", ".zip"]) allowed_extensions: list[str] = Field(default_factory=lambda: list(DEFAULT_ALLOWED_EXTENSIONS))
class AccountCreate(AccountBase): class AccountCreate(AccountBase):
model_config = ConfigDict(extra="ignore") model_config = ConfigDict(extra="ignore")
destination_email: str = Field(default=DEFAULT_BIZDOCS_DESTINATION) imap_password: str | None = None
imap_password: str webdav_password: str | None = None
smtp_password: str smtp_password: str | None = None
bizdocs_password: str | None = None
# UI compat fields — ignored but accepted without validation error # UI compat fields — ignored but accepted without validation error
active: bool | None = None active: bool | None = None
email: str | None = None email: str | None = None
@@ -40,18 +51,52 @@ class AccountCreate(AccountBase):
def _apply_ui_compat_defaults(cls, data: object) -> object: def _apply_ui_compat_defaults(cls, data: object) -> object:
if not isinstance(data, dict): if not isinstance(data, dict):
return data return data
if not data.get("destination_email"): source_type = data.get("source_type") or "imap"
data["source_type"] = source_type
delivery_mode = data.get("delivery_mode") or "smtp"
data["delivery_mode"] = delivery_mode
if delivery_mode == "smtp" and not data.get("destination_email"):
data["destination_email"] = DEFAULT_BIZDOCS_DESTINATION data["destination_email"] = DEFAULT_BIZDOCS_DESTINATION
if not data.get("imap_user") and data.get("email"): if not data.get("bizdocs_email") and data.get("email"):
data["imap_user"] = data["email"] data["bizdocs_email"] = data["email"]
if source_type == "webdav":
if not data.get("webdav_user") and data.get("email"):
data["webdav_user"] = data["email"]
if not data.get("bizdocs_email") and data.get("webdav_user"):
data["bizdocs_email"] = data["webdav_user"]
else:
if not data.get("bizdocs_email") and data.get("imap_user"):
data["bizdocs_email"] = data["imap_user"]
if not data.get("imap_user") and data.get("email"):
data["imap_user"] = data["email"]
if not data.get("smtp_user") and data.get("email"): if not data.get("smtp_user") and data.get("email"):
data["smtp_user"] = data["email"] data["smtp_user"] = data["email"]
if not data.get("bizdocs_company_id") and data.get("bizdocs_entity_id"):
data["bizdocs_company_id"] = data["bizdocs_entity_id"]
return data return data
@model_validator(mode="after") @model_validator(mode="after")
def _sync_active(self) -> AccountCreate: def _validate_account(self) -> AccountCreate:
if self.active is not None: if self.active is not None:
self.enabled = self.active self.enabled = self.active
if self.source_type == "webdav":
if not self.webdav_url or not self.webdav_user or not self.webdav_password:
raise ValueError(
"webdav_url, webdav_user and webdav_password are required for WebDAV source"
)
else:
if not self.imap_host or not self.imap_user or not self.imap_password:
raise ValueError("imap_host, imap_user and imap_password are required for IMAP source")
if self.delivery_mode == "api":
if not self.bizdocs_password:
raise ValueError("bizdocs_password is required for API delivery")
if not self.bizdocs_company_id:
raise ValueError("bizdocs_company_id is required for API delivery")
else:
if not self.smtp_host or not self.smtp_user or not self.smtp_password:
raise ValueError("smtp_host, smtp_user and smtp_password are required for SMTP delivery")
if not self.destination_email:
raise ValueError("destination_email is required for SMTP delivery")
return self return self
@@ -61,16 +106,27 @@ class AccountUpdate(BaseModel):
name: str | None = None name: str | None = None
enabled: bool | None = None enabled: bool | None = None
sync_interval_minutes: int | None = None sync_interval_minutes: int | None = None
source_type: str | None = None
imap_host: str | None = None imap_host: str | None = None
imap_port: int | None = None imap_port: int | None = None
imap_user: str | None = None imap_user: str | None = None
imap_password: str | None = None imap_password: str | None = None
webdav_url: str | None = None
webdav_path: str | None = None
webdav_user: str | None = None
webdav_password: str | None = None
webdav_verify_ssl: bool | None = None
smtp_host: str | None = None smtp_host: str | None = None
smtp_port: int | None = None smtp_port: int | None = None
smtp_user: str | None = None smtp_user: str | None = None
smtp_password: str | None = None smtp_password: str | None = None
smtp_use_tls: bool | None = None smtp_use_tls: bool | None = None
delivery_mode: str | None = None
destination_email: str | None = None destination_email: str | None = None
bizdocs_email: str | None = None
bizdocs_password: str | None = None
bizdocs_company_id: str | None = None
bizdocs_api_base_url: str | None = None
include_all_attachments: bool | None = None include_all_attachments: bool | None = None
allowed_extensions: list[str] | None = None allowed_extensions: list[str] | None = None
active: bool | None = None active: bool | None = None
@@ -87,7 +143,9 @@ class AccountResponse(AccountBase):
id: int id: int
imap_password: str = "********" imap_password: str = "********"
webdav_password: str = "********"
smtp_password: str = "********" smtp_password: str = "********"
bizdocs_password: str = "********"
created_at: datetime created_at: datetime
updated_at: datetime updated_at: datetime
# UI compat stubs # UI compat stubs
@@ -102,20 +160,38 @@ class AccountResponse(AccountBase):
@computed_field # type: ignore[misc] @computed_field # type: ignore[misc]
@property @property
def email(self) -> str: def email(self) -> str:
return self.imap_user if self.source_type == "webdav":
return self.webdav_user or ""
return self.imap_user or ""
@computed_field # type: ignore[misc]
@property
def bizdocs_entity_id(self) -> str:
return self.bizdocs_company_id or ""
class InlineConnectionConfig(BaseModel): class InlineConnectionConfig(BaseModel):
source_type: str | None = None
imap_host: str | None = None imap_host: str | None = None
imap_port: int | None = None imap_port: int | None = None
imap_user: str | None = None imap_user: str | None = None
imap_password: str | None = None imap_password: str | None = None
webdav_url: str | None = None
webdav_path: str | None = None
webdav_user: str | None = None
webdav_password: str | None = None
webdav_verify_ssl: bool | None = None
smtp_host: str | None = None smtp_host: str | None = None
smtp_port: int | None = None smtp_port: int | None = None
smtp_user: str | None = None smtp_user: str | None = None
smtp_password: str | None = None smtp_password: str | None = None
smtp_use_tls: bool | None = None smtp_use_tls: bool | None = None
destination_email: str | None = None destination_email: str | None = None
delivery_mode: str | None = None
bizdocs_email: str | None = None
bizdocs_password: str | None = None
bizdocs_company_id: str | None = None
bizdocs_api_base_url: str | None = None
class ConnectionTestResponse(BaseModel): class ConnectionTestResponse(BaseModel):
+5
View File
@@ -0,0 +1,5 @@
"""BizDocs mobile API client."""
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials, BizdocsSession
__all__ = ["BizdocsClient", "BizdocsCredentials", "BizdocsSession"]
+358
View File
@@ -0,0 +1,358 @@
"""BizDocs mobile API client (login + direct document upload)."""
from __future__ import annotations
import logging
import mimetypes
from dataclasses import dataclass
from typing import Any
import httpx
from forwarder.bizdocs.errors import BizdocsAuthError, BizdocsError, BizdocsUploadError
logger = logging.getLogger(__name__)
IDENTITY_ROUTER_URL = "https://bizdocsidentityrouter.azurewebsites.net"
GET_ROUTE_PATH = "/api/GetRoute"
UPLOAD_PATH = "/user/companies/document/file-s3-blob"
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
LOGIN_PATHS = (
"/login",
"/user/login",
"/auth/login",
"/api/login",
"/api/auth/login",
"/user/signInWithPassword",
)
REFRESH_PATHS = (
"/user/getAccessToken",
"/auth/refresh",
"/api/auth/refresh",
"/token/refresh",
)
COMPANIES_PATHS = (
"/user/companies",
"/companies",
"/api/companies",
"/user/getUserCompanies",
)
MOBILE_USER_AGENT = "Bizdocs-Forwarder/1.0 (compatible; Bizdocs Mobi 3.0.2)"
@dataclass(frozen=True)
class BizdocsCredentials:
email: str
password: str
company_id: str
api_base_url: str | None = None
@dataclass
class BizdocsSession:
mobile_api_url: str
access_token: str
refresh_token: str | None = None
def _pick_string(data: dict[str, Any], *keys: str) -> str | None:
for key in keys:
value = data.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _unwrap_payload(body: Any) -> dict[str, Any]:
if not isinstance(body, dict):
return {}
for wrapper in ("data", "result", "payload"):
inner = body.get(wrapper)
if isinstance(inner, dict):
return inner
return body
def _extract_mobile_api_url(body: Any) -> str | None:
data = _unwrap_payload(body)
if not isinstance(data, dict):
return None
return _pick_string(
data,
"mobileApiUrl",
"MobileApiUrl",
"mobile_api_url",
"apiUrl",
"api_url",
"url",
)
def _extract_tokens(body: Any) -> tuple[str | None, str | None]:
data = _unwrap_payload(body)
if not isinstance(data, dict):
return None, None
access = _pick_string(
data,
"accessToken",
"access_token",
"token",
"jwt",
"idToken",
"id_token",
)
refresh = _pick_string(data, "refreshToken", "refresh_token")
return access, refresh
def _extract_document_id(body: Any) -> str | None:
data = _unwrap_payload(body)
if not isinstance(data, dict):
return None
doc_id = _pick_string(data, "id", "documentId", "document_id", "docId", "doc_id")
if doc_id:
return doc_id
document = data.get("document")
if isinstance(document, dict):
return _pick_string(document, "id", "documentId", "document_id")
return None
class BizdocsClient:
def __init__(
self,
*,
identity_router_url: str = IDENTITY_ROUTER_URL,
timeout: float = 60.0,
) -> None:
self._identity_router_url = identity_router_url.rstrip("/")
self._timeout = timeout
def _client(self) -> httpx.Client:
return httpx.Client(
timeout=self._timeout,
follow_redirects=True,
headers={
"Accept": "application/json",
"User-Agent": MOBILE_USER_AGENT,
},
)
def resolve_mobile_api_url(self, email: str, override: str | None = None) -> str:
if override and override.strip():
return override.strip().rstrip("/")
url = f"{self._identity_router_url}{GET_ROUTE_PATH}"
params = {"email": email.strip()}
with self._client() as client:
response = client.get(url, params=params)
if response.status_code == 404:
raise BizdocsError(
"Identity router returned 404 for GetRoute. "
"Set bizdocs_api_base_url on the account if you know the tenant API URL."
)
if response.status_code >= 400:
raise BizdocsError(
f"Identity router failed: HTTP {response.status_code} {response.text[:200]}"
)
if not response.content:
raise BizdocsError("Identity router returned an empty response")
try:
body = response.json()
except ValueError as exc:
raise BizdocsError("Identity router returned non-JSON response") from exc
mobile_url = _extract_mobile_api_url(body)
if not mobile_url:
raise BizdocsError(
f"Identity router response missing mobileApiUrl: {body!r}"
)
return mobile_url.rstrip("/")
def login(self, credentials: BizdocsCredentials) -> BizdocsSession:
mobile_api_url = self.resolve_mobile_api_url(
credentials.email,
credentials.api_base_url,
)
last_error: str | None = None
login_bodies = (
{"email": credentials.email, "password": credentials.password},
{"Email": credentials.email, "Password": credentials.password},
{"username": credentials.email, "password": credentials.password},
)
with self._client() as client:
for path in LOGIN_PATHS:
for body in login_bodies:
url = f"{mobile_api_url}{path}"
try:
response = client.post(url, json=body)
except httpx.HTTPError as exc:
last_error = str(exc)
continue
if response.status_code in (404, 405):
last_error = f"{path}: HTTP {response.status_code}"
continue
if response.status_code >= 400:
last_error = f"{path}: HTTP {response.status_code} {response.text[:200]}"
continue
try:
payload = response.json()
except ValueError:
last_error = f"{path}: non-JSON response"
continue
access, refresh = _extract_tokens(payload)
if access:
logger.info("BizDocs login OK via %s", path)
return BizdocsSession(
mobile_api_url=mobile_api_url,
access_token=access,
refresh_token=refresh,
)
last_error = f"{path}: response missing access token: {payload!r}"
raise BizdocsAuthError(
last_error or f"BizDocs login failed for {credentials.email}"
)
def test_connection(self, credentials: BizdocsCredentials) -> tuple[bool, str]:
try:
session = self.login(credentials)
except BizdocsError as exc:
return False, str(exc)
companies_msg = ""
try:
companies = self.list_companies(session)
if companies:
ids = ", ".join(c["id"] for c in companies[:5])
companies_msg = f"; companies: {ids}"
except BizdocsError as exc:
companies_msg = f"; companies lookup: {exc}"
if credentials.company_id:
return True, f"Login OK ({session.mobile_api_url}){companies_msg}"
return True, f"Login OK ({session.mobile_api_url}){companies_msg} — set company_id"
def list_companies(self, session: BizdocsSession) -> list[dict[str, str]]:
headers = {"Authorization": f"Bearer {session.access_token}"}
with self._client() as client:
for path in COMPANIES_PATHS:
url = f"{session.mobile_api_url}{path}"
try:
response = client.get(url, headers=headers)
except httpx.HTTPError:
continue
if response.status_code >= 400:
continue
try:
body = response.json()
except ValueError:
continue
items = body
if isinstance(body, dict):
for key in ("companies", "data", "items", "results"):
if isinstance(body.get(key), list):
items = body[key]
break
if not isinstance(items, list):
continue
companies: list[dict[str, str]] = []
for item in items:
if not isinstance(item, dict):
continue
company_id = _pick_string(
item,
"id",
"companyId",
"company_id",
"enterpriseId",
"enterprise_id",
)
name = _pick_string(item, "name", "companyName", "company_name") or company_id
if company_id:
companies.append({"id": company_id, "name": name or company_id})
if companies:
return companies
raise BizdocsError("Could not list companies from BizDocs API")
def upload_document(
self,
session: BizdocsSession,
*,
company_id: str,
filename: str,
data: bytes,
content_type: str | None = None,
) -> str:
if len(data) > MAX_UPLOAD_BYTES:
raise BizdocsUploadError(
f"File {filename} exceeds BizDocs limit ({MAX_UPLOAD_BYTES // (1024 * 1024)} MB)"
)
if not content_type:
content_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
url = f"{session.mobile_api_url}{UPLOAD_PATH}"
headers = {"Authorization": f"Bearer {session.access_token}"}
param_variants = (
{"companyId": company_id},
{"company_id": company_id},
{"entityId": company_id},
{"entity_id": company_id},
)
last_error: str | None = None
with self._client() as client:
for params in param_variants:
files = {"file": (filename, data, content_type)}
try:
response = client.post(url, headers=headers, params=params, files=files)
except httpx.HTTPError as exc:
last_error = str(exc)
continue
if response.status_code in (404, 405):
last_error = f"HTTP {response.status_code}"
continue
if response.status_code >= 400:
last_error = f"HTTP {response.status_code} {response.text[:300]}"
continue
doc_id = None
if response.content:
try:
doc_id = _extract_document_id(response.json())
except ValueError:
doc_id = response.text.strip()[:255] or None
if doc_id:
return doc_id
if response.status_code in (200, 201, 204):
return filename
last_error = f"unexpected response: {response.status_code} {response.text[:200]}"
raise BizdocsUploadError(last_error or f"Upload failed for {filename}")
+13
View File
@@ -0,0 +1,13 @@
"""BizDocs API errors."""
class BizdocsError(Exception):
"""Base error for BizDocs API operations."""
class BizdocsAuthError(BizdocsError):
"""Login or token refresh failed."""
class BizdocsUploadError(BizdocsError):
"""Document upload failed."""
+1 -1
View File
@@ -18,7 +18,7 @@ class Settings(BaseSettings):
admin_username: str = "admin" admin_username: str = "admin"
admin_password: str = "change-me" admin_password: str = "change-me"
sync_interval_minutes: int = 15 sync_interval_minutes: int = 15
max_forwards_per_hour: int = 200 max_forwards_per_hour: int = 400
forward_queue_batch_size: int = 5 forward_queue_batch_size: int = 5
forward_queue_interval_seconds: int = 60 forward_queue_interval_seconds: int = 60
api_host: str = "0.0.0.0" api_host: str = "0.0.0.0"
+39 -9
View File
@@ -20,7 +20,17 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from forwarder.db.base import Base from forwarder.db.base import Base
DEFAULT_ALLOWED_EXTENSIONS = [".pdf", ".xml", ".zip"] DEFAULT_ALLOWED_EXTENSIONS = [".pdf", ".xml", ".zip", ".png", ".jpg", ".jpeg"]
class DeliveryMode(str, enum.Enum):
smtp = "smtp"
api = "api"
class SourceType(str, enum.Enum):
imap = "imap"
webdav = "webdav"
class MessageStatus(str, enum.Enum): class MessageStatus(str, enum.Enum):
@@ -42,6 +52,7 @@ class ConnectionTestType(str, enum.Enum):
imap = "imap" imap = "imap"
smtp = "smtp" smtp = "smtp"
send = "send" send = "send"
webdav = "webdav"
class User(Base): class User(Base):
@@ -68,18 +79,36 @@ class Account(Base):
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
sync_interval_minutes: Mapped[int] = mapped_column(Integer, default=15, nullable=False) sync_interval_minutes: Mapped[int] = mapped_column(Integer, default=15, nullable=False)
imap_host: Mapped[str] = mapped_column(String(255), nullable=False) source_type: Mapped[SourceType] = mapped_column(
imap_port: Mapped[int] = mapped_column(Integer, default=993, nullable=False) Enum(SourceType), default=SourceType.imap, nullable=False
imap_user: Mapped[str] = mapped_column(String(255), nullable=False) )
imap_password_encrypted: Mapped[str] = mapped_column(Text, nullable=False)
smtp_host: Mapped[str] = mapped_column(String(255), nullable=False) imap_host: Mapped[str | None] = mapped_column(String(255), nullable=True)
imap_port: Mapped[int] = mapped_column(Integer, default=993, nullable=False)
imap_user: Mapped[str | None] = mapped_column(String(255), nullable=True)
imap_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
webdav_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
webdav_path: Mapped[str | None] = mapped_column(String(512), nullable=True)
webdav_user: Mapped[str | None] = mapped_column(String(255), nullable=True)
webdav_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
webdav_verify_ssl: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
smtp_host: Mapped[str | None] = mapped_column(String(255), nullable=True)
smtp_port: Mapped[int] = mapped_column(Integer, default=587, nullable=False) smtp_port: Mapped[int] = mapped_column(Integer, default=587, nullable=False)
smtp_user: Mapped[str] = mapped_column(String(255), nullable=False) smtp_user: Mapped[str | None] = mapped_column(String(255), nullable=True)
smtp_password_encrypted: Mapped[str] = mapped_column(Text, nullable=False) smtp_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
smtp_use_tls: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) smtp_use_tls: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
destination_email: Mapped[str] = mapped_column(String(255), nullable=False) delivery_mode: Mapped[DeliveryMode] = mapped_column(
Enum(DeliveryMode), default=DeliveryMode.smtp, nullable=False
)
bizdocs_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
bizdocs_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
bizdocs_company_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
bizdocs_api_base_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
destination_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
include_all_attachments: Mapped[bool] = mapped_column( include_all_attachments: Mapped[bool] = mapped_column(
Boolean, default=False, nullable=False Boolean, default=False, nullable=False
) )
@@ -135,6 +164,7 @@ class Message(Base):
Enum(MessageStatus), default=MessageStatus.pending, nullable=False, index=True Enum(MessageStatus), default=MessageStatus.pending, nullable=False, index=True
) )
error_message: Mapped[str | None] = mapped_column(Text, nullable=True) error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
bizdocs_doc_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column( created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), nullable=False DateTime(timezone=True), server_default=func.now(), nullable=False
) )
+210
View File
@@ -0,0 +1,210 @@
"""Invoice attachment validation — reject icons, inline embeds, and unreadable files."""
from __future__ import annotations
import os
import struct
import xml.etree.ElementTree as element_tree
# BizDocs accepts up to 10 MB; icons / tracking pixels are usually tiny.
MIN_IMAGE_BYTES = 8 * 1024
MIN_PDF_BYTES = 1024
MIN_XML_BYTES = 80
MIN_ZIP_BYTES = 22
MIN_IMAGE_WIDTH = 200
MIN_IMAGE_HEIGHT = 200
# Applied only to small image files (likely logos / UI assets).
_ICON_NAME_HINTS = (
"icon",
"logo",
"signature",
"spacer",
"pixel",
"tracking",
"facebook",
"linkedin",
"twitter",
"instagram",
"banner",
"emoji",
"avatar",
"thumb",
"badge",
"footer",
"header",
"social",
"favicon",
"cid",
"image00",
)
_SMALL_IMAGE_BYTES = 32 * 1024
def _extension_from_filename(filename: str) -> str:
_, ext = os.path.splitext(filename.lower())
return ext
def _looks_like_icon_filename(filename: str) -> bool:
base = os.path.splitext(os.path.basename(filename.lower()))[0]
if not base:
return False
for hint in _ICON_NAME_HINTS:
if hint in base:
return True
return False
def _png_dimensions(data: bytes) -> tuple[int, int] | None:
if len(data) < 24 or not data.startswith(b"\x89PNG\r\n\x1a\n"):
return None
width, height = struct.unpack(">II", data[16:24])
if width <= 0 or height <= 0:
return None
return width, height
def _jpeg_dimensions(data: bytes) -> tuple[int, int] | None:
if len(data) < 4 or not data.startswith(b"\xff\xd8"):
return None
index = 2
data_len = len(data)
while index < data_len - 1:
if data[index] != 0xFF:
index += 1
continue
marker = data[index + 1]
if marker in (
0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
):
if index + 9 > data_len:
return None
height = struct.unpack(">H", data[index + 5 : index + 7])[0]
width = struct.unpack(">H", data[index + 7 : index + 9])[0]
if width <= 0 or height <= 0:
return None
return width, height
if marker in (0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD8, 0xD9):
index += 2
continue
if marker == 0xDA:
break
if index + 4 > data_len:
break
segment_length = struct.unpack(">H", data[index + 2 : index + 4])[0]
if segment_length < 2:
break
index += 2 + segment_length
return None
def _image_meets_min_dimensions(data: bytes, ext: str) -> bool:
dimensions = None
if ext in (".png",):
dimensions = _png_dimensions(data)
elif ext in (".jpg", ".jpeg"):
dimensions = _jpeg_dimensions(data)
if dimensions is None:
return False
width, height = dimensions
if width < MIN_IMAGE_WIDTH or height < MIN_IMAGE_HEIGHT:
return False
return True
def _is_valid_pdf(data: bytes) -> bool:
if len(data) < MIN_PDF_BYTES:
return False
if not data.startswith(b"%PDF-"):
return False
return True
def _is_valid_xml(data: bytes) -> bool:
if len(data) < MIN_XML_BYTES:
return False
sample = data.lstrip()
if not sample.startswith(b"<"):
return False
try:
element_tree.fromstring(data)
except element_tree.ParseError:
return False
return True
def _is_valid_zip(data: bytes) -> bool:
if len(data) < MIN_ZIP_BYTES:
return False
if not data.startswith(b"PK"):
return False
return True
def _is_valid_image(data: bytes, ext: str) -> bool:
if len(data) < MIN_IMAGE_BYTES:
return False
if ext == ".png":
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
return False
elif ext in (".jpg", ".jpeg"):
if not data.startswith(b"\xff\xd8"):
return False
else:
return False
if not _image_meets_min_dimensions(data, ext):
return False
return True
def is_plausible_invoice_file(
data: bytes,
*,
filename: str,
content_type: str,
) -> bool:
"""Return True when decoded bytes look like a real invoice document, not an embed/icon."""
if not data:
return False
ext = _extension_from_filename(filename)
content_type = (content_type or "").lower()
if ext in (".png", ".jpg", ".jpeg") or content_type.startswith("image/"):
if len(data) < MIN_IMAGE_BYTES:
return False
if len(data) <= _SMALL_IMAGE_BYTES and _looks_like_icon_filename(filename):
return False
if ext in (".png", ".jpg", ".jpeg"):
return _is_valid_image(data, ext)
if content_type == "image/png":
return _is_valid_image(data, ".png")
if content_type in ("image/jpeg", "image/jpg"):
return _is_valid_image(data, ".jpeg")
return False
if ext == ".pdf" or content_type == "application/pdf":
return _is_valid_pdf(data)
if ext == ".xml" or content_type in ("application/xml", "text/xml"):
return _is_valid_xml(data)
if ext == ".zip" or content_type in ("application/zip", "application/x-zip-compressed"):
return _is_valid_zip(data)
return False
+48 -9
View File
@@ -10,7 +10,9 @@ from email.header import decode_header, make_header
from email.message import EmailMessage from email.message import EmailMessage
from email.utils import parsedate_to_datetime from email.utils import parsedate_to_datetime
DEFAULT_ALLOWED_EXTENSIONS = {".pdf", ".xml", ".zip"} from forwarder.email.invoice_validation import is_plausible_invoice_file
DEFAULT_ALLOWED_EXTENSIONS = {".pdf", ".xml", ".zip", ".png", ".jpg", ".jpeg"}
ALLOWED_MIME_TYPES = { ALLOWED_MIME_TYPES = {
"application/pdf", "application/pdf",
@@ -18,8 +20,13 @@ ALLOWED_MIME_TYPES = {
"text/xml", "text/xml",
"application/zip", "application/zip",
"application/x-zip-compressed", "application/x-zip-compressed",
"image/png",
"image/jpeg",
"image/jpg",
} }
MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
def clean_header(value: str | None) -> str: def clean_header(value: str | None) -> str:
if not value: if not value:
@@ -80,25 +87,57 @@ def part_filename(part: email.message.Message) -> str:
def is_real_attachment(part: email.message.Message) -> bool: def is_real_attachment(part: email.message.Message) -> bool:
"""True for explicit file attachments — not inline HTML embeds (logos, tracking pixels)."""
disposition = (part.get_content_disposition() or "").lower() disposition = (part.get_content_disposition() or "").lower()
filename = part_filename(part) filename = part_filename(part)
content_type = (part.get_content_type() or "").lower() content_type = (part.get_content_type() or "").lower()
if disposition == "inline" and not filename: if disposition == "inline":
return False return False
if disposition == "attachment": if disposition == "attachment":
return True if filename:
return True
return content_type in ALLOWED_MIME_TYPES
if filename: if filename:
return True _, ext = os.path.splitext(filename)
if ext in DEFAULT_ALLOWED_EXTENSIONS:
if content_type in ALLOWED_MIME_TYPES: return True
return True
return False return False
def _part_passes_invoice_checks(
part: email.message.Message,
*,
include_all_attachments: bool,
allowed_extensions: set[str],
) -> bool:
if not attachment_allowed(
part,
include_all_attachments=include_all_attachments,
allowed_extensions=allowed_extensions,
):
return False
payload = part.get_payload(decode=True)
if not payload:
return False
if len(payload) > MAX_ATTACHMENT_BYTES:
return False
filename = part_filename(part) or part.get_filename() or "attachment"
filename = clean_header(filename) or "attachment"
content_type = part.get_content_type() or ""
return is_plausible_invoice_file(
payload,
filename=filename,
content_type=content_type,
)
def attachment_allowed( def attachment_allowed(
part: email.message.Message, part: email.message.Message,
*, *,
@@ -152,7 +191,7 @@ def collect_matching_attachments(
for part in msg.walk(): for part in msg.walk():
if part.is_multipart(): if part.is_multipart():
continue continue
if not attachment_allowed( if not _part_passes_invoice_checks(
part, part,
include_all_attachments=include_all_attachments, include_all_attachments=include_all_attachments,
allowed_extensions=allowed_extensions, allowed_extensions=allowed_extensions,
@@ -198,7 +237,7 @@ def has_matching_attachment(
for part in msg.walk(): for part in msg.walk():
if part.is_multipart(): if part.is_multipart():
continue continue
if attachment_allowed( if _part_passes_invoice_checks(
part, part,
include_all_attachments=include_all_attachments, include_all_attachments=include_all_attachments,
allowed_extensions=allowed_extensions, allowed_extensions=allowed_extensions,
+216 -15
View File
@@ -10,9 +10,13 @@ from forwarder.db.models import (
ConnectionTest, ConnectionTest,
ConnectionTestType, ConnectionTestType,
DEFAULT_ALLOWED_EXTENSIONS, DEFAULT_ALLOWED_EXTENSIONS,
DeliveryMode,
SourceType,
) )
from forwarder.email.imap_client import ImapConfig, test_imap_connection from forwarder.email.imap_client import ImapConfig, test_imap_connection
from forwarder.email.smtp_client import SmtpConfig, send_test_email, test_smtp_connection from forwarder.email.smtp_client import SmtpConfig, send_test_email, test_smtp_connection
from forwarder.services.delivery_service import test_bizdocs_delivery
from forwarder.webdav.client import WebdavConfig, test_connection as test_webdav_connection
class AccountNotFoundError(Exception): class AccountNotFoundError(Exception):
@@ -35,29 +39,48 @@ def _normalize_extensions(extensions: list[str] | None) -> list[str]:
def account_to_dict(account: Account, *, include_secrets: bool = False) -> dict: def account_to_dict(account: Account, *, include_secrets: bool = False) -> dict:
delivery_mode = account.delivery_mode.value if account.delivery_mode else DeliveryMode.smtp.value
source_type = account.source_type.value if account.source_type else SourceType.imap.value
data = { data = {
"id": account.id, "id": account.id,
"name": account.name, "name": account.name,
"enabled": account.enabled, "enabled": account.enabled,
"sync_interval_minutes": account.sync_interval_minutes, "sync_interval_minutes": account.sync_interval_minutes,
"source_type": source_type,
"imap_host": account.imap_host, "imap_host": account.imap_host,
"imap_port": account.imap_port, "imap_port": account.imap_port,
"imap_user": account.imap_user, "imap_user": account.imap_user,
"imap_password": mask_password(), "imap_password": mask_password(),
"webdav_url": account.webdav_url,
"webdav_path": account.webdav_path,
"webdav_user": account.webdav_user,
"webdav_password": mask_password(),
"webdav_verify_ssl": account.webdav_verify_ssl,
"delivery_mode": delivery_mode,
"smtp_host": account.smtp_host, "smtp_host": account.smtp_host,
"smtp_port": account.smtp_port, "smtp_port": account.smtp_port,
"smtp_user": account.smtp_user, "smtp_user": account.smtp_user,
"smtp_password": mask_password(), "smtp_password": mask_password(),
"smtp_use_tls": account.smtp_use_tls, "smtp_use_tls": account.smtp_use_tls,
"destination_email": account.destination_email, "destination_email": account.destination_email,
"bizdocs_email": account.bizdocs_email,
"bizdocs_password": mask_password(),
"bizdocs_company_id": account.bizdocs_company_id,
"bizdocs_api_base_url": account.bizdocs_api_base_url,
"include_all_attachments": account.include_all_attachments, "include_all_attachments": account.include_all_attachments,
"allowed_extensions": account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS), "allowed_extensions": account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS),
"created_at": account.created_at, "created_at": account.created_at,
"updated_at": account.updated_at, "updated_at": account.updated_at,
} }
if include_secrets: if include_secrets:
data["imap_password_plain"] = decrypt_password(account.imap_password_encrypted) if account.imap_password_encrypted:
data["smtp_password_plain"] = decrypt_password(account.smtp_password_encrypted) data["imap_password_plain"] = decrypt_password(account.imap_password_encrypted)
if account.webdav_password_encrypted:
data["webdav_password_plain"] = decrypt_password(account.webdav_password_encrypted)
if account.smtp_password_encrypted:
data["smtp_password_plain"] = decrypt_password(account.smtp_password_encrypted)
if account.bizdocs_password_encrypted:
data["bizdocs_password_plain"] = decrypt_password(account.bizdocs_password_encrypted)
return data return data
@@ -72,22 +95,67 @@ def get_account(db: Session, account_id: int) -> Account:
return account return account
def _parse_delivery_mode(value: str | None) -> DeliveryMode:
if not value or value == "smtp":
return DeliveryMode.smtp
if value == "api":
return DeliveryMode.api
raise ValueError(f"Invalid delivery_mode: {value}")
def _parse_source_type(value: str | None) -> SourceType:
if not value or value == "imap":
return SourceType.imap
if value == "webdav":
return SourceType.webdav
raise ValueError(f"Invalid source_type: {value}")
def create_account(db: Session, data: dict) -> Account: def create_account(db: Session, data: dict) -> Account:
settings_sync = data.get("sync_interval_minutes") settings_sync = data.get("sync_interval_minutes")
delivery_mode = _parse_delivery_mode(data.get("delivery_mode"))
source_type = _parse_source_type(data.get("source_type"))
account = Account( account = Account(
name=data["name"], name=data["name"],
enabled=data.get("enabled", True), enabled=data.get("enabled", True),
sync_interval_minutes=settings_sync if settings_sync is not None else 15, sync_interval_minutes=settings_sync if settings_sync is not None else 15,
imap_host=data["imap_host"], source_type=source_type,
imap_host=data.get("imap_host") if source_type == SourceType.imap else None,
imap_port=data.get("imap_port", 993), imap_port=data.get("imap_port", 993),
imap_user=data["imap_user"], imap_user=data.get("imap_user") if source_type == SourceType.imap else None,
imap_password_encrypted=encrypt_password(data["imap_password"]), imap_password_encrypted=(
smtp_host=data["smtp_host"], encrypt_password(data["imap_password"])
if source_type == SourceType.imap and data.get("imap_password")
else None
),
webdav_url=data.get("webdav_url") if source_type == SourceType.webdav else None,
webdav_path=data.get("webdav_path") if source_type == SourceType.webdav else None,
webdav_user=data.get("webdav_user") if source_type == SourceType.webdav else None,
webdav_password_encrypted=(
encrypt_password(data["webdav_password"])
if source_type == SourceType.webdav and data.get("webdav_password")
else None
),
webdav_verify_ssl=data.get("webdav_verify_ssl", True),
delivery_mode=delivery_mode,
smtp_host=data.get("smtp_host"),
smtp_port=data.get("smtp_port", 587), smtp_port=data.get("smtp_port", 587),
smtp_user=data["smtp_user"], smtp_user=data.get("smtp_user"),
smtp_password_encrypted=encrypt_password(data["smtp_password"]), smtp_password_encrypted=(
encrypt_password(data["smtp_password"]) if data.get("smtp_password") else None
),
smtp_use_tls=data.get("smtp_use_tls", True), smtp_use_tls=data.get("smtp_use_tls", True),
destination_email=data["destination_email"], destination_email=data.get("destination_email"),
bizdocs_email=(
data.get("bizdocs_email")
or data.get("imap_user")
or data.get("webdav_user")
),
bizdocs_password_encrypted=(
encrypt_password(data["bizdocs_password"]) if data.get("bizdocs_password") else None
),
bizdocs_company_id=data.get("bizdocs_company_id") or data.get("bizdocs_entity_id"),
bizdocs_api_base_url=data.get("bizdocs_api_base_url"),
include_all_attachments=data.get("include_all_attachments", False), include_all_attachments=data.get("include_all_attachments", False),
allowed_extensions=_normalize_extensions(data.get("allowed_extensions")), allowed_extensions=_normalize_extensions(data.get("allowed_extensions")),
) )
@@ -100,12 +168,36 @@ def create_account(db: Session, data: dict) -> Account:
def update_account(db: Session, account_id: int, data: dict) -> Account: def update_account(db: Session, account_id: int, data: dict) -> Account:
account = get_account(db, account_id) account = get_account(db, account_id)
for field in ("name", "enabled", "sync_interval_minutes", "imap_host", "imap_port", for field in (
"imap_user", "smtp_host", "smtp_port", "smtp_user", "smtp_use_tls", "name",
"destination_email", "include_all_attachments"): "enabled",
"sync_interval_minutes",
"imap_host",
"imap_port",
"imap_user",
"webdav_url",
"webdav_path",
"webdav_user",
"webdav_verify_ssl",
"smtp_host",
"smtp_port",
"smtp_user",
"smtp_use_tls",
"destination_email",
"include_all_attachments",
"bizdocs_email",
"bizdocs_company_id",
"bizdocs_api_base_url",
):
if field in data and data[field] is not None: if field in data and data[field] is not None:
setattr(account, field, data[field]) setattr(account, field, data[field])
if "source_type" in data and data["source_type"] is not None:
account.source_type = _parse_source_type(data["source_type"])
if "delivery_mode" in data and data["delivery_mode"] is not None:
account.delivery_mode = _parse_delivery_mode(data["delivery_mode"])
if "allowed_extensions" in data and data["allowed_extensions"] is not None: if "allowed_extensions" in data and data["allowed_extensions"] is not None:
account.allowed_extensions = _normalize_extensions(data["allowed_extensions"]) account.allowed_extensions = _normalize_extensions(data["allowed_extensions"])
@@ -113,10 +205,18 @@ def update_account(db: Session, account_id: int, data: dict) -> Account:
if imap_password: if imap_password:
account.imap_password_encrypted = encrypt_password(imap_password) account.imap_password_encrypted = encrypt_password(imap_password)
webdav_password = data.get("webdav_password")
if webdav_password:
account.webdav_password_encrypted = encrypt_password(webdav_password)
smtp_password = data.get("smtp_password") smtp_password = data.get("smtp_password")
if smtp_password: if smtp_password:
account.smtp_password_encrypted = encrypt_password(smtp_password) account.smtp_password_encrypted = encrypt_password(smtp_password)
bizdocs_password = data.get("bizdocs_password")
if bizdocs_password:
account.bizdocs_password_encrypted = encrypt_password(bizdocs_password)
account.updated_at = datetime.now(timezone.utc) account.updated_at = datetime.now(timezone.utc)
db.commit() db.commit()
db.refresh(account) db.refresh(account)
@@ -146,6 +246,8 @@ def resolve_imap_config(db: Session, account_id: int | None, inline: dict | None
raise ValueError("account_id or inline config required") raise ValueError("account_id or inline config required")
account = get_account(db, account_id) account = get_account(db, account_id)
if not account.imap_host or not account.imap_user or not account.imap_password_encrypted:
raise ValueError("IMAP is not configured for this account")
return ImapConfig( return ImapConfig(
host=account.imap_host, host=account.imap_host,
port=account.imap_port, port=account.imap_port,
@@ -154,16 +256,59 @@ def resolve_imap_config(db: Session, account_id: int | None, inline: dict | None
) )
def resolve_webdav_config(
db: Session, account_id: int | None, inline: dict | None
) -> WebdavConfig:
from forwarder.webdav.client import normalize_webdav_folder_path
if inline:
password = inline.get("webdav_password") or inline.get("password") or ""
if not password and account_id is not None:
account = get_account(db, account_id)
if account.webdav_password_encrypted:
password = decrypt_password(account.webdav_password_encrypted)
url = inline.get("webdav_url") or ""
user = inline.get("webdav_user") or ""
if not url or not user:
raise ValueError("webdav_url and webdav_user required")
return WebdavConfig(
base_url=url,
folder_path=normalize_webdav_folder_path(inline.get("webdav_path")),
user=user,
password=password,
verify_ssl=inline.get("webdav_verify_ssl", True),
)
if account_id is None:
raise ValueError("account_id or inline config required")
account = get_account(db, account_id)
if not account.webdav_url or not account.webdav_user or not account.webdav_password_encrypted:
raise ValueError("WebDAV is not configured for this account")
return WebdavConfig(
base_url=account.webdav_url,
folder_path=normalize_webdav_folder_path(account.webdav_path),
user=account.webdav_user,
password=decrypt_password(account.webdav_password_encrypted),
verify_ssl=account.webdav_verify_ssl,
)
def resolve_smtp_config(db: Session, account_id: int | None, inline: dict | None) -> SmtpConfig: def resolve_smtp_config(db: Session, account_id: int | None, inline: dict | None) -> SmtpConfig:
if inline: if inline:
password = inline.get("smtp_password") or inline.get("password") or "" password = inline.get("smtp_password") or inline.get("password") or ""
if not password and account_id is not None: if not password and account_id is not None:
account = get_account(db, account_id) account = get_account(db, account_id)
password = decrypt_password(account.smtp_password_encrypted) if account.smtp_password_encrypted:
password = decrypt_password(account.smtp_password_encrypted)
host = inline.get("smtp_host") or ""
user = inline.get("smtp_user") or ""
if not host or not user:
raise ValueError("smtp_host and smtp_user required")
return SmtpConfig( return SmtpConfig(
host=inline["smtp_host"], host=host,
port=int(inline.get("smtp_port", 587)), port=int(inline.get("smtp_port", 587)),
user=inline["smtp_user"], user=user,
password=password, password=password,
use_tls=inline.get("smtp_use_tls", True), use_tls=inline.get("smtp_use_tls", True),
) )
@@ -172,6 +317,8 @@ def resolve_smtp_config(db: Session, account_id: int | None, inline: dict | None
raise ValueError("account_id or inline config required") raise ValueError("account_id or inline config required")
account = get_account(db, account_id) account = get_account(db, account_id)
if not account.smtp_host or not account.smtp_user or not account.smtp_password_encrypted:
raise ValueError("SMTP is not configured for this account")
return SmtpConfig( return SmtpConfig(
host=account.smtp_host, host=account.smtp_host,
port=account.smtp_port, port=account.smtp_port,
@@ -239,3 +386,57 @@ def run_send_test(db: Session, account_id: int | None, inline: dict | None) -> t
success=success, message=message, success=success, message=message,
) )
return success, message return success, message
def run_bizdocs_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]:
if account_id is not None:
account = get_account(db, account_id)
password = ""
if inline and inline.get("bizdocs_password"):
password = inline["bizdocs_password"]
elif account.bizdocs_password_encrypted:
password = decrypt_password(account.bizdocs_password_encrypted)
if inline:
if inline.get("bizdocs_email"):
account.bizdocs_email = inline["bizdocs_email"]
if inline.get("bizdocs_company_id"):
account.bizdocs_company_id = inline["bizdocs_company_id"]
if inline.get("bizdocs_api_base_url"):
account.bizdocs_api_base_url = inline["bizdocs_api_base_url"]
else:
if not inline:
raise ValueError("account_id or inline config required")
password = inline.get("bizdocs_password") or ""
account = Account(
imap_user=inline.get("imap_user") or inline.get("bizdocs_email") or "",
bizdocs_email=inline.get("bizdocs_email") or inline.get("imap_user"),
bizdocs_company_id=inline.get("bizdocs_company_id"),
bizdocs_api_base_url=inline.get("bizdocs_api_base_url"),
delivery_mode=DeliveryMode.api,
)
if not password:
raise ValueError("BizDocs password is required")
success, message = test_bizdocs_delivery(account, password)
record_connection_test(
db,
account_id=account_id,
test_type=ConnectionTestType.send,
success=success,
message=f"BizDocs: {message}",
)
return success, message
def run_webdav_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]:
config = resolve_webdav_config(db, account_id, inline)
success, message = test_webdav_connection(config)
record_connection_test(
db,
account_id=account_id,
test_type=ConnectionTestType.webdav,
success=success,
message=message,
)
return success, message
+208
View File
@@ -0,0 +1,208 @@
"""Deliver matched email attachments to BizDocs (API or SMTP)."""
from __future__ import annotations
import logging
import mimetypes
import os
from email.message import EmailMessage
import smtplib
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials, BizdocsSession
from forwarder.bizdocs.errors import BizdocsError
from forwarder.db.models import Account, DEFAULT_ALLOWED_EXTENSIONS, DeliveryMode
from forwarder.email.invoice_validation import is_plausible_invoice_file
from forwarder.email.parsing import InvoiceAttachment, collect_matching_attachments
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments
logger = logging.getLogger(__name__)
def _bizdocs_credentials(account: Account, password: str) -> BizdocsCredentials:
email = (account.bizdocs_email or account.imap_user or account.webdav_user or "").strip()
company_id = (account.bizdocs_company_id or "").strip()
if not email:
raise ValueError("BizDocs email is required for API delivery")
if not password:
raise ValueError("BizDocs password is required for API delivery")
if not company_id:
raise ValueError("BizDocs company_id is required for API delivery")
api_base = account.bizdocs_api_base_url
if api_base:
api_base = api_base.strip() or None
return BizdocsCredentials(
email=email,
password=password,
company_id=company_id,
api_base_url=api_base,
)
def open_bizdocs_session(account: Account, bizdocs_password: str) -> BizdocsSession:
client = BizdocsClient()
credentials = _bizdocs_credentials(account, bizdocs_password)
return client.login(credentials)
def _extension_allowed(filename: str, allowed_extensions: set[str], include_all: bool) -> bool:
if include_all:
return True
_, ext = os.path.splitext(filename.lower())
return ext in allowed_extensions
def _content_type_for_filename(filename: str) -> str:
guessed = mimetypes.guess_type(filename)[0]
if guessed:
return guessed
return "application/octet-stream"
def _build_synthetic_email(
*,
filename: str,
data: bytes,
content_type: str,
source_label: str,
) -> EmailMessage:
msg = EmailMessage()
msg["Subject"] = filename
msg["From"] = source_label
msg.set_content(
f"Documento importado automaticamente.\n\nOrigem: {source_label}\nFicheiro: {filename}\n"
)
maintype, _, subtype = content_type.partition("/")
if not subtype:
maintype, subtype = "application", "octet-stream"
msg.add_attachment(
data,
maintype=maintype,
subtype=subtype,
filename=filename,
disposition="attachment",
)
return msg
def deliver_invoice_file(
account: Account,
*,
filename: str,
data: bytes,
content_type: str | None = None,
source_label: str = "forwarder",
bizdocs_password: str | None = None,
smtp_config: SmtpConfig | None = None,
smtp: smtplib.SMTP | None = None,
bizdocs_session: BizdocsSession | None = None,
) -> list[str]:
"""Validate and deliver a single invoice file to BizDocs."""
if content_type is None:
content_type = _content_type_for_filename(filename)
if not is_plausible_invoice_file(data, filename=filename, content_type=content_type):
raise ValueError(f"File {filename} failed invoice validation")
if account.delivery_mode == DeliveryMode.api:
if bizdocs_session is None:
if not bizdocs_password:
raise ValueError("BizDocs password required")
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
client = BizdocsClient()
doc_id = client.upload_document(
bizdocs_session,
company_id=account.bizdocs_company_id or "",
filename=filename,
data=data,
content_type=content_type,
)
logger.info("Uploaded %s → BizDocs doc %s", filename, doc_id)
return [doc_id]
if smtp_config is None:
raise ValueError("SMTP config required for email delivery")
synthetic = _build_synthetic_email(
filename=filename,
data=data,
content_type=content_type,
source_label=source_label,
)
forward_invoice_attachments(
synthetic,
smtp_config=smtp_config,
destination_email=account.destination_email or "",
smtp=smtp,
include_all_attachments=True,
)
return []
def deliver_message_attachments(
msg: EmailMessage,
account: Account,
*,
bizdocs_password: str | None = None,
smtp_config: SmtpConfig | None = None,
smtp: smtplib.SMTP | None = None,
bizdocs_session: BizdocsSession | None = None,
) -> list[str]:
"""Upload or SMTP-forward attachments. Returns BizDocs document ids when using API."""
allowed_extensions = set(account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS))
if account.delivery_mode == DeliveryMode.api:
if bizdocs_session is None:
if not bizdocs_password:
raise ValueError("BizDocs password required")
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
attachments = collect_matching_attachments(
msg,
include_all_attachments=account.include_all_attachments,
allowed_extensions=allowed_extensions,
)
if not attachments:
raise ValueError("No matching attachments to upload")
client = BizdocsClient()
doc_ids: list[str] = []
for attachment in attachments:
doc_id = client.upload_document(
bizdocs_session,
company_id=account.bizdocs_company_id or "",
filename=attachment.filename,
data=attachment.data,
content_type=f"{attachment.maintype}/{attachment.subtype}",
)
doc_ids.append(doc_id)
logger.info("Uploaded %s → BizDocs doc %s", attachment.filename, doc_id)
return doc_ids
if smtp_config is None:
raise ValueError("SMTP config required for email delivery")
forward_invoice_attachments(
msg,
smtp_config=smtp_config,
destination_email=account.destination_email or "",
smtp=smtp,
include_all_attachments=account.include_all_attachments,
allowed_extensions=allowed_extensions,
)
return []
def test_bizdocs_delivery(
account: Account,
bizdocs_password: str,
) -> tuple[bool, str]:
client = BizdocsClient()
try:
credentials = _bizdocs_credentials(account, bizdocs_password)
return client.test_connection(credentials)
except (BizdocsError, ValueError) as exc:
return False, str(exc)
+88 -30
View File
@@ -10,9 +10,12 @@ from sqlalchemy.orm import Session
from forwarder.crypto import decrypt_password from forwarder.crypto import decrypt_password
from forwarder.db.models import ( from forwarder.db.models import (
Account, Account,
DEFAULT_ALLOWED_EXTENSIONS,
DeliveryMode,
ForwardAttempt, ForwardAttempt,
Message, Message,
MessageStatus, MessageStatus,
SourceType,
SyncRun, SyncRun,
SyncRunStatus, SyncRunStatus,
) )
@@ -29,9 +32,10 @@ from forwarder.email.parsing import (
get_message_key, get_message_key,
has_matching_attachment, has_matching_attachment,
) )
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments from forwarder.email.smtp_client import SmtpConfig, create_smtp_client
from forwarder.error_reporter import report_error, report_error_with_cooldown from forwarder.error_reporter import report_error, report_error_with_cooldown
from forwarder.services.account_service import get_account from forwarder.services.account_service import get_account
from forwarder.services.delivery_service import deliver_message_attachments, open_bizdocs_session
from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -46,9 +50,13 @@ class MessageMissingFromMailboxError(Exception):
def is_missing_from_mailbox_error(error_text: str) -> bool: def is_missing_from_mailbox_error(error_text: str) -> bool:
return error_text.startswith("Could not fetch message UID") or error_text.startswith( if error_text.startswith("Could not fetch message UID"):
"Could not open folder:" return True
) if error_text.startswith("Could not open folder:"):
return True
if error_text.startswith("WebDAV file not found"):
return True
return False
class SyncResult: class SyncResult:
@@ -82,6 +90,7 @@ def _upsert_message(
date: str, date: str,
status: MessageStatus, status: MessageStatus,
error_message: str | None = None, error_message: str | None = None,
bizdocs_doc_id: str | None = None,
) -> Message: ) -> Message:
existing = ( existing = (
db.query(Message) db.query(Message)
@@ -91,6 +100,8 @@ def _upsert_message(
if existing is not None: if existing is not None:
existing.status = status existing.status = status
existing.error_message = error_message existing.error_message = error_message
if bizdocs_doc_id is not None:
existing.bizdocs_doc_id = bizdocs_doc_id
existing.updated_at = datetime.now(timezone.utc) existing.updated_at = datetime.now(timezone.utc)
db.commit() db.commit()
db.refresh(existing) db.refresh(existing)
@@ -106,6 +117,7 @@ def _upsert_message(
date=date, date=date,
status=status, status=status,
error_message=error_message, error_message=error_message,
bizdocs_doc_id=bizdocs_doc_id,
) )
db.add(msg) db.add(msg)
db.commit() db.commit()
@@ -149,9 +161,21 @@ def sync_account(
db.commit() db.commit()
db.refresh(sync_run) db.refresh(sync_run)
if account.source_type == SourceType.webdav:
from forwarder.services.webdav_sync_service import sync_webdav_account
return sync_webdav_account(
db,
account,
sync_run,
dry_run=dry_run,
max_files=max_emails,
)
result = SyncResult() result = SyncResult()
imap = None imap = None
smtp = None smtp = None
bizdocs_session = None
try: try:
imap_config = ImapConfig( imap_config = ImapConfig(
@@ -160,21 +184,35 @@ def sync_account(
user=account.imap_user, user=account.imap_user,
password=decrypt_password(account.imap_password_encrypted), password=decrypt_password(account.imap_password_encrypted),
) )
smtp_config = SmtpConfig( smtp_config = None
host=account.smtp_host, bizdocs_password = None
port=account.smtp_port, if account.delivery_mode == DeliveryMode.smtp:
user=account.smtp_user, if not account.smtp_host or not account.smtp_user or not account.smtp_password_encrypted:
password=decrypt_password(account.smtp_password_encrypted), raise ValueError("SMTP delivery requires smtp_host, smtp_user and smtp_password")
use_tls=account.smtp_use_tls, smtp_config = SmtpConfig(
) host=account.smtp_host,
port=account.smtp_port,
user=account.smtp_user,
password=decrypt_password(account.smtp_password_encrypted),
use_tls=account.smtp_use_tls,
)
else:
if not account.bizdocs_password_encrypted:
raise ValueError("API delivery requires bizdocs_password")
bizdocs_password = decrypt_password(account.bizdocs_password_encrypted)
allowed_extensions = set(account.allowed_extensions or []) allowed_extensions = set(
account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS)
)
processed_keys = _get_known_message_keys(db, account_id) processed_keys = _get_known_message_keys(db, account_id)
stop_all = False stop_all = False
imap = connect_imap(imap_config) imap = connect_imap(imap_config)
if not dry_run: if not dry_run:
smtp = create_smtp_client(smtp_config) if account.delivery_mode == DeliveryMode.smtp and smtp_config is not None:
smtp = create_smtp_client(smtp_config)
elif bizdocs_password:
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
folders = list_mailboxes(imap) folders = list_mailboxes(imap)
logger.info("Account %s: %d mailbox(es)", account_id, len(folders)) logger.info("Account %s: %d mailbox(es)", account_id, len(folders))
@@ -265,14 +303,15 @@ def sync_account(
try: try:
check_forward_allowed(db) check_forward_allowed(db)
forward_invoice_attachments( doc_ids = deliver_message_attachments(
msg, msg,
account,
bizdocs_password=bizdocs_password,
smtp_config=smtp_config, smtp_config=smtp_config,
destination_email=account.destination_email,
smtp=smtp, smtp=smtp,
include_all_attachments=account.include_all_attachments, bizdocs_session=bizdocs_session,
allowed_extensions=allowed_extensions,
) )
doc_id_str = ",".join(doc_ids) if doc_ids else None
message_row = _upsert_message( message_row = _upsert_message(
db, db,
account_id=account_id, account_id=account_id,
@@ -283,6 +322,7 @@ def sync_account(
from_addr=from_addr, from_addr=from_addr,
date=date, date=date,
status=MessageStatus.forwarded, status=MessageStatus.forwarded,
bizdocs_doc_id=doc_id_str,
) )
_record_forward_attempt( _record_forward_attempt(
db, message=message_row, success=True, dry_run=False, db, message=message_row, success=True, dry_run=False,
@@ -418,22 +458,35 @@ def retry_single_message(db: Session, message_id: int) -> Message:
) )
account = get_account(db, message.account_id) account = get_account(db, message.account_id)
message_key = message.message_key if isinstance(message.message_key, str) else ""
if account.source_type == SourceType.webdav or message_key.startswith("webdav:"):
from forwarder.services.webdav_sync_service import retry_webdav_message
return retry_webdav_message(db, message, account)
imap_config = ImapConfig( imap_config = ImapConfig(
host=account.imap_host, host=account.imap_host,
port=account.imap_port, port=account.imap_port,
user=account.imap_user, user=account.imap_user,
password=decrypt_password(account.imap_password_encrypted), password=decrypt_password(account.imap_password_encrypted),
) )
smtp_config = SmtpConfig( smtp_config = None
host=account.smtp_host, bizdocs_password = None
port=account.smtp_port, if account.delivery_mode == DeliveryMode.smtp:
user=account.smtp_user, smtp_config = SmtpConfig(
password=decrypt_password(account.smtp_password_encrypted), host=account.smtp_host or "",
use_tls=account.smtp_use_tls, port=account.smtp_port,
) user=account.smtp_user or "",
password=decrypt_password(account.smtp_password_encrypted or ""),
use_tls=account.smtp_use_tls,
)
else:
bizdocs_password = decrypt_password(account.bizdocs_password_encrypted or "")
imap = None imap = None
smtp = None smtp = None
bizdocs_session = None
try: try:
imap = connect_imap(imap_config) imap = connect_imap(imap_config)
if not select_folder_readonly(imap, message.folder): if not select_folder_readonly(imap, message.folder):
@@ -454,20 +507,25 @@ def retry_single_message(db: Session, message_id: int) -> Message:
) )
raise MessageMissingFromMailboxError(marked, marked.error_message or "") raise MessageMissingFromMailboxError(marked, marked.error_message or "")
smtp = create_smtp_client(smtp_config) smtp = None
allowed_extensions = set(account.allowed_extensions or []) if account.delivery_mode == DeliveryMode.smtp and smtp_config is not None:
smtp = create_smtp_client(smtp_config)
elif bizdocs_password:
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
check_forward_allowed(db) check_forward_allowed(db)
forward_invoice_attachments( doc_ids = deliver_message_attachments(
msg, msg,
account,
bizdocs_password=bizdocs_password,
smtp_config=smtp_config, smtp_config=smtp_config,
destination_email=account.destination_email,
smtp=smtp, smtp=smtp,
include_all_attachments=account.include_all_attachments, bizdocs_session=bizdocs_session,
allowed_extensions=allowed_extensions,
) )
message.status = MessageStatus.forwarded message.status = MessageStatus.forwarded
message.error_message = None message.error_message = None
message.bizdocs_doc_id = ",".join(doc_ids) if doc_ids else message.bizdocs_doc_id
message.updated_at = datetime.now(timezone.utc) message.updated_at = datetime.now(timezone.utc)
_record_forward_attempt(db, message=message, success=True, dry_run=False) _record_forward_attempt(db, message=message, success=True, dry_run=False)
db.commit() db.commit()
@@ -0,0 +1,371 @@
"""WebDAV account sync — scan folder and forward invoice files."""
from __future__ import annotations
import logging
import os
from datetime import datetime, timezone
import smtplib
from sqlalchemy.orm import Session
from forwarder.crypto import decrypt_password
from forwarder.db.models import (
Account,
DEFAULT_ALLOWED_EXTENSIONS,
DeliveryMode,
Message,
MessageStatus,
SyncRun,
SyncRunStatus,
)
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client
from forwarder.error_reporter import report_error, report_error_with_cooldown
from forwarder.services.delivery_service import (
_extension_allowed,
deliver_invoice_file,
open_bizdocs_session,
)
from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed
from forwarder.services.sync_service import (
MessageMissingFromMailboxError,
SyncResult,
_get_known_message_keys,
_mark_missing_from_mailbox,
_record_forward_attempt,
_upsert_message,
is_missing_from_mailbox_error,
)
from forwarder.webdav.client import (
WebdavConfig,
WebdavNotFoundError,
download_file,
get_webdav_message_key,
list_files,
normalize_webdav_folder_path,
parse_webdav_message_key,
)
logger = logging.getLogger(__name__)
def resolve_webdav_config(account: Account) -> WebdavConfig:
if not account.webdav_url or not account.webdav_user or not account.webdav_password_encrypted:
raise ValueError("WebDAV url, user and password are required")
return WebdavConfig(
base_url=account.webdav_url,
folder_path=normalize_webdav_folder_path(account.webdav_path),
user=account.webdav_user,
password=decrypt_password(account.webdav_password_encrypted),
verify_ssl=account.webdav_verify_ssl,
)
def sync_webdav_account(
db: Session,
account: Account,
sync_run,
*,
dry_run: bool = False,
max_files: int | None = None,
) -> SyncRun:
account_id = account.id
result = SyncResult()
smtp = None
bizdocs_session = None
try:
webdav_config = resolve_webdav_config(account)
smtp_config, bizdocs_password = _resolve_delivery_for_account(account)
allowed_extensions = set(account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS))
processed_keys = _get_known_message_keys(db, account_id)
folder_label = normalize_webdav_folder_path(account.webdav_path)
if not dry_run:
if account.delivery_mode == DeliveryMode.smtp and smtp_config is not None:
smtp = create_smtp_client(smtp_config)
elif bizdocs_password:
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
remote_files = list_files(webdav_config)
logger.info("Account %s WebDAV: %d file(s) listed", account_id, len(remote_files))
stop_all = False
for remote_file in sorted(remote_files, key=lambda item: item.relative_path):
if max_files is not None and result.messages_scanned >= max_files:
stop_all = True
break
if stop_all:
break
result.messages_scanned += 1
filename = remote_file.name
if not _extension_allowed(
filename,
allowed_extensions,
account.include_all_attachments,
):
continue
message_key = get_webdav_message_key(remote_file.relative_path)
if message_key in processed_keys:
result.messages_skipped += 1
continue
try:
data = download_file(webdav_config, remote_file.relative_path)
except WebdavNotFoundError as exc:
result.messages_failed += 1
logger.warning("WebDAV download missing %s: %s", remote_file.relative_path, exc)
continue
except Exception as exc:
result.messages_failed += 1
logger.error("WebDAV download failed %s: %s", remote_file.relative_path, exc)
continue
result.messages_matched += 1
source_label = f"webdav:{account.webdav_url}"
subject = filename
from_addr = source_label
date = remote_file.modified or ""
uid = remote_file.etag or str(remote_file.size)
if dry_run:
message_row = _upsert_message(
db,
account_id=account_id,
message_key=message_key,
folder=folder_label,
uid=uid,
subject=subject,
from_addr=from_addr,
date=date,
status=MessageStatus.dry_run,
)
_record_forward_attempt(db, message=message_row, success=True, dry_run=True)
processed_keys.add(message_key)
result.messages_forwarded += 1
continue
try:
check_forward_allowed(db)
doc_ids = deliver_invoice_file(
account,
filename=filename,
data=data,
source_label=source_label,
bizdocs_password=bizdocs_password,
smtp_config=smtp_config,
smtp=smtp,
bizdocs_session=bizdocs_session,
)
message_row = _upsert_message(
db,
account_id=account_id,
message_key=message_key,
folder=folder_label,
uid=uid,
subject=subject,
from_addr=from_addr,
date=date,
status=MessageStatus.forwarded,
bizdocs_doc_id=",".join(doc_ids) if doc_ids else None,
)
_record_forward_attempt(db, message=message_row, success=True, dry_run=False)
processed_keys.add(message_key)
result.messages_forwarded += 1
logger.info("WebDAV forwarded: %s", remote_file.relative_path)
except ForwardRateLimitError as exc:
message_row = _upsert_message(
db,
account_id=account_id,
message_key=message_key,
folder=folder_label,
uid=uid,
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("WebDAV forward failed for %s: %s", remote_file.relative_path, error_text)
report_error(
exc,
context_data={
"account_id": account_id,
"path": remote_file.relative_path,
},
endpoint="sync:forward_webdav",
)
message_row = _upsert_message(
db,
account_id=account_id,
message_key=message_key,
folder=folder_label,
uid=uid,
subject=subject,
from_addr=from_addr,
date=date,
status=MessageStatus.failed,
error_message=error_text,
)
_record_forward_attempt(
db,
message=message_row,
success=False,
dry_run=False,
error_message=error_text,
)
processed_keys.add(message_key)
result.messages_failed += 1
sync_run.status = SyncRunStatus.completed
except Exception as exc:
sync_run.status = SyncRunStatus.failed
sync_run.error_message = str(exc)
logger.exception("WebDAV sync failed for account %s", account_id)
report_error_with_cooldown(
f"sync_webdav:{account_id}",
300.0,
exc,
severity="error",
context_data={"account_id": account_id},
endpoint="sync:webdav_account",
)
finally:
if smtp is not None:
try:
smtp.quit()
except smtplib.SMTPException:
pass
sync_run.messages_scanned = result.messages_scanned
sync_run.messages_matched = result.messages_matched
sync_run.messages_forwarded = result.messages_forwarded
sync_run.messages_skipped = result.messages_skipped
sync_run.messages_failed = result.messages_failed
sync_run.finished_at = datetime.now(timezone.utc)
db.commit()
db.refresh(sync_run)
return sync_run
def _resolve_delivery_for_account(
account: Account,
) -> tuple[SmtpConfig | None, str | None]:
smtp_config = None
bizdocs_password = None
if account.delivery_mode == DeliveryMode.smtp:
if not account.smtp_host or not account.smtp_user or not account.smtp_password_encrypted:
raise ValueError("SMTP delivery requires smtp_host, smtp_user and smtp_password")
smtp_config = SmtpConfig(
host=account.smtp_host,
port=account.smtp_port,
user=account.smtp_user,
password=decrypt_password(account.smtp_password_encrypted),
use_tls=account.smtp_use_tls,
)
else:
if not account.bizdocs_password_encrypted:
raise ValueError("API delivery requires bizdocs_password")
bizdocs_password = decrypt_password(account.bizdocs_password_encrypted)
return smtp_config, bizdocs_password
def retry_webdav_message(db: Session, message: Message, account: Account) -> Message:
relative_path = parse_webdav_message_key(message.message_key)
if not relative_path:
raise ValueError(f"Invalid WebDAV message_key: {message.message_key}")
webdav_config = resolve_webdav_config(account)
filename = os.path.basename(relative_path)
source_label = f"webdav:{account.webdav_url}"
smtp_config, bizdocs_password = _resolve_delivery_for_account(account)
smtp = None
bizdocs_session = None
try:
try:
data = download_file(webdav_config, relative_path)
except WebdavNotFoundError as exc:
marked = _mark_missing_from_mailbox(
db,
message,
f"WebDAV file not found: {relative_path}",
)
raise MessageMissingFromMailboxError(marked, str(exc)) from exc
if account.delivery_mode == DeliveryMode.smtp and smtp_config is not None:
smtp = create_smtp_client(smtp_config)
elif bizdocs_password:
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
check_forward_allowed(db)
doc_ids = deliver_invoice_file(
account,
filename=filename,
data=data,
source_label=source_label,
bizdocs_password=bizdocs_password,
smtp_config=smtp_config,
smtp=smtp,
bizdocs_session=bizdocs_session,
)
message.status = MessageStatus.forwarded
message.error_message = None
message.bizdocs_doc_id = ",".join(doc_ids) if doc_ids else message.bizdocs_doc_id
message.updated_at = datetime.now(timezone.utc)
_record_forward_attempt(db, message=message, success=True, dry_run=False)
db.commit()
db.refresh(message)
logger.info("WebDAV retry forwarded: %s", relative_path)
return message
except MessageMissingFromMailboxError:
raise
except Exception as exc:
error_text = str(exc)
if is_missing_from_mailbox_error(error_text):
marked = _mark_missing_from_mailbox(db, message, error_text)
raise MessageMissingFromMailboxError(marked, error_text) from exc
message.status = MessageStatus.failed
message.error_message = error_text
message.updated_at = datetime.now(timezone.utc)
_record_forward_attempt(
db,
message=message,
success=False,
dry_run=False,
error_message=error_text,
)
db.commit()
db.refresh(message)
report_error(
exc,
context_data={
"message_id": message.id,
"account_id": message.account_id,
"path": relative_path,
},
endpoint="messages:retry_webdav",
)
raise
finally:
if smtp is not None:
try:
smtp.quit()
except smtplib.SMTPException:
pass
+25
View File
@@ -0,0 +1,25 @@
"""WebDAV package."""
from forwarder.webdav.client import (
WebdavConfig,
WebdavFile,
WebdavNotFoundError,
build_webdav_root,
download_file,
get_webdav_message_key,
list_files,
parse_webdav_message_key,
test_connection,
)
__all__ = [
"WebdavConfig",
"WebdavFile",
"WebdavNotFoundError",
"build_webdav_root",
"download_file",
"get_webdav_message_key",
"list_files",
"parse_webdav_message_key",
"test_connection",
]
+239
View File
@@ -0,0 +1,239 @@
"""WebDAV / Nextcloud client (PROPFIND + GET)."""
from __future__ import annotations
import logging
import os
import xml.etree.ElementTree as element_tree
from dataclasses import dataclass
from urllib.parse import quote, unquote, urljoin, urlparse
import httpx
logger = logging.getLogger(__name__)
DAV_NS = "{DAV:}"
PROPFIND_BODY = b"""<?xml version="1.0" encoding="utf-8"?>
<D:propfind xmlns:D="DAV:">
<D:prop>
<D:displayname/>
<D:getetag/>
<D:getcontentlength/>
<D:getlastmodified/>
<D:resourcetype/>
</D:prop>
</D:propfind>
"""
@dataclass(frozen=True)
class WebdavConfig:
base_url: str
folder_path: str
user: str
password: str
verify_ssl: bool = True
@dataclass(frozen=True)
class WebdavFile:
relative_path: str
name: str
href: str
etag: str
modified: str
size: int
class WebdavError(Exception):
"""WebDAV operation failed."""
class WebdavNotFoundError(WebdavError):
"""Remote file or folder not found."""
def normalize_webdav_base_url(url: str) -> str:
cleaned = url.strip().rstrip("/")
if not cleaned:
raise ValueError("webdav_url is required")
parsed = urlparse(cleaned)
if not parsed.scheme or not parsed.netloc:
raise ValueError("webdav_url must include scheme and host")
return cleaned
def normalize_webdav_folder_path(path: str | None) -> str:
if not path or not path.strip():
return "/"
cleaned = path.strip()
if not cleaned.startswith("/"):
cleaned = f"/{cleaned}"
return cleaned.rstrip("/") or "/"
def build_webdav_root(config: WebdavConfig) -> str:
base = normalize_webdav_base_url(config.base_url)
folder = normalize_webdav_folder_path(config.folder_path)
if folder == "/":
return base
return f"{base}{folder}"
def get_webdav_message_key(relative_path: str) -> str:
normalized = relative_path.strip().lstrip("/")
return f"webdav:{normalized}"
def parse_webdav_message_key(message_key: str) -> str | None:
if not message_key.startswith("webdav:"):
return None
path = message_key.removeprefix("webdav:").strip()
if not path:
return None
return path
def _client(config: WebdavConfig, *, timeout: float = 60.0) -> httpx.Client:
return httpx.Client(
timeout=timeout,
verify=config.verify_ssl,
follow_redirects=True,
auth=(config.user, config.password),
headers={"User-Agent": "Bizdocs-Forwarder/1.0"},
)
def _element_text(parent: element_tree.Element, tag: str) -> str:
node = parent.find(f"{DAV_NS}{tag}")
if node is None or node.text is None:
return ""
return node.text.strip()
def _is_collection(response_elem: element_tree.Element) -> bool:
resource_type = response_elem.find(f"{DAV_NS}propstat/{DAV_NS}prop/{DAV_NS}resourcetype")
if resource_type is None:
return False
return resource_type.find(f"{DAV_NS}collection") is not None
def _href_to_relative(root_url: str, href: str) -> str | None:
root = root_url.rstrip("/") + "/"
if href.startswith("http://") or href.startswith("https://"):
absolute = href
else:
absolute = urljoin(root, href)
if not absolute.startswith(root):
return None
relative = unquote(absolute[len(root) :].lstrip("/"))
return relative
def _parse_propfind_response(root_url: str, content: bytes) -> list[WebdavFile]:
try:
root = element_tree.fromstring(content)
except element_tree.ParseError as exc:
raise WebdavError("Invalid PROPFIND XML response") from exc
files: list[WebdavFile] = []
for response_elem in root.findall(f"{DAV_NS}response"):
href = _element_text(response_elem, "href")
if not href:
continue
if _is_collection(response_elem):
continue
relative = _href_to_relative(root_url, href)
if relative is None:
continue
if not relative or relative.endswith("/"):
continue
name = os.path.basename(relative)
if name.startswith("."):
continue
propstat = response_elem.find(f"{DAV_NS}propstat")
if propstat is None:
continue
prop = propstat.find(f"{DAV_NS}prop")
if prop is None:
continue
etag = _element_text(prop, "getetag").strip('"')
modified = _element_text(prop, "getlastmodified")
size_text = _element_text(prop, "getcontentlength")
try:
size = int(size_text) if size_text else 0
except ValueError:
size = 0
files.append(
WebdavFile(
relative_path=relative,
name=name,
href=href,
etag=etag,
modified=modified,
size=size,
)
)
return files
def list_files(config: WebdavConfig) -> list[WebdavFile]:
root_url = build_webdav_root(config)
headers = {"Depth": "infinity", "Content-Type": "application/xml; charset=utf-8"}
with _client(config) as client:
response = client.request("PROPFIND", root_url, content=PROPFIND_BODY, headers=headers)
if response.status_code == 404:
raise WebdavNotFoundError(f"WebDAV folder not found: {root_url}")
if response.status_code == 401:
raise WebdavError("WebDAV authentication failed (401)")
if response.status_code >= 400:
raise WebdavError(f"PROPFIND failed: HTTP {response.status_code} {response.text[:200]}")
return _parse_propfind_response(root_url, response.content)
def download_file(config: WebdavConfig, relative_path: str) -> bytes:
root_url = build_webdav_root(config)
path = relative_path.lstrip("/")
file_url = f"{root_url}/{quote(path, safe='/')}"
with _client(config) as client:
response = client.get(file_url)
if response.status_code == 404:
raise WebdavNotFoundError(f"WebDAV file not found: {relative_path}")
if response.status_code == 401:
raise WebdavError("WebDAV authentication failed (401)")
if response.status_code >= 400:
raise WebdavError(
f"GET failed for {relative_path}: HTTP {response.status_code} {response.text[:200]}"
)
return response.content
def test_connection(config: WebdavConfig) -> tuple[bool, str]:
try:
root_url = build_webdav_root(config)
headers = {"Depth": "0", "Content-Type": "application/xml; charset=utf-8"}
with _client(config, timeout=15.0) as client:
response = client.request("PROPFIND", root_url, content=PROPFIND_BODY, headers=headers)
if response.status_code == 401:
return False, "WebDAV authentication failed (401)"
if response.status_code == 404:
return False, f"WebDAV folder not found: {root_url}"
if response.status_code >= 400:
return False, f"WebDAV PROPFIND failed: HTTP {response.status_code}"
files = list_files(config)
return True, f"WebDAV OK — {len(files)} ficheiro(s) em {root_url}"
except WebdavError as exc:
return False, str(exc)
except httpx.HTTPError as exc:
return False, str(exc)
+52
View File
@@ -0,0 +1,52 @@
"""BizDocs API client unit tests."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials
def test_identity_router_parses_mobile_api_url():
client = BizdocsClient()
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.content = b'{"mobileApiUrl":"https://api.example.com"}'
mock_response.json.return_value = {"mobileApiUrl": "https://api.example.com"}
with patch.object(client, "_client") as mock_client_factory:
mock_http = MagicMock()
mock_http.__enter__.return_value = mock_http
mock_http.get.return_value = mock_response
mock_client_factory.return_value = mock_http
url = client.resolve_mobile_api_url("[email protected]")
assert url == "https://api.example.com"
def test_login_extracts_access_token():
client = BizdocsClient()
route_response = MagicMock(status_code=200, content=b"{}", json=lambda: {"mobileApiUrl": "https://api.example.com"})
login_response = MagicMock(
status_code=200,
content=b"{}",
json=lambda: {"accessToken": "abc123", "refreshToken": "ref"},
)
with patch.object(client, "_client") as mock_client_factory:
mock_http = MagicMock()
mock_http.__enter__.return_value = mock_http
mock_http.get.return_value = route_response
mock_http.post.return_value = login_response
mock_client_factory.return_value = mock_http
session = client.login(
BizdocsCredentials(
email="[email protected]",
password="secret",
company_id="co-1",
api_base_url="https://api.example.com",
)
)
assert session.access_token == "abc123"
assert session.mobile_api_url == "https://api.example.com"
+144
View File
@@ -0,0 +1,144 @@
"""Invoice attachment validation tests."""
from __future__ import annotations
import struct
from email.message import EmailMessage
from forwarder.email.invoice_validation import is_plausible_invoice_file
from forwarder.email.parsing import (
DEFAULT_ALLOWED_EXTENSIONS,
collect_matching_attachments,
has_matching_attachment,
)
def _fake_png(width: int, height: int, *, padding: int = 9000) -> bytes:
signature = b"\x89PNG\r\n\x1a\n"
ihdr_data = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
ihdr = struct.pack(">I", 13) + b"IHDR" + ihdr_data + struct.pack(">I", 0)
iend = struct.pack(">I", 0) + b"IEND" + struct.pack(">I", 0xAE426082)
body = signature + ihdr + iend
if len(body) >= padding:
return body
return body + b"\x00" * (padding - len(body))
def _fake_jpeg(width: int, height: int, *, padding: int = 9000) -> bytes:
sof_payload = struct.pack(">BHH", 8, height, width) + b"\x03\x01\x11\x00"
sof = b"\xff\xc0" + struct.pack(">H", len(sof_payload) + 2) + sof_payload
body = b"\xff\xd8" + sof + b"\xff\xd9"
if len(body) >= padding:
return body
return body + b"\x00" * (padding - len(body))
def _msg_with_part(
*,
data: bytes,
filename: str,
content_type: str,
disposition: str = "attachment",
) -> EmailMessage:
msg = EmailMessage()
msg["Subject"] = "Test"
msg.set_content("body")
maintype, subtype = content_type.split("/", 1)
msg.add_attachment(
data,
maintype=maintype,
subtype=subtype,
filename=filename,
disposition=disposition,
)
return msg
def test_rejects_inline_embedded_image():
msg = _msg_with_part(
data=_fake_png(400, 400),
filename="logo.png",
content_type="image/png",
disposition="inline",
)
assert not has_matching_attachment(msg, allowed_extensions=DEFAULT_ALLOWED_EXTENSIONS)
assert collect_matching_attachments(msg) == []
def test_rejects_tiny_tracking_pixel():
msg = _msg_with_part(
data=b"\x89PNG" + b"\x00" * 100,
filename="pixel.png",
content_type="image/png",
disposition="attachment",
)
assert not has_matching_attachment(msg)
def test_rejects_small_icon_by_filename():
msg = _msg_with_part(
data=_fake_png(400, 400, padding=5000),
filename="company-logo.png",
content_type="image/png",
)
assert not is_plausible_invoice_file(
_fake_png(400, 400, padding=5000),
filename="company-logo.png",
content_type="image/png",
)
def test_accepts_large_invoice_scan_jpeg():
data = _fake_jpeg(800, 1200)
msg = _msg_with_part(
data=data,
filename="fatura_123.jpg",
content_type="image/jpeg",
)
assert has_matching_attachment(msg)
attachments = collect_matching_attachments(msg)
assert len(attachments) == 1
assert attachments[0].filename == "fatura_123.jpg"
def test_accepts_valid_pdf_attachment():
pdf = b"%PDF-1.4\n" + (b"% invoice body\n" * 80)
msg = _msg_with_part(
data=pdf,
filename="FT2024.pdf",
content_type="application/pdf",
)
assert has_matching_attachment(msg)
assert len(collect_matching_attachments(msg)) == 1
def test_rejects_truncated_pdf():
msg = _msg_with_part(
data=b"%PDF",
filename="x.pdf",
content_type="application/pdf",
)
assert not has_matching_attachment(msg)
def test_rejects_low_resolution_image():
data = _fake_png(80, 80, padding=9000)
msg = _msg_with_part(
data=data,
filename="scan.png",
content_type="image/png",
)
assert not has_matching_attachment(msg)
def test_accepts_valid_xml():
xml = (
b'<?xml version="1.0" encoding="UTF-8"?>'
b"<Invoice><Id>1</Id><Note>test document</Note></Invoice>"
)
msg = _msg_with_part(
data=xml,
filename="doc.xml",
content_type="application/xml",
)
assert has_matching_attachment(msg)
+14 -3
View File
@@ -15,7 +15,7 @@ def test_forward_sends_clean_message_with_pdf_only():
original["X-SG-EID"] = "spam-marker" original["X-SG-EID"] = "spam-marker"
original.set_content("marketing body") original.set_content("marketing body")
original.add_attachment( original.add_attachment(
b"%PDF-1.4", b"%PDF-1.4\n" + (b"x" * 1200),
maintype="application", maintype="application",
subtype="pdf", subtype="pdf",
filename="fatura.pdf", filename="fatura.pdf",
@@ -53,8 +53,19 @@ def test_forward_includes_multiple_invoice_types():
original = EmailMessage() original = EmailMessage()
original["Subject"] = "Docs" original["Subject"] = "Docs"
original.set_content("x") original.set_content("x")
original.add_attachment(b"%PDF", maintype="application", subtype="pdf", filename="a.pdf") original.add_attachment(
original.add_attachment(b"<x/>", maintype="text", subtype="xml", filename="b.xml") b"%PDF-1.4\n" + (b"x" * 1200),
maintype="application",
subtype="pdf",
filename="a.pdf",
)
original.add_attachment(
b'<?xml version="1.0" encoding="UTF-8"?>'
b"<Invoice><Id>1</Id><Line>item description</Line><Total>10.00</Total></Invoice>",
maintype="text",
subtype="xml",
filename="b.xml",
)
outbound = build_forward_message( outbound = build_forward_message(
original, original,
+82
View File
@@ -0,0 +1,82 @@
"""Tests for WebDAV client helpers and PROPFIND parsing."""
from forwarder.webdav.client import (
WebdavConfig,
_parse_propfind_response,
build_webdav_root,
get_webdav_message_key,
normalize_webdav_folder_path,
parse_webdav_message_key,
)
PROPFIND_SAMPLE = b"""<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response>
<D:href>/remote.php/dav/files/user/Faturas/</D:href>
<D:propstat>
<D:prop>
<D:resourcetype><D:collection/></D:resourcetype>
</D:prop>
</D:propstat>
</D:response>
<D:response>
<D:href>/remote.php/dav/files/user/Faturas/invoice.pdf</D:href>
<D:propstat>
<D:prop>
<D:getetag>"abc123"</D:getetag>
<D:getlastmodified>Mon, 01 Jan 2024 10:00:00 GMT</D:getlastmodified>
<D:getcontentlength>12345</D:getcontentlength>
<D:resourcetype/>
</D:prop>
</D:propstat>
</D:response>
<D:response>
<D:href>/remote.php/dav/files/user/Faturas/sub/photo.jpg</D:href>
<D:propstat>
<D:prop>
<D:getetag>"def456"</D:getetag>
<D:getcontentlength>999</D:getcontentlength>
<D:resourcetype/>
</D:prop>
</D:propstat>
</D:response>
</D:multistatus>
"""
def test_normalize_webdav_folder_path():
assert normalize_webdav_folder_path(None) == "/"
assert normalize_webdav_folder_path("") == "/"
assert normalize_webdav_folder_path("Faturas") == "/Faturas"
assert normalize_webdav_folder_path("/Faturas/") == "/Faturas"
def test_build_webdav_root():
config = WebdavConfig(
base_url="https://cloud.example.com/remote.php/dav/files/user",
folder_path="/Faturas",
user="user",
password="secret",
)
assert (
build_webdav_root(config)
== "https://cloud.example.com/remote.php/dav/files/user/Faturas"
)
def test_webdav_message_key_roundtrip():
key = get_webdav_message_key("Faturas/invoice.pdf")
assert key == "webdav:Faturas/invoice.pdf"
assert parse_webdav_message_key(key) == "Faturas/invoice.pdf"
assert parse_webdav_message_key("imap:123") is None
def test_parse_propfind_response():
root = "https://cloud.example.com/remote.php/dav/files/user/Faturas/"
files = _parse_propfind_response(root, PROPFIND_SAMPLE)
names = sorted(item.name for item in files)
assert names == ["invoice.pdf", "photo.jpg"]
invoice = next(item for item in files if item.name == "invoice.pdf")
assert invoice.relative_path == "invoice.pdf"
assert invoice.etag == "abc123"
assert invoice.size == 12345
+71
View File
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Probe BizDocs mobile API (GetRoute, login, companies).
Usage:
PYTHONPATH=src python tools/probe_bizdocs_api.py --email [email protected] --password 'secret'
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials
def main() -> int:
parser = argparse.ArgumentParser(description="Probe BizDocs API login and routing")
parser.add_argument("--email", required=True)
parser.add_argument("--password", required=True)
parser.add_argument("--company-id", default="")
parser.add_argument("--api-base", default="", help="Skip identity router when set")
args = parser.parse_args()
client = BizdocsClient()
credentials = BizdocsCredentials(
email=args.email,
password=args.password,
company_id=args.company_id,
api_base_url=args.api_base or None,
)
print("=== Resolve mobile API URL ===")
try:
mobile_url = client.resolve_mobile_api_url(
credentials.email,
credentials.api_base_url,
)
print("mobileApiUrl:", mobile_url)
except Exception as exc:
print("FAILED:", exc)
if not args.api_base:
print("Tip: pass --api-base if you know the tenant API URL")
return 1
print("\n=== Login ===")
try:
session = client.login(credentials)
print("access_token:", session.access_token[:24] + "…")
if session.refresh_token:
print("refresh_token: present")
except Exception as exc:
print("FAILED:", exc)
return 1
print("\n=== Companies ===")
try:
companies = client.list_companies(session)
print(json.dumps(companies, indent=2, ensure_ascii=False))
except Exception as exc:
print("FAILED:", exc)
return 0
if __name__ == "__main__":
raise SystemExit(main())