Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0998a016fa | ||
|
|
e160520655 | ||
|
|
4998a0f009 | ||
|
|
a782a97a1d | ||
|
|
c0c3109174 | ||
|
|
4fd7e51a7c | ||
|
|
ac932323c8 | ||
|
|
5bc5e0d889 | ||
|
|
bc39e00192 | ||
|
|
c2524c31a5 | ||
|
|
91b1a726e8 |
No files matched your search
@@ -0,0 +1,30 @@
|
||||
name: ci
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: PHP 8.5 syntax check (webhook-receiver.php)
|
||||
run: |
|
||||
php -v
|
||||
php -l deploy/webhook-receiver.php
|
||||
|
||||
- name: Setup Node.js 24.22.1
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24.22.1"
|
||||
|
||||
- name: Build admin-ui
|
||||
working-directory: admin-ui
|
||||
run: |
|
||||
npm ci
|
||||
npm run build
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM node:20-alpine AS build
|
||||
FROM node:24-alpine AS build
|
||||
ARG GIT_SHA=unknown
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
|
||||
@@ -23,5 +23,8 @@
|
||||
"tailwindcss": "^3.4.14",
|
||||
"typescript": "^5.6.3",
|
||||
"vite": "^5.4.10"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24.22.1"
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,8 @@ export interface Account {
|
||||
bizdocs_api_base_url: string | null
|
||||
sync_interval_minutes: number
|
||||
active: boolean
|
||||
imap_folder_selection_mode: 'default' | 'custom'
|
||||
imap_selected_folders: string[] | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -139,6 +141,19 @@ export interface SyncRunResult {
|
||||
finished_at: string | null
|
||||
}
|
||||
|
||||
export interface ImapFolderInfo {
|
||||
name: string
|
||||
skipped_by_default: boolean
|
||||
selected: boolean
|
||||
}
|
||||
|
||||
export interface ImapFoldersResponse {
|
||||
selection_mode: string
|
||||
folders: ImapFolderInfo[]
|
||||
scanned_count: number
|
||||
total_count: number
|
||||
}
|
||||
|
||||
export interface TestPayload {
|
||||
imap_host: string
|
||||
imap_port: number
|
||||
@@ -171,6 +186,29 @@ export const api = {
|
||||
method: 'POST',
|
||||
})
|
||||
},
|
||||
imapFolders: (
|
||||
id: number,
|
||||
opts?: { selection_mode?: string },
|
||||
) => {
|
||||
const q = new URLSearchParams()
|
||||
if (opts?.selection_mode) q.set('selection_mode', opts.selection_mode)
|
||||
const qs = q.toString()
|
||||
return request<ImapFoldersResponse>(
|
||||
`/accounts/${id}/imap/folders${qs ? '?' + qs : ''}`,
|
||||
)
|
||||
},
|
||||
imapFoldersPresave: (data: {
|
||||
imap_host: string
|
||||
imap_port?: number
|
||||
imap_user: string
|
||||
imap_password: string
|
||||
selection_mode?: string
|
||||
imap_selected_folders?: string[]
|
||||
}) =>
|
||||
request<ImapFoldersResponse>('/accounts/imap/folders', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
}),
|
||||
},
|
||||
messages: {
|
||||
list: (params?: {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react'
|
||||
import { api, Account, AccountCreate, DEFAULT_DESTINATION_EMAIL } from '../lib/api'
|
||||
import { api, Account, AccountCreate, DEFAULT_DESTINATION_EMAIL, ImapFolderInfo } from '../lib/api'
|
||||
import { useAsync } from '../hooks/useApi'
|
||||
import Spinner from '../components/Spinner'
|
||||
import StatusBadge from '../components/StatusBadge'
|
||||
@@ -41,25 +41,70 @@ const EMPTY_FORM: AccountCreate = {
|
||||
destination_email: DEFAULT_DESTINATION_EMAIL,
|
||||
sync_interval_minutes: 15,
|
||||
active: false,
|
||||
imap_folder_selection_mode: 'default',
|
||||
imap_selected_folders: null,
|
||||
}
|
||||
|
||||
function AccountModal({
|
||||
initial,
|
||||
accountId,
|
||||
onSave,
|
||||
onClose,
|
||||
}: {
|
||||
initial: Partial<AccountCreate> | null
|
||||
accountId: number | null
|
||||
onSave: (data: AccountCreate) => Promise<void>
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [form, setForm] = useState<AccountCreate>({ ...EMPTY_FORM, ...initial })
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [folderList, setFolderList] = useState<ImapFolderInfo[]>([])
|
||||
const [foldersLoading, setFoldersLoading] = useState(false)
|
||||
const [foldersError, setFoldersError] = 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 | string[] | null) =>
|
||||
setForm((f) => ({ ...f, [k]: v }))
|
||||
|
||||
const selectedFolderSet = () => new Set(form.imap_selected_folders ?? [])
|
||||
|
||||
const toggleFolder = (name: string, checked: boolean) => {
|
||||
const current = new Set(form.imap_selected_folders ?? [])
|
||||
if (checked) current.add(name)
|
||||
else current.delete(name)
|
||||
set('imap_selected_folders', Array.from(current))
|
||||
}
|
||||
|
||||
const loadImapFolders = async () => {
|
||||
setFoldersLoading(true)
|
||||
setFoldersError(null)
|
||||
try {
|
||||
const mode = form.imap_folder_selection_mode || 'default'
|
||||
const response = accountId
|
||||
? await api.accounts.imapFolders(accountId, { selection_mode: mode })
|
||||
: await api.accounts.imapFoldersPresave({
|
||||
imap_host: form.imap_host || '',
|
||||
imap_port: form.imap_port,
|
||||
imap_user: (form.imap_user ?? '').trim() || form.email.trim(),
|
||||
imap_password: form.imap_password || '',
|
||||
selection_mode: mode,
|
||||
imap_selected_folders: form.imap_selected_folders ?? undefined,
|
||||
})
|
||||
setFolderList(response.folders)
|
||||
if (mode === 'custom' && !form.imap_selected_folders?.length) {
|
||||
set(
|
||||
'imap_selected_folders',
|
||||
response.folders.filter((f) => f.selected).map((f) => f.name),
|
||||
)
|
||||
}
|
||||
} catch (e) {
|
||||
setFoldersError(e instanceof Error ? e.message : String(e))
|
||||
} finally {
|
||||
setFoldersLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setSaving(true)
|
||||
@@ -212,6 +257,73 @@ function AccountModal({
|
||||
{field('Password', 'imap_password', 'password')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 space-y-3 border-t border-gray-100 pt-3">
|
||||
<p className="text-xs font-semibold text-gray-600">Pastas IMAP a sincronizar</p>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="imap_folder_mode"
|
||||
checked={form.imap_folder_selection_mode !== 'custom'}
|
||||
onChange={() => {
|
||||
set('imap_folder_selection_mode', 'default')
|
||||
set('imap_selected_folders', null)
|
||||
}}
|
||||
/>
|
||||
<span className="text-sm">
|
||||
Todas as pastas (excepto lixo, spam, enviados, rascunhos)
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="radio"
|
||||
name="imap_folder_mode"
|
||||
checked={form.imap_folder_selection_mode === 'custom'}
|
||||
onChange={() => set('imap_folder_selection_mode', 'custom')}
|
||||
/>
|
||||
<span className="text-sm">Seleccionar pastas manualmente</span>
|
||||
</label>
|
||||
{form.imap_folder_selection_mode === 'custom' && (
|
||||
<div className="space-y-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={loadImapFolders}
|
||||
disabled={foldersLoading}
|
||||
className="text-sm px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
|
||||
>
|
||||
{foldersLoading ? 'A carregar…' : 'Carregar pastas do servidor'}
|
||||
</button>
|
||||
{foldersError && (
|
||||
<p className="text-xs text-red-600">{foldersError}</p>
|
||||
)}
|
||||
{folderList.length > 0 && (
|
||||
<div className="max-h-48 overflow-y-auto border border-gray-200 rounded-md p-2 space-y-1">
|
||||
{folderList.map((folder) => (
|
||||
<label
|
||||
key={folder.name}
|
||||
className="flex items-start gap-2 text-sm cursor-pointer"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedFolderSet().has(folder.name)}
|
||||
onChange={(e) => toggleFolder(folder.name, e.target.checked)}
|
||||
className="mt-0.5 rounded"
|
||||
/>
|
||||
<span>
|
||||
{folder.name}
|
||||
{folder.skipped_by_default && (
|
||||
<span className="ml-1 text-xs text-gray-400">(ignorada por defeito)</span>
|
||||
)}
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-gray-500">
|
||||
Só as pastas marcadas serão percorridas no sync IMAP.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</fieldset>
|
||||
)}
|
||||
|
||||
@@ -577,6 +689,7 @@ export default function Accounts() {
|
||||
|
||||
{modal.open && (
|
||||
<AccountModal
|
||||
accountId={modal.account?.id ?? null}
|
||||
initial={
|
||||
modal.account
|
||||
? {
|
||||
@@ -586,6 +699,8 @@ export default function Accounts() {
|
||||
imap_host: modal.account.imap_host || '',
|
||||
imap_port: modal.account.imap_port,
|
||||
imap_user: modal.account.imap_user || '',
|
||||
imap_folder_selection_mode: modal.account.imap_folder_selection_mode || 'default',
|
||||
imap_selected_folders: modal.account.imap_selected_folders,
|
||||
webdav_url: modal.account.webdav_url || '',
|
||||
webdav_path: modal.account.webdav_path || '',
|
||||
webdav_user: modal.account.webdav_user || '',
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM php:8.3-cli-alpine
|
||||
FROM php:8.5-cli-alpine
|
||||
|
||||
RUN apk add --no-cache bash git curl docker-cli docker-cli-compose
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Add IMAP folder selection fields on accounts
|
||||
|
||||
Revision ID: 007_imap_folder_selection
|
||||
Revises: 006_shop_accounts
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "007_imap_folder_selection"
|
||||
down_revision: Union[str, None] = "006_shop_accounts"
|
||||
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(
|
||||
"imap_folder_selection_mode",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="default",
|
||||
),
|
||||
)
|
||||
op.add_column(
|
||||
"accounts",
|
||||
sa.Column("imap_selected_folders", sa.JSON(), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("accounts", "imap_selected_folders")
|
||||
op.drop_column("accounts", "imap_folder_selection_mode")
|
||||
@@ -9,6 +9,7 @@ from forwarder.api.schemas import (
|
||||
AccountResponse,
|
||||
AccountUpdate,
|
||||
ConnectionTestResponse,
|
||||
ImapFoldersResponse,
|
||||
InlineConnectionConfig,
|
||||
SyncRunResponse,
|
||||
)
|
||||
@@ -90,6 +91,64 @@ def test_webdav_presave(
|
||||
return ConnectionTestResponse(success=success, message=message)
|
||||
|
||||
|
||||
@router.post("/imap/folders", response_model=ImapFoldersResponse)
|
||||
def list_imap_folders_presave(
|
||||
inline: InlineConnectionConfig,
|
||||
db: DbSession,
|
||||
_user: CurrentUser,
|
||||
selection_mode: str = Query(default="default"),
|
||||
) -> ImapFoldersResponse:
|
||||
"""List IMAP mailboxes using inline credentials (before account is saved)."""
|
||||
data = inline.model_dump(exclude_unset=True)
|
||||
required = ("imap_host", "imap_user", "imap_password")
|
||||
for field in required:
|
||||
if not data.get(field):
|
||||
raise HTTPException(status_code=400, detail=f"{field} is required")
|
||||
try:
|
||||
result = account_service.list_imap_folders(
|
||||
db,
|
||||
None,
|
||||
data,
|
||||
selection_mode=selection_mode,
|
||||
selected_folders=inline.imap_selected_folders,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
return ImapFoldersResponse(**result)
|
||||
|
||||
|
||||
@router.get("/{account_id}/imap/folders", response_model=ImapFoldersResponse)
|
||||
def list_imap_folders(
|
||||
account_id: int,
|
||||
db: DbSession,
|
||||
_user: CurrentUser,
|
||||
selection_mode: str | None = Query(default=None),
|
||||
) -> ImapFoldersResponse:
|
||||
"""List IMAP mailboxes for a saved account."""
|
||||
try:
|
||||
account = account_service.get_account(db, account_id)
|
||||
except account_service.AccountNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
if account.source_type != SourceType.imap:
|
||||
raise HTTPException(status_code=400, detail="Account is not IMAP")
|
||||
mode = selection_mode or account.imap_folder_selection_mode or "default"
|
||||
try:
|
||||
result = account_service.list_imap_folders(
|
||||
db,
|
||||
account_id,
|
||||
None,
|
||||
selection_mode=mode,
|
||||
selected_folders=account.imap_selected_folders,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
||||
return ImapFoldersResponse(**result)
|
||||
|
||||
|
||||
@router.get("", response_model=list[AccountResponse])
|
||||
def list_accounts(db: DbSession, _user: CurrentUser) -> list[AccountResponse]:
|
||||
return [_to_response(a) for a in account_service.list_accounts(db)]
|
||||
|
||||
@@ -32,6 +32,8 @@ class AccountBase(BaseModel):
|
||||
bizdocs_api_base_url: str | None = None
|
||||
include_all_attachments: bool = False
|
||||
allowed_extensions: list[str] = Field(default_factory=lambda: list(DEFAULT_ALLOWED_EXTENSIONS))
|
||||
imap_folder_selection_mode: str = "default"
|
||||
imap_selected_folders: list[str] | None = None
|
||||
|
||||
|
||||
class AccountCreate(AccountBase):
|
||||
@@ -131,6 +133,8 @@ class AccountUpdate(BaseModel):
|
||||
bizdocs_api_base_url: str | None = None
|
||||
include_all_attachments: bool | None = None
|
||||
allowed_extensions: list[str] | None = None
|
||||
imap_folder_selection_mode: str | None = None
|
||||
imap_selected_folders: list[str] | None = None
|
||||
active: bool | None = None
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -193,6 +197,8 @@ class InlineConnectionConfig(BaseModel):
|
||||
bizdocs_password: str | None = None
|
||||
bizdocs_company_id: str | None = None
|
||||
bizdocs_api_base_url: str | None = None
|
||||
imap_folder_selection_mode: str | None = None
|
||||
imap_selected_folders: list[str] | None = None
|
||||
|
||||
|
||||
class ConnectionTestResponse(BaseModel):
|
||||
@@ -200,6 +206,19 @@ class ConnectionTestResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
class ImapFolderInfo(BaseModel):
|
||||
name: str
|
||||
skipped_by_default: bool
|
||||
selected: bool
|
||||
|
||||
|
||||
class ImapFoldersResponse(BaseModel):
|
||||
selection_mode: str
|
||||
folders: list[ImapFolderInfo]
|
||||
scanned_count: int
|
||||
total_count: int
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
id: int
|
||||
account_id: int
|
||||
|
||||
@@ -87,6 +87,10 @@ class Account(Base):
|
||||
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)
|
||||
imap_folder_selection_mode: Mapped[str] = mapped_column(
|
||||
String(16), default="default", nullable=False
|
||||
)
|
||||
imap_selected_folders: Mapped[list[Any] | None] = mapped_column(JSON, nullable=True)
|
||||
|
||||
webdav_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
webdav_path: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
|
||||
@@ -46,6 +46,25 @@ def should_skip_folder(folder: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def folder_should_be_scanned(
|
||||
folder: str,
|
||||
*,
|
||||
selection_mode: str = "default",
|
||||
selected_folders: list[str] | None = None,
|
||||
) -> bool:
|
||||
"""Return True when sync should traverse this mailbox."""
|
||||
if selection_mode == "custom":
|
||||
if not selected_folders:
|
||||
return False
|
||||
return folder in selected_folders
|
||||
return not should_skip_folder(folder)
|
||||
|
||||
|
||||
def default_scanned_folders(all_folders: list[str]) -> list[str]:
|
||||
"""Folders scanned under the default selection mode."""
|
||||
return [folder for folder in all_folders if not should_skip_folder(folder)]
|
||||
|
||||
|
||||
def list_mailboxes(imap: imaplib.IMAP4_SSL) -> list[str]:
|
||||
status, boxes = imap.list()
|
||||
if status != "OK" or not boxes:
|
||||
|
||||
@@ -12,6 +12,9 @@ MIN_PDF_BYTES = 1024
|
||||
MIN_XML_BYTES = 80
|
||||
MIN_ZIP_BYTES = 22
|
||||
|
||||
_PDF_MAGIC = b"%PDF-"
|
||||
_PDF_HEADER_SCAN_BYTES = 1024
|
||||
|
||||
MIN_IMAGE_WIDTH = 200
|
||||
MIN_IMAGE_HEIGHT = 200
|
||||
|
||||
@@ -124,12 +127,18 @@ def _image_meets_min_dimensions(data: bytes, ext: str) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _find_pdf_magic(data: bytes) -> int | None:
|
||||
"""Return byte offset of %PDF- within the header window, or None."""
|
||||
if not data:
|
||||
return None
|
||||
index = data[:_PDF_HEADER_SCAN_BYTES].find(_PDF_MAGIC)
|
||||
return index if index >= 0 else None
|
||||
|
||||
|
||||
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
|
||||
return _find_pdf_magic(data) is not None
|
||||
|
||||
|
||||
def _is_valid_xml(data: bytes) -> bool:
|
||||
@@ -199,7 +208,12 @@ def is_plausible_invoice_file(
|
||||
return False
|
||||
|
||||
if ext == ".pdf" or content_type == "application/pdf":
|
||||
return _is_valid_pdf(data)
|
||||
if _is_valid_pdf(data):
|
||||
return True
|
||||
# Some mobile scanners store JPEG/PNG bytes under a .pdf filename.
|
||||
if _is_valid_image(data, ".jpeg") or _is_valid_image(data, ".png"):
|
||||
return True
|
||||
return False
|
||||
|
||||
if ext == ".xml" or content_type in ("application/xml", "text/xml"):
|
||||
return _is_valid_xml(data)
|
||||
@@ -208,3 +222,41 @@ def is_plausible_invoice_file(
|
||||
return _is_valid_zip(data)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def invoice_validation_failure_reason(
|
||||
data: bytes,
|
||||
*,
|
||||
filename: str,
|
||||
content_type: str,
|
||||
) -> str | None:
|
||||
"""Human-readable reason when is_plausible_invoice_file would return False."""
|
||||
if is_plausible_invoice_file(data, filename=filename, content_type=content_type):
|
||||
return None
|
||||
|
||||
ext = _extension_from_filename(filename)
|
||||
content_type = (content_type or "").lower()
|
||||
|
||||
if not data:
|
||||
return "empty file"
|
||||
|
||||
if ext == ".pdf" or content_type == "application/pdf":
|
||||
if len(data) < MIN_PDF_BYTES:
|
||||
return f"too small ({len(data)} bytes, min {MIN_PDF_BYTES})"
|
||||
if _find_pdf_magic(data) is None:
|
||||
head = data[:16].hex()
|
||||
return f"PDF header %PDF- not found in first {_PDF_HEADER_SCAN_BYTES} bytes (head={head})"
|
||||
return "not a valid PDF or invoice scan image"
|
||||
|
||||
if ext in (".png", ".jpg", ".jpeg") or content_type.startswith("image/"):
|
||||
if len(data) < MIN_IMAGE_BYTES:
|
||||
return f"image too small ({len(data)} bytes, min {MIN_IMAGE_BYTES})"
|
||||
return "image below minimum dimensions or invalid format"
|
||||
|
||||
if ext == ".xml" or content_type in ("application/xml", "text/xml"):
|
||||
return "invalid or too small XML"
|
||||
|
||||
if ext == ".zip" or content_type in ("application/zip", "application/x-zip-compressed"):
|
||||
return "invalid or too small ZIP"
|
||||
|
||||
return f"unsupported type ({ext or content_type or 'unknown'})"
|
||||
@@ -13,7 +13,15 @@ from forwarder.db.models import (
|
||||
DeliveryMode,
|
||||
SourceType,
|
||||
)
|
||||
from forwarder.email.imap_client import ImapConfig, test_imap_connection
|
||||
from forwarder.email.imap_client import (
|
||||
ImapConfig,
|
||||
connect_imap,
|
||||
default_scanned_folders,
|
||||
folder_should_be_scanned,
|
||||
list_mailboxes,
|
||||
should_skip_folder,
|
||||
test_imap_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
|
||||
@@ -70,6 +78,8 @@ def account_to_dict(account: Account, *, include_secrets: bool = False) -> dict:
|
||||
"bizdocs_api_base_url": account.bizdocs_api_base_url,
|
||||
"include_all_attachments": account.include_all_attachments,
|
||||
"allowed_extensions": account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS),
|
||||
"imap_folder_selection_mode": account.imap_folder_selection_mode or "default",
|
||||
"imap_selected_folders": account.imap_selected_folders,
|
||||
"created_at": account.created_at,
|
||||
"updated_at": account.updated_at,
|
||||
}
|
||||
@@ -160,6 +170,8 @@ def create_account(db: Session, data: dict) -> Account:
|
||||
bizdocs_api_base_url=data.get("bizdocs_api_base_url"),
|
||||
include_all_attachments=data.get("include_all_attachments", False),
|
||||
allowed_extensions=_normalize_extensions(data.get("allowed_extensions")),
|
||||
imap_folder_selection_mode=data.get("imap_folder_selection_mode", "default"),
|
||||
imap_selected_folders=data.get("imap_selected_folders"),
|
||||
)
|
||||
db.add(account)
|
||||
db.commit()
|
||||
@@ -188,6 +200,8 @@ def update_account(db: Session, account_id: int, data: dict) -> Account:
|
||||
"smtp_use_tls",
|
||||
"destination_email",
|
||||
"include_all_attachments",
|
||||
"imap_folder_selection_mode",
|
||||
"imap_selected_folders",
|
||||
"bizdocs_email",
|
||||
"bizdocs_company_id",
|
||||
"bizdocs_api_base_url",
|
||||
@@ -204,6 +218,9 @@ def update_account(db: Session, account_id: int, data: dict) -> Account:
|
||||
if "allowed_extensions" in data and data["allowed_extensions"] is not None:
|
||||
account.allowed_extensions = _normalize_extensions(data["allowed_extensions"])
|
||||
|
||||
if "imap_selected_folders" in data:
|
||||
account.imap_selected_folders = data["imap_selected_folders"]
|
||||
|
||||
imap_password = data.get("imap_password")
|
||||
if imap_password:
|
||||
account.imap_password_encrypted = encrypt_password(imap_password)
|
||||
@@ -443,3 +460,60 @@ def run_webdav_test(db: Session, account_id: int | None, inline: dict | None) ->
|
||||
message=message,
|
||||
)
|
||||
return success, message
|
||||
|
||||
|
||||
def list_imap_folders(
|
||||
db: Session,
|
||||
account_id: int | None,
|
||||
inline: dict | None,
|
||||
*,
|
||||
selection_mode: str = "default",
|
||||
selected_folders: list[str] | None = None,
|
||||
) -> dict:
|
||||
"""Connect to IMAP and return mailbox list with scan metadata."""
|
||||
config = resolve_imap_config(db, account_id, inline)
|
||||
imap = None
|
||||
try:
|
||||
imap = connect_imap(config)
|
||||
all_folders = list_mailboxes(imap)
|
||||
finally:
|
||||
if imap is not None:
|
||||
try:
|
||||
imap.logout()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if account_id is not None and selected_folders is None:
|
||||
account = get_account(db, account_id)
|
||||
selection_mode = account.imap_folder_selection_mode or "default"
|
||||
selected_folders = account.imap_selected_folders
|
||||
|
||||
effective_selected = selected_folders
|
||||
if selection_mode == "custom" and not effective_selected:
|
||||
effective_selected = default_scanned_folders(all_folders)
|
||||
|
||||
folders_out: list[dict] = []
|
||||
scanned_count = 0
|
||||
for folder in all_folders:
|
||||
skipped_by_default = should_skip_folder(folder)
|
||||
selected = folder_should_be_scanned(
|
||||
folder,
|
||||
selection_mode=selection_mode,
|
||||
selected_folders=effective_selected,
|
||||
)
|
||||
if selected:
|
||||
scanned_count += 1
|
||||
folders_out.append(
|
||||
{
|
||||
"name": folder,
|
||||
"skipped_by_default": skipped_by_default,
|
||||
"selected": selected,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"selection_mode": selection_mode,
|
||||
"folders": folders_out,
|
||||
"scanned_count": scanned_count,
|
||||
"total_count": len(all_folders),
|
||||
}
|
||||
@@ -12,7 +12,10 @@ 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.invoice_validation import (
|
||||
invoice_validation_failure_reason,
|
||||
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
|
||||
|
||||
@@ -104,7 +107,15 @@ def deliver_invoice_file(
|
||||
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")
|
||||
detail = invoice_validation_failure_reason(
|
||||
data,
|
||||
filename=filename,
|
||||
content_type=content_type,
|
||||
)
|
||||
message = f"File {filename} failed invoice validation"
|
||||
if detail:
|
||||
message = f"{message}: {detail}"
|
||||
raise ValueError(message)
|
||||
|
||||
if account.delivery_mode == DeliveryMode.api:
|
||||
if bizdocs_session is None:
|
||||
|
||||
@@ -22,9 +22,9 @@ from forwarder.db.models import (
|
||||
from forwarder.email.imap_client import (
|
||||
connect_imap,
|
||||
fetch_message,
|
||||
folder_should_be_scanned,
|
||||
list_mailboxes,
|
||||
select_folder_readonly,
|
||||
should_skip_folder,
|
||||
ImapConfig,
|
||||
)
|
||||
from forwarder.email.parsing import (
|
||||
@@ -216,12 +216,18 @@ def sync_account(
|
||||
|
||||
folders = list_mailboxes(imap)
|
||||
logger.info("Account %s: %d mailbox(es)", account_id, len(folders))
|
||||
selection_mode = account.imap_folder_selection_mode or "default"
|
||||
selected_folders = account.imap_selected_folders
|
||||
|
||||
for folder in folders:
|
||||
if stop_all:
|
||||
break
|
||||
|
||||
if should_skip_folder(folder):
|
||||
if not folder_should_be_scanned(
|
||||
folder,
|
||||
selection_mode=selection_mode,
|
||||
selected_folders=selected_folders,
|
||||
):
|
||||
logger.debug("Skipping folder: %s", folder)
|
||||
continue
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Tests for IMAP folder selection (BIT-26607)."""
|
||||
|
||||
from forwarder.email.imap_client import (
|
||||
default_scanned_folders,
|
||||
folder_should_be_scanned,
|
||||
should_skip_folder,
|
||||
)
|
||||
|
||||
|
||||
def test_should_skip_folder_logical_names():
|
||||
assert should_skip_folder("INBOX/Spam")
|
||||
assert should_skip_folder("Lixo")
|
||||
assert should_skip_folder("Sent Items")
|
||||
assert not should_skip_folder("INBOX/Faturas")
|
||||
|
||||
|
||||
def test_folder_should_be_scanned_default_mode():
|
||||
assert folder_should_be_scanned("INBOX/Faturas", selection_mode="default")
|
||||
assert not folder_should_be_scanned("INBOX/Spam", selection_mode="default")
|
||||
|
||||
|
||||
def test_folder_should_be_scanned_custom_mode():
|
||||
selected = ["INBOX", "INBOX/Faturas"]
|
||||
assert folder_should_be_scanned(
|
||||
"INBOX",
|
||||
selection_mode="custom",
|
||||
selected_folders=selected,
|
||||
)
|
||||
assert not folder_should_be_scanned(
|
||||
"INBOX/Spam",
|
||||
selection_mode="custom",
|
||||
selected_folders=selected,
|
||||
)
|
||||
assert not folder_should_be_scanned(
|
||||
"INBOX",
|
||||
selection_mode="custom",
|
||||
selected_folders=[],
|
||||
)
|
||||
|
||||
|
||||
def test_default_scanned_folders():
|
||||
all_folders = ["INBOX", "INBOX/Spam", "INBOX/Faturas", "Sent"]
|
||||
scanned = default_scanned_folders(all_folders)
|
||||
assert scanned == ["INBOX", "INBOX/Faturas"]
|
||||
@@ -112,6 +112,33 @@ def test_accepts_valid_pdf_attachment():
|
||||
assert len(collect_matching_attachments(msg)) == 1
|
||||
|
||||
|
||||
def test_accepts_pdf_with_leading_whitespace():
|
||||
pdf = b" \n\r\t" + b"%PDF-1.4\n" + (b"% invoice body\n" * 80)
|
||||
assert is_plausible_invoice_file(
|
||||
pdf,
|
||||
filename="1784074260.pdf",
|
||||
content_type="application/pdf",
|
||||
)
|
||||
|
||||
|
||||
def test_accepts_pdf_with_utf8_bom():
|
||||
pdf = b"\xef\xbb\xbf%PDF-1.4\n" + (b"% body\n" * 150)
|
||||
assert is_plausible_invoice_file(
|
||||
pdf,
|
||||
filename="scan.pdf",
|
||||
content_type="application/pdf",
|
||||
)
|
||||
|
||||
|
||||
def test_accepts_jpeg_bytes_with_pdf_extension():
|
||||
data = _fake_jpeg(800, 1200)
|
||||
assert is_plausible_invoice_file(
|
||||
data,
|
||||
filename="1784074260.pdf",
|
||||
content_type="application/pdf",
|
||||
)
|
||||
|
||||
|
||||
def test_rejects_truncated_pdf():
|
||||
msg = _msg_with_part(
|
||||
data=b"%PDF",
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
# Build stage — compile the React admin UI
|
||||
FROM node:20-alpine AS builder
|
||||
FROM node:24-alpine AS builder
|
||||
|
||||
WORKDIR /build
|
||||
COPY admin-ui/package*.json ./
|
||||
|
||||
Reference in new issue
Block a user