Compare commits
78
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
948b6ba2c6 | ||
|
|
54c317e452 | ||
|
|
969dbe08ce | ||
|
|
77ee80d3f1 | ||
|
|
c389503fb9 | ||
|
|
c9d1ad4b48 | ||
|
|
3ca283aa41 | ||
|
|
66dcd1f78e | ||
|
|
f39338a2a9 | ||
|
|
e1ddd2a293 | ||
|
|
f55629212c | ||
|
|
0998a016fa | ||
|
|
e160520655 | ||
|
|
4998a0f009 | ||
|
|
a782a97a1d | ||
|
|
c0c3109174 | ||
|
|
4fd7e51a7c | ||
|
|
ac932323c8 | ||
|
|
5bc5e0d889 | ||
|
|
bc39e00192 | ||
|
|
c2524c31a5 | ||
|
|
91b1a726e8 | ||
|
|
d63a9e0290 | ||
|
|
a5256c45a5 | ||
|
|
48d8ef2952 | ||
|
|
c83e452f54 | ||
|
|
7e5e4584fc | ||
|
|
3d81005588 | ||
|
|
a0f90bd8ef | ||
|
|
d8f298cec6 | ||
|
|
d561de7d02 | ||
|
|
1617be3aee | ||
|
|
f381af9c60 | ||
|
|
a4f4c2a921 | ||
|
|
b02add914e | ||
|
|
d3c26a453e | ||
|
|
28164ad9f4 | ||
|
|
529ecb31a4 | ||
|
|
0f4bb5f522 | ||
|
|
f165f411d9 | ||
|
|
6840e521dd | ||
|
|
16816e9d4e | ||
|
|
e31a1b4a7a | ||
|
|
b1382b4b95 | ||
|
|
31d32ed1b4 | ||
|
|
50b231caa6 | ||
|
|
5b841a8850 | ||
|
|
2ee2306c3e | ||
|
|
9b966cf325 | ||
|
|
66d7189aa5 | ||
|
|
95edd74d9f | ||
|
|
f19886d78e | ||
|
|
ea88e8833d | ||
|
|
bd2d04aba7 | ||
|
|
f55a38c032 | ||
|
|
b070af8503 | ||
|
|
f664cca6b5 | ||
|
|
87b1ad4b8a | ||
|
|
20966501a8 | ||
|
|
41ba0befe6 | ||
|
|
146593bf05 | ||
|
|
c834560f81 | ||
|
|
c281b2b56d | ||
|
|
df016a1e34 | ||
|
|
210bc7e324 | ||
|
|
eb4a95dfc2 | ||
|
|
0c63ae7fbd | ||
|
|
f6b276511a | ||
|
|
d476cb0204 | ||
|
|
6e6f1a44e4 | ||
|
|
3436611714 | ||
|
|
34f7fd9cdd | ||
|
|
7100440294 | ||
|
|
f3d2533db5 | ||
|
|
b211d9d8df | ||
|
|
fd1c1b1ba3 | ||
|
|
d1e4725ac3 | ||
|
|
305570458b |
No files matched your search
+31
-10
@@ -1,15 +1,36 @@
|
|||||||
# BizDocs Forwarder — environment template
|
# Copy to .env — never commit .env
|
||||||
# Copy to .env and fill in values. Never commit .env to git.
|
|
||||||
# Secrets managed via Infisical CT 235 (http://10.10.50.35)
|
|
||||||
|
|
||||||
# MySQL
|
# MySQL
|
||||||
MYSQL_ROOT_PASSWORD=change_me_strong_root_password
|
MYSQL_ROOT_PASSWORD=change_me_root
|
||||||
MYSQL_DATABASE=forwarder
|
MYSQL_DATABASE=forwarder
|
||||||
MYSQL_USER=forwarder_app
|
MYSQL_USER=forwarder
|
||||||
MYSQL_PASSWORD=change_me_strong_app_password
|
MYSQL_PASSWORD=change_me_db
|
||||||
|
|
||||||
# FastAPI
|
# App
|
||||||
SECRET_KEY=change_me_64char_random_hex_string
|
DATABASE_URL=mysql+pymysql://forwarder:change_me_db@mysql:3306/forwarder?charset=utf8mb4
|
||||||
|
ENCRYPTION_KEY=change_me_fernet_key
|
||||||
|
APP_SECRET=change_me_jwt_secret
|
||||||
|
ADMIN_USERNAME=admin
|
||||||
|
ADMIN_PASSWORD=change_me
|
||||||
|
|
||||||
# MySQL backup read-only user (created in Phase 4 of deploy runbook)
|
# Worker
|
||||||
MYSQL_BACKUP_PASS=change_me_backup_password
|
SYNC_INTERVAL_MINUTES=15
|
||||||
|
# Max successful SMTP forwards per rolling hour (0 = unlimited)
|
||||||
|
MAX_FORWARDS_PER_HOUR=400
|
||||||
|
# Forward queue: process at most N failed messages per tick
|
||||||
|
FORWARD_QUEUE_BATCH_SIZE=5
|
||||||
|
FORWARD_QUEUE_INTERVAL_SECONDS=60
|
||||||
|
|
||||||
|
# Gitea webhook autodeploy (deploy-hook service on :9090)
|
||||||
|
DEPLOY_WEBHOOK_SECRET=change_me_random_64_chars
|
||||||
|
# On CT 243 production, set absolute path to clone:
|
||||||
|
# FORWARDER_REPO_DIR=/opt/forwarder
|
||||||
|
|
||||||
|
# Error hub (errors.bitreport.pt)
|
||||||
|
ERROR_REPORTING_TOKEN=
|
||||||
|
ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt
|
||||||
|
ERROR_MONITORING_PROJECT_NAME=BizDocs Forwarder
|
||||||
|
ERROR_MONITORING_PROJECT_SLUG=bizdocs-forwarder
|
||||||
|
ERROR_MONITORING_GITEA_REPO=BitReport.pt/forwarder
|
||||||
|
ERROR_MONITORING_PAPERCLIP_PROJECT_ID=
|
||||||
|
ERROR_MONITORING_ENV=production
|
||||||
@@ -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
|
||||||
+50
-11
@@ -1,19 +1,58 @@
|
|||||||
# Node
|
|
||||||
admin-ui/node_modules/
|
|
||||||
admin-ui/dist/
|
|
||||||
|
|
||||||
# Python
|
# Python
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.py[cod]
|
||||||
*.pyo
|
*$py.class
|
||||||
.env
|
*.so
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
# Allow frontend source lib directories
|
||||||
|
!admin-ui/src/lib/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
*.egg-info/
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
|
||||||
|
# Virtual environments
|
||||||
.venv/
|
.venv/
|
||||||
venv/
|
venv/
|
||||||
|
ENV/
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
.pytest_cache/
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
|
||||||
|
# Legacy state
|
||||||
|
processed_emails.json
|
||||||
|
|
||||||
# Docker
|
# Docker
|
||||||
.docker/
|
*.log
|
||||||
|
storage/deploy-logs/*
|
||||||
|
!storage/deploy-logs/.gitkeep
|
||||||
|
|
||||||
# Editor
|
# Git credentials (deploy-hook container)
|
||||||
.vscode/
|
.git-credentials
|
||||||
.idea/
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
ARG FORWARDER_GIT_SHA=unknown
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
gcc \
|
||||||
|
default-libmysqlclient-dev \
|
||||||
|
pkg-config \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY pyproject.toml README.md ./
|
||||||
|
COPY src ./src
|
||||||
|
COPY alembic.ini ./
|
||||||
|
COPY migrations ./migrations
|
||||||
|
|
||||||
|
RUN pip install --no-cache-dir -e .
|
||||||
|
|
||||||
|
ENV PYTHONUNBUFFERED=1
|
||||||
|
ENV PYTHONPATH=/app/src
|
||||||
|
ENV FORWARDER_GIT_SHA=$FORWARDER_GIT_SHA
|
||||||
|
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
CMD ["uvicorn", "forwarder.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--app-dir", "src"]
|
||||||
@@ -1,35 +1,76 @@
|
|||||||
# BizDocs Forwarder
|
# BizDocs Forwarder
|
||||||
|
|
||||||
IMAP-to-BizDocs multi-account forwarder platform.
|
Multi-account IMAP → BizDocs forwarder: detect invoice attachments (PDF/XML/ZIP), forward original email via SMTP.
|
||||||
|
|
||||||
## Overview
|
- **Repo:** https://git.bitreport.pt/BitReport.pt/forwarder
|
||||||
|
- **Paperclip:** http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder
|
||||||
Automates document forwarding from IMAP email accounts to the BizDocs platform. Supports multiple accounts, with a background worker, REST API, and admin UI.
|
|
||||||
|
|
||||||
## Architecture
|
|
||||||
|
|
||||||
| Component | Description |
|
|
||||||
|-----------|-------------|
|
|
||||||
| **Worker** | Background process: polls IMAP, extracts attachments, forwards to BizDocs API |
|
|
||||||
| **API** | REST endpoints for account management, forwarding rules, and job status |
|
|
||||||
| **Admin UI** | Web interface for configuration and monitoring |
|
|
||||||
| **DB** | MySQL — account config, forwarding rules, job history |
|
|
||||||
|
|
||||||
## Stack
|
## Stack
|
||||||
|
|
||||||
- Python (worker + API)
|
| Component | Path | Description |
|
||||||
- MySQL
|
|-----------|------|-------------|
|
||||||
- Docker / Proxmox LXC (deploy target)
|
| API | `src/forwarder/api/` | FastAPI REST |
|
||||||
|
| Worker | `src/forwarder/worker/` | APScheduler IMAP sync |
|
||||||
|
| Admin UI | `admin-ui/` | Vite + React |
|
||||||
|
| DB | MySQL 8 | Alembic migrations |
|
||||||
|
|
||||||
## Getting Started
|
## Quick start
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
# Edit .env with your IMAP credentials and BizDocs API key
|
# Generate ENCRYPTION_KEY: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
||||||
docker compose up -d
|
|
||||||
|
docker compose up -d --build
|
||||||
|
docker compose exec api alembic upgrade head
|
||||||
```
|
```
|
||||||
|
|
||||||
## Related
|
- API: http://localhost:8000/api/health
|
||||||
|
- Admin UI: http://localhost:8080
|
||||||
|
- Auth: HTTP Basic (`ADMIN_USERNAME` / `ADMIN_PASSWORD`)
|
||||||
|
|
||||||
- Project board: http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder
|
## Local dev
|
||||||
- Repo: https://git.bitreport.pt/BitReport.pt/forwarder
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv && source .venv/bin/activate
|
||||||
|
pip install -e .
|
||||||
|
docker compose up -d mysql
|
||||||
|
alembic upgrade head
|
||||||
|
uvicorn forwarder.api.app:app --reload --app-dir src
|
||||||
|
forwarder worker # second terminal
|
||||||
|
cd admin-ui && npm install && npm run dev # third terminal
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deploy (Proxmox CT 243)
|
||||||
|
|
||||||
|
**Autodeploy:** push to `main` on Gitea → webhook → `deploy-hook` (:9090) → `deploy/deploy-pull.sh` → `docker compose build && up`.
|
||||||
|
|
||||||
|
### One-time setup (CT)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.bitreport.pt/BitReport.pt/forwarder.git /opt/forwarder
|
||||||
|
cd /opt/forwarder
|
||||||
|
cp .env.example .env # or ln -s /etc/forwarder/forwarder.env .env
|
||||||
|
# Set DEPLOY_WEBHOOK_SECRET in .env (same value as Gitea webhook secret)
|
||||||
|
export FORWARDER_REPO_DIR=/opt/forwarder
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Gitea webhook
|
||||||
|
|
||||||
|
Repo → Settings → Webhooks → Add:
|
||||||
|
|
||||||
|
| Field | Value |
|
||||||
|
|-------|-------|
|
||||||
|
| URL | `http://10.10.50.43:9090/` |
|
||||||
|
| Secret | same as `DEPLOY_WEBHOOK_SECRET` in `.env` |
|
||||||
|
| Events | Push |
|
||||||
|
|
||||||
|
Test: `curl -s http://10.10.50.43:9090/` → `{"status":"ok",...}`
|
||||||
|
|
||||||
|
Deploy logs: `/opt/forwarder/storage/deploy-logs/`
|
||||||
|
|
||||||
|
### Manual deploy (emergency only)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /opt/forwarder && bash deploy/deploy-pull.sh
|
||||||
|
```
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
FROM node:24-alpine AS build
|
||||||
|
ARG GIT_SHA=unknown
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY . .
|
||||||
|
RUN echo "admin-ui build ${GIT_SHA}" && npm run build
|
||||||
|
|
||||||
|
FROM nginx:alpine
|
||||||
|
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
# Use Docker's embedded DNS so upstream names are re-resolved dynamically.
|
||||||
|
# Using a variable in proxy_pass forces nginx to use this resolver on each request.
|
||||||
|
resolver 127.0.0.11 valid=5s;
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
set $api_upstream api;
|
||||||
|
proxy_pass http://$api_upstream:8000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 10s;
|
||||||
|
proxy_send_timeout 300s;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
root /usr/share/nginx/html;
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,5 +23,8 @@
|
|||||||
"tailwindcss": "^3.4.14",
|
"tailwindcss": "^3.4.14",
|
||||||
"typescript": "^5.6.3",
|
"typescript": "^5.6.3",
|
||||||
"vite": "^5.4.10"
|
"vite": "^5.4.10"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24.22.1"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+24
-11
@@ -1,21 +1,34 @@
|
|||||||
import { BrowserRouter, Routes, Route } from 'react-router-dom'
|
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
||||||
|
import { AuthProvider, useAuth } from './auth'
|
||||||
import Layout from './components/Layout'
|
import Layout from './components/Layout'
|
||||||
import Dashboard from './pages/Dashboard'
|
import Dashboard from './pages/Dashboard'
|
||||||
import Accounts from './pages/Accounts'
|
import Accounts from './pages/Accounts'
|
||||||
import Emails from './pages/Emails'
|
import Emails from './pages/Emails'
|
||||||
import ConnectionTest from './pages/ConnectionTest'
|
import ConnectionTest from './pages/ConnectionTest'
|
||||||
|
import Login from './pages/Login'
|
||||||
|
|
||||||
|
function AuthedRoutes() {
|
||||||
|
const { credentials } = useAuth()
|
||||||
|
if (!credentials) return <Login />
|
||||||
|
return (
|
||||||
|
<Routes>
|
||||||
|
<Route element={<Layout />}>
|
||||||
|
<Route index element={<Dashboard />} />
|
||||||
|
<Route path="/accounts" element={<Accounts />} />
|
||||||
|
<Route path="/emails" element={<Emails />} />
|
||||||
|
<Route path="/connection-test" element={<ConnectionTest />} />
|
||||||
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
|
</Route>
|
||||||
|
</Routes>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<AuthProvider>
|
||||||
<Routes>
|
<BrowserRouter>
|
||||||
<Route element={<Layout />}>
|
<AuthedRoutes />
|
||||||
<Route index element={<Dashboard />} />
|
</BrowserRouter>
|
||||||
<Route path="/accounts" element={<Accounts />} />
|
</AuthProvider>
|
||||||
<Route path="/emails" element={<Emails />} />
|
|
||||||
<Route path="/connection-test" element={<ConnectionTest />} />
|
|
||||||
</Route>
|
|
||||||
</Routes>
|
|
||||||
</BrowserRouter>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { createContext, useContext, useState, ReactNode } from 'react'
|
||||||
|
|
||||||
|
interface AuthCtx {
|
||||||
|
credentials: string | null
|
||||||
|
login: (user: string, pass: string) => void
|
||||||
|
logout: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const Ctx = createContext<AuthCtx>({
|
||||||
|
credentials: null,
|
||||||
|
login: () => {},
|
||||||
|
logout: () => {},
|
||||||
|
})
|
||||||
|
|
||||||
|
const KEY = 'fwd_auth'
|
||||||
|
|
||||||
|
function stored(): string | null {
|
||||||
|
try { return sessionStorage.getItem(KEY) } catch { return null }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||||
|
const [credentials, setCredentials] = useState<string | null>(stored)
|
||||||
|
|
||||||
|
const login = (user: string, pass: string) => {
|
||||||
|
const encoded = btoa(`${user}:${pass}`)
|
||||||
|
sessionStorage.setItem(KEY, encoded)
|
||||||
|
setCredentials(encoded)
|
||||||
|
}
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
sessionStorage.removeItem(KEY)
|
||||||
|
setCredentials(null)
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Ctx.Provider value={{ credentials, login, logout }}>{children}</Ctx.Provider>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useAuth() {
|
||||||
|
return useContext(Ctx)
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NavLink, Outlet } from 'react-router-dom'
|
import { NavLink, Outlet } from 'react-router-dom'
|
||||||
import { LayoutDashboard, Users, Mail, Wifi } from 'lucide-react'
|
import { LayoutDashboard, Users, Mail, Wifi, LogOut } from 'lucide-react'
|
||||||
|
import { useAuth } from '../auth'
|
||||||
|
|
||||||
const nav = [
|
const nav = [
|
||||||
{ to: '/', label: 'Dashboard', icon: LayoutDashboard },
|
{ to: '/', label: 'Dashboard', icon: LayoutDashboard },
|
||||||
@@ -9,6 +10,8 @@ const nav = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
export default function Layout() {
|
export default function Layout() {
|
||||||
|
const { logout } = useAuth()
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen">
|
<div className="flex h-screen">
|
||||||
<aside className="w-56 bg-gray-900 text-white flex flex-col">
|
<aside className="w-56 bg-gray-900 text-white flex flex-col">
|
||||||
@@ -35,6 +38,15 @@ export default function Layout() {
|
|||||||
</NavLink>
|
</NavLink>
|
||||||
))}
|
))}
|
||||||
</nav>
|
</nav>
|
||||||
|
<div className="p-3 border-t border-gray-700">
|
||||||
|
<button
|
||||||
|
onClick={logout}
|
||||||
|
className="flex items-center gap-3 px-3 py-2 w-full rounded-md text-sm text-gray-400 hover:bg-gray-800 hover:text-white transition-colors"
|
||||||
|
>
|
||||||
|
<LogOut size={16} />
|
||||||
|
Sair
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
<main className="flex-1 overflow-auto">
|
<main className="flex-1 overflow-auto">
|
||||||
<Outlet />
|
<Outlet />
|
||||||
|
|||||||
@@ -2,14 +2,22 @@ const styles: Record<string, string> = {
|
|||||||
pending: 'bg-yellow-100 text-yellow-800',
|
pending: 'bg-yellow-100 text-yellow-800',
|
||||||
forwarded: 'bg-green-100 text-green-800',
|
forwarded: 'bg-green-100 text-green-800',
|
||||||
failed: 'bg-red-100 text-red-800',
|
failed: 'bg-red-100 text-red-800',
|
||||||
|
missing_from_mailbox: 'bg-gray-100 text-gray-700',
|
||||||
active: 'bg-green-100 text-green-800',
|
active: 'bg-green-100 text-green-800',
|
||||||
inactive: 'bg-gray-100 text-gray-600',
|
inactive: 'bg-gray-100 text-gray-600',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
pending: 'pendente',
|
||||||
|
forwarded: 'reencaminhado',
|
||||||
|
failed: 'falhado',
|
||||||
|
missing_from_mailbox: 'apagado da mailbox',
|
||||||
|
}
|
||||||
|
|
||||||
export default function StatusBadge({ status }: { status: string }) {
|
export default function StatusBadge({ status }: { status: string }) {
|
||||||
return (
|
return (
|
||||||
<span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${styles[status] ?? 'bg-gray-100 text-gray-700'}`}>
|
<span className={`inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${styles[status] ?? 'bg-gray-100 text-gray-700'}`}>
|
||||||
{status}
|
{labels[status] ?? status}
|
||||||
</span>
|
</span>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
+155
-15
@@ -1,8 +1,16 @@
|
|||||||
const BASE = '/api'
|
const BASE = '/api'
|
||||||
|
|
||||||
|
function authHeader(): Record<string, string> {
|
||||||
|
try {
|
||||||
|
const cred = sessionStorage.getItem('fwd_auth')
|
||||||
|
if (cred) return { Authorization: `Basic ${cred}` }
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return {}
|
||||||
|
}
|
||||||
|
|
||||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
const res = await fetch(`${BASE}${path}`, {
|
const res = await fetch(`${BASE}${path}`, {
|
||||||
headers: { 'Content-Type': 'application/json', ...init?.headers },
|
headers: { 'Content-Type': 'application/json', ...authHeader(), ...init?.headers },
|
||||||
...init,
|
...init,
|
||||||
})
|
})
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -13,26 +21,41 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
return res.json()
|
return res.json()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const DEFAULT_DESTINATION_EMAIL = '[email protected]'
|
||||||
|
|
||||||
export interface Account {
|
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
|
||||||
bizdocs_api_key: string
|
destination_email: string | null
|
||||||
bizdocs_entity_id: string
|
bizdocs_email: string | null
|
||||||
|
bizdocs_company_id: string | null
|
||||||
|
bizdocs_api_base_url: string | null
|
||||||
|
sync_interval_minutes: number
|
||||||
active: boolean
|
active: boolean
|
||||||
|
imap_folder_selection_mode: 'default' | 'custom'
|
||||||
|
imap_selected_folders: string[] | null
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
@@ -40,14 +63,45 @@ export interface Message {
|
|||||||
account_id: number
|
account_id: number
|
||||||
account_name: string
|
account_name: string
|
||||||
message_uid: string
|
message_uid: string
|
||||||
|
message_key: string
|
||||||
subject: string
|
subject: string
|
||||||
sender: string
|
sender: string
|
||||||
received_at: string
|
received_at: string
|
||||||
status: 'pending' | 'forwarded' | 'failed'
|
date: string
|
||||||
|
folder: string
|
||||||
|
created_at: string
|
||||||
|
status: 'pending' | 'forwarded' | 'failed' | 'missing_from_mailbox'
|
||||||
error: string | null
|
error: string | null
|
||||||
forwarded_at: string | null
|
forwarded_at: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ForwardQueueStatus {
|
||||||
|
pending: number
|
||||||
|
forwards_used_last_hour: number
|
||||||
|
forwards_remaining_this_hour: number | null
|
||||||
|
max_forwards_per_hour: number
|
||||||
|
batch_size_per_tick: number
|
||||||
|
tick_interval_seconds: number
|
||||||
|
eta_hours_at_limit: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RetryBatchResult extends Partial<ForwardQueueStatus> {
|
||||||
|
queued?: boolean
|
||||||
|
attempted: number
|
||||||
|
succeeded: number
|
||||||
|
failed: number
|
||||||
|
rate_limited: boolean
|
||||||
|
errors: string[]
|
||||||
|
pending_total?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MessageList {
|
||||||
|
items: Message[]
|
||||||
|
total: number
|
||||||
|
limit: number
|
||||||
|
offset: number
|
||||||
|
}
|
||||||
|
|
||||||
export interface Stats {
|
export interface Stats {
|
||||||
accounts_total: number
|
accounts_total: number
|
||||||
accounts_active: number
|
accounts_active: number
|
||||||
@@ -55,18 +109,51 @@ export interface Stats {
|
|||||||
messages_pending: number
|
messages_pending: number
|
||||||
messages_forwarded: number
|
messages_forwarded: number
|
||||||
messages_failed: number
|
messages_failed: number
|
||||||
|
messages_missing_from_mailbox?: number
|
||||||
last_sync_at: string | null
|
last_sync_at: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
||||||
bizdocs_error: string | null
|
bizdocs_error: string | null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface SyncRunResult {
|
||||||
|
id: number
|
||||||
|
account_id: number
|
||||||
|
status: string
|
||||||
|
dry_run: boolean
|
||||||
|
max_emails: number | null
|
||||||
|
messages_scanned: number
|
||||||
|
messages_matched: number
|
||||||
|
messages_forwarded: number
|
||||||
|
messages_skipped: number
|
||||||
|
messages_failed: number
|
||||||
|
messages_missing_from_mailbox?: number
|
||||||
|
error_message: string | null
|
||||||
|
started_at: string
|
||||||
|
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 {
|
export interface TestPayload {
|
||||||
imap_host: string
|
imap_host: string
|
||||||
imap_port: number
|
imap_port: number
|
||||||
@@ -90,17 +177,70 @@ export const api = {
|
|||||||
update: (id: number, data: Partial<AccountCreate>) =>
|
update: (id: number, data: Partial<AccountCreate>) =>
|
||||||
request<Account>(`/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
request<Account>(`/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
|
||||||
delete: (id: number) => request<void>(`/accounts/${id}`, { method: 'DELETE' }),
|
delete: (id: number) => request<void>(`/accounts/${id}`, { method: 'DELETE' }),
|
||||||
|
sync: (id: number, opts?: { dry_run?: boolean; max_emails?: number }) => {
|
||||||
|
const q = new URLSearchParams()
|
||||||
|
if (opts?.dry_run) q.set('dry_run', 'true')
|
||||||
|
if (opts?.max_emails != null) q.set('max_emails', String(opts.max_emails))
|
||||||
|
const qs = q.toString()
|
||||||
|
return request<SyncRunResult>(`/accounts/${id}/sync${qs ? '?' + qs : ''}`, {
|
||||||
|
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: {
|
messages: {
|
||||||
list: (params?: { account_id?: number; status?: string; limit?: number; offset?: number }) => {
|
list: (params?: {
|
||||||
|
account_id?: number
|
||||||
|
status?: string
|
||||||
|
q?: string
|
||||||
|
limit?: number
|
||||||
|
offset?: number
|
||||||
|
}) => {
|
||||||
const q = new URLSearchParams()
|
const q = new URLSearchParams()
|
||||||
if (params?.account_id) q.set('account_id', String(params.account_id))
|
if (params?.account_id) q.set('account_id', String(params.account_id))
|
||||||
if (params?.status) q.set('status', params.status)
|
if (params?.status) q.set('status', params.status)
|
||||||
if (params?.limit) q.set('limit', String(params.limit))
|
if (params?.q) q.set('q', params.q)
|
||||||
if (params?.offset) q.set('offset', String(params.offset))
|
if (params?.limit != null) q.set('limit', String(params.limit))
|
||||||
return request<Message[]>(`/messages${q.toString() ? '?' + q : ''}`)
|
if (params?.offset != null) q.set('offset', String(params.offset))
|
||||||
|
return request<MessageList>(`/messages${q.toString() ? '?' + q : ''}`)
|
||||||
},
|
},
|
||||||
retry: (id: number) => request<void>(`/messages/${id}/retry`, { method: 'POST' }),
|
retry: (id: number) => request<Message>(`/messages/${id}/retry`, { method: 'POST' }),
|
||||||
|
retryBatch: (opts?: { limit?: number; account_id?: number; all?: boolean }) => {
|
||||||
|
const q = new URLSearchParams()
|
||||||
|
if (opts?.all) q.set('all', 'true')
|
||||||
|
else if (opts?.limit != null) q.set('limit', String(opts.limit))
|
||||||
|
if (opts?.account_id != null) q.set('account_id', String(opts.account_id))
|
||||||
|
return request<RetryBatchResult>(`/messages/retry-batch${q.toString() ? '?' + q : ''}`, {
|
||||||
|
method: 'POST',
|
||||||
|
})
|
||||||
|
},
|
||||||
|
queueStatus: () => request<ForwardQueueStatus>('/messages/queue/status'),
|
||||||
|
requeueForwarded: () =>
|
||||||
|
request<{ requeued: number } & ForwardQueueStatus>('/messages/requeue-forwarded', {
|
||||||
|
method: 'POST',
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
stats: {
|
stats: {
|
||||||
get: () => request<Stats>('/stats'),
|
get: () => request<Stats>('/stats'),
|
||||||
|
|||||||
+448
-54
@@ -1,48 +1,168 @@
|
|||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { api, Account, AccountCreate } from '../lib/api'
|
import { api, Account, AccountCreate, DEFAULT_DESTINATION_EMAIL, ImapFolderInfo } from '../lib/api'
|
||||||
import { useAsync } from '../hooks/useApi'
|
import { useAsync } from '../hooks/useApi'
|
||||||
import Spinner from '../components/Spinner'
|
import Spinner from '../components/Spinner'
|
||||||
import StatusBadge from '../components/StatusBadge'
|
import StatusBadge from '../components/StatusBadge'
|
||||||
import { Plus, Pencil, Trash2, Wifi, X, Check } from 'lucide-react'
|
import { Plus, Pencil, Trash2, Wifi, X, Check, Play, FlaskConical, RefreshCw } from 'lucide-react'
|
||||||
|
|
||||||
|
const DEFAULT_TEST_BATCH = 5
|
||||||
|
|
||||||
|
function formatSyncResult(r: import('../lib/api').SyncRunResult): string {
|
||||||
|
const mode = r.dry_run ? 'Dry-run' : 'Sync'
|
||||||
|
const limit =
|
||||||
|
r.max_emails != null ? ` (limite teste: ${r.max_emails} lidos)` : ' (completo)'
|
||||||
|
const skipped =
|
||||||
|
r.messages_skipped > 0 ? `, ${r.messages_skipped} já conhecidos` : ''
|
||||||
|
return `${mode}${limit}: ${r.messages_forwarded} enviados, ${r.messages_failed} falhas, ${r.messages_matched} match${skipped} — ${r.messages_scanned} lidos`
|
||||||
|
}
|
||||||
|
|
||||||
const EMPTY_FORM: AccountCreate = {
|
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_api_key: '',
|
bizdocs_email: '',
|
||||||
bizdocs_entity_id: '',
|
bizdocs_password: '',
|
||||||
active: true,
|
bizdocs_company_id: '',
|
||||||
|
bizdocs_api_base_url: '',
|
||||||
|
destination_email: DEFAULT_DESTINATION_EMAIL,
|
||||||
|
sync_interval_minutes: 15,
|
||||||
|
active: false,
|
||||||
|
imap_folder_selection_mode: 'default',
|
||||||
|
imap_selected_folders: null,
|
||||||
}
|
}
|
||||||
|
|
||||||
function AccountModal({
|
function AccountModal({
|
||||||
initial,
|
initial,
|
||||||
|
accountId,
|
||||||
onSave,
|
onSave,
|
||||||
onClose,
|
onClose,
|
||||||
}: {
|
}: {
|
||||||
initial: Partial<AccountCreate> | null
|
initial: Partial<AccountCreate> | null
|
||||||
|
accountId: number | null
|
||||||
onSave: (data: AccountCreate) => Promise<void>
|
onSave: (data: AccountCreate) => Promise<void>
|
||||||
onClose: () => void
|
onClose: () => void
|
||||||
}) {
|
}) {
|
||||||
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 [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 }))
|
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) => {
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
setSaving(true)
|
setSaving(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
|
|
||||||
|
const sourceEmail = form.email.trim()
|
||||||
|
const imapUser = (form.imap_user ?? '').trim() || sourceEmail
|
||||||
|
const webdavUser = (form.webdav_user ?? '').trim() || sourceEmail
|
||||||
|
const smtpUser = (form.smtp_user ?? '').trim() || sourceEmail || imapUser || webdavUser
|
||||||
|
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 = {
|
||||||
|
...form,
|
||||||
|
imap_user: isWebdav ? '' : imapUser,
|
||||||
|
webdav_user: isWebdav ? webdavUser : '',
|
||||||
|
smtp_user: smtpUser,
|
||||||
|
bizdocs_email: bizdocsEmail,
|
||||||
|
destination_email: form.destination_email?.trim() || DEFAULT_DESTINATION_EMAIL,
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
await onSave(form)
|
await onSave(payload)
|
||||||
onClose()
|
onClose()
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setError(e instanceof Error ? e.message : String(e))
|
setError(e instanceof Error ? e.message : String(e))
|
||||||
@@ -61,7 +181,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"
|
||||||
@@ -81,40 +201,188 @@ 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>
|
||||||
|
<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>
|
||||||
|
)}
|
||||||
|
|
||||||
<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>
|
||||||
|
|
||||||
|
{form.delivery_mode === 'api' ? (
|
||||||
|
<div className="grid grid-cols-2 gap-3">
|
||||||
|
{field('Email BizDocs', 'bizdocs_email', 'email')}
|
||||||
|
{field('Password BizDocs', 'bizdocs_password', 'password')}
|
||||||
|
{field('Company ID', 'bizdocs_company_id', 'text', 'UUID da empresa')}
|
||||||
|
<div className="col-span-2">
|
||||||
|
{field(
|
||||||
|
'API base URL (opcional)',
|
||||||
|
'bizdocs_api_base_url',
|
||||||
|
'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>
|
||||||
|
|
||||||
<fieldset className="border border-gray-200 rounded-md p-3">
|
{form.delivery_mode === 'smtp' && (
|
||||||
<legend className="text-xs font-semibold text-gray-500 px-1">BizDocs</legend>
|
<p className="text-xs text-gray-500 -mt-2">
|
||||||
<div className="grid grid-cols-2 gap-3 mt-1">
|
O remetente SMTP tem de estar autorizado como mailbox no portal BizDocs.
|
||||||
{field('API Key', 'bizdocs_api_key', 'password')}
|
</p>
|
||||||
{field('Entity ID', 'bizdocs_entity_id')}
|
)}
|
||||||
</div>
|
|
||||||
</fieldset>
|
|
||||||
|
|
||||||
<label className="flex items-center gap-2 cursor-pointer">
|
<label className="flex items-center gap-2 cursor-pointer">
|
||||||
<input
|
<input
|
||||||
@@ -165,7 +433,10 @@ export default function Accounts() {
|
|||||||
account: null,
|
account: null,
|
||||||
})
|
})
|
||||||
const [testResults, setTestResults] = useState<Record<number, { ok: boolean; msg: string }>>({})
|
const [testResults, setTestResults] = useState<Record<number, { ok: boolean; msg: string }>>({})
|
||||||
|
const [syncResults, setSyncResults] = useState<Record<number, { ok: boolean; msg: string }>>({})
|
||||||
const [testingId, setTestingId] = useState<number | null>(null)
|
const [testingId, setTestingId] = useState<number | null>(null)
|
||||||
|
const [syncingId, setSyncingId] = useState<number | null>(null)
|
||||||
|
const [testBatchSize, setTestBatchSize] = useState(DEFAULT_TEST_BATCH)
|
||||||
|
|
||||||
const openNew = () => setModal({ open: true, account: null })
|
const openNew = () => setModal({ open: true, account: null })
|
||||||
const openEdit = (a: Account) => setModal({ open: true, account: a })
|
const openEdit = (a: Account) => setModal({ open: true, account: a })
|
||||||
@@ -190,11 +461,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(' | ') },
|
||||||
@@ -209,12 +485,55 @@ export default function Accounts() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleSync = async (
|
||||||
|
id: number,
|
||||||
|
opts: { dry_run?: boolean; max_emails?: number },
|
||||||
|
confirmFull = false,
|
||||||
|
) => {
|
||||||
|
const account = accounts?.find((a) => a.id === id)
|
||||||
|
const isWebdav = account?.source_type === 'webdav'
|
||||||
|
if (confirmFull) {
|
||||||
|
const ok = confirm(
|
||||||
|
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
|
||||||
|
}
|
||||||
|
setSyncingId(id)
|
||||||
|
setSyncResults((prev) => {
|
||||||
|
const next = { ...prev }
|
||||||
|
delete next[id]
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
try {
|
||||||
|
const r = await api.accounts.sync(id, opts)
|
||||||
|
const failed = r.status === 'failed'
|
||||||
|
setSyncResults((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[id]: {
|
||||||
|
ok: !failed && r.messages_failed === 0,
|
||||||
|
msg: failed && r.error_message
|
||||||
|
? `Erro: ${r.error_message}`
|
||||||
|
: formatSyncResult(r),
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
} catch (e) {
|
||||||
|
setSyncResults((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[id]: { ok: false, msg: e instanceof Error ? e.message : 'Erro no sync' },
|
||||||
|
}))
|
||||||
|
} finally {
|
||||||
|
setSyncingId(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<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}
|
||||||
@@ -235,6 +554,27 @@ export default function Accounts() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{accounts && accounts.length > 0 && (
|
||||||
|
<div className="mb-4 flex flex-wrap items-center gap-3 text-sm text-gray-600 bg-blue-50 border border-blue-100 rounded-md px-4 py-3">
|
||||||
|
<span>
|
||||||
|
O worker automático só corre com <strong>Conta activa</strong>.{' '}
|
||||||
|
<strong>▶</strong> testa os primeiros N itens;{' '}
|
||||||
|
<strong>↻</strong> sync completo (toda a origem).
|
||||||
|
</span>
|
||||||
|
<label className="flex items-center gap-1.5 ml-auto">
|
||||||
|
Itens no teste ▶:
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={50}
|
||||||
|
value={testBatchSize}
|
||||||
|
onChange={(e) => setTestBatchSize(Math.max(1, Number(e.target.value) || 1))}
|
||||||
|
className="w-14 border border-gray-300 rounded px-2 py-0.5 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{accounts && accounts.length === 0 && (
|
{accounts && accounts.length === 0 && (
|
||||||
<div className="text-center py-12 text-gray-400 text-sm">
|
<div className="text-center py-12 text-gray-400 text-sm">
|
||||||
Nenhuma conta configurada. Clique em "Nova conta" para começar.
|
Nenhuma conta configurada. Clique em "Nova conta" para começar.
|
||||||
@@ -247,8 +587,9 @@ 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">IMAP</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">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>
|
||||||
</tr>
|
</tr>
|
||||||
@@ -257,24 +598,64 @@ 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">
|
<td className="px-4 py-3 text-gray-500 text-xs truncate max-w-[200px]" title={a.destination_email || ''}>
|
||||||
{a.imap_host}:{a.imap_port}
|
{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 items-center gap-2">
|
<div className="flex flex-col gap-1">
|
||||||
<StatusBadge status={a.active ? 'active' : 'inactive'} />
|
<div className="flex items-center gap-2">
|
||||||
{testResults[a.id] && (
|
<StatusBadge status={a.active ? 'active' : 'inactive'} />
|
||||||
|
{testResults[a.id] && (
|
||||||
|
<span
|
||||||
|
className={`text-xs ${testResults[a.id].ok ? 'text-green-600' : 'text-red-600'}`}
|
||||||
|
>
|
||||||
|
{testResults[a.id].msg}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{syncResults[a.id] && (
|
||||||
<span
|
<span
|
||||||
className={`text-xs ${testResults[a.id].ok ? 'text-green-600' : 'text-red-600'}`}
|
className={`text-xs ${syncResults[a.id].ok ? 'text-green-700' : 'text-red-600'}`}
|
||||||
>
|
>
|
||||||
{testResults[a.id].msg}
|
{syncResults[a.id].msg}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3">
|
<td className="px-4 py-3">
|
||||||
<div className="flex items-center justify-end gap-1">
|
<div className="flex items-center justify-end gap-1 flex-wrap">
|
||||||
|
<button
|
||||||
|
title={`Teste: ler no máximo ${testBatchSize} itens (não é sync completo)`}
|
||||||
|
onClick={() => handleSync(a.id, { max_emails: testBatchSize })}
|
||||||
|
disabled={syncingId === a.id}
|
||||||
|
className="p-1.5 text-gray-400 hover:text-green-600 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{syncingId === a.id ? (
|
||||||
|
<Spinner className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<Play size={14} />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
title={`Dry-run (${testBatchSize})`}
|
||||||
|
onClick={() =>
|
||||||
|
handleSync(a.id, { dry_run: true, max_emails: testBatchSize })
|
||||||
|
}
|
||||||
|
disabled={syncingId === a.id}
|
||||||
|
className="p-1.5 text-gray-400 hover:text-amber-600 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
<FlaskConical size={14} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
title={a.source_type === 'webdav' ? 'Sync completo — todos os ficheiros WebDAV' : 'Sync completo — percorre todas as pastas IMAP'}
|
||||||
|
onClick={() => handleSync(a.id, {}, true)}
|
||||||
|
disabled={syncingId === a.id}
|
||||||
|
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
<RefreshCw size={14} />
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
title="Testar ligação"
|
title="Testar ligação"
|
||||||
onClick={() => handleTest(a.id)}
|
onClick={() => handleTest(a.id)}
|
||||||
@@ -308,18 +689,31 @@ export default function Accounts() {
|
|||||||
|
|
||||||
{modal.open && (
|
{modal.open && (
|
||||||
<AccountModal
|
<AccountModal
|
||||||
|
accountId={modal.account?.id ?? null}
|
||||||
initial={
|
initial={
|
||||||
modal.account
|
modal.account
|
||||||
? {
|
? {
|
||||||
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,
|
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 || '',
|
||||||
|
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 || '',
|
||||||
bizdocs_entity_id: modal.account.bizdocs_entity_id,
|
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,
|
||||||
active: modal.account.active,
|
active: modal.account.active,
|
||||||
}
|
}
|
||||||
: null
|
: null
|
||||||
|
|||||||
+354
-60
@@ -1,29 +1,194 @@
|
|||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import { api, Message } from '../lib/api'
|
import { api, Message } from '../lib/api'
|
||||||
import { useAsync } from '../hooks/useApi'
|
import { useAsync } from '../hooks/useApi'
|
||||||
import Spinner from '../components/Spinner'
|
import Spinner from '../components/Spinner'
|
||||||
import StatusBadge from '../components/StatusBadge'
|
import StatusBadge from '../components/StatusBadge'
|
||||||
import { RefreshCw, RotateCcw } from 'lucide-react'
|
import { ChevronLeft, ChevronRight, RefreshCw, RotateCcw, Search, X } from 'lucide-react'
|
||||||
|
|
||||||
|
const PAGE_SIZE = 25
|
||||||
|
|
||||||
|
function formatMessageKey(key: string): string {
|
||||||
|
const at = key.indexOf('@')
|
||||||
|
if (at > 0) {
|
||||||
|
return key.slice(0, 8) + '…' + key.slice(at)
|
||||||
|
}
|
||||||
|
return key.length > 20 ? key.slice(0, 20) + '…' : key
|
||||||
|
}
|
||||||
|
|
||||||
export default function Emails() {
|
export default function Emails() {
|
||||||
const [filterStatus, setFilterStatus] = useState('')
|
const [filterStatus, setFilterStatus] = useState('')
|
||||||
|
const [searchInput, setSearchInput] = useState('')
|
||||||
|
const [searchQuery, setSearchQuery] = useState('')
|
||||||
|
const [page, setPage] = useState(0)
|
||||||
const [retryingId, setRetryingId] = useState<number | null>(null)
|
const [retryingId, setRetryingId] = useState<number | null>(null)
|
||||||
|
const [actionMsg, setActionMsg] = useState<{ ok: boolean; text: string } | null>(null)
|
||||||
|
const [batchRetrying, setBatchRetrying] = useState(false)
|
||||||
|
const [queueInfo, setQueueInfo] = useState<import('../lib/api').ForwardQueueStatus | null>(null)
|
||||||
|
|
||||||
const { data: messages, loading, error, reload } = useAsync<Message[]>(
|
const loadQueueStatus = async () => {
|
||||||
() => api.messages.list({ status: filterStatus || undefined, limit: 100 }),
|
try {
|
||||||
[filterStatus],
|
setQueueInfo(await api.messages.queueStatus())
|
||||||
|
} catch {
|
||||||
|
setQueueInfo(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadQueueStatus()
|
||||||
|
const t = setInterval(loadQueueStatus, 30_000)
|
||||||
|
return () => clearInterval(t)
|
||||||
|
}, [filterStatus, page, searchQuery])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const t = setTimeout(() => setSearchQuery(searchInput.trim()), 300)
|
||||||
|
return () => clearTimeout(t)
|
||||||
|
}, [searchInput])
|
||||||
|
|
||||||
|
const { data, loading, error, reload } = useAsync(
|
||||||
|
() =>
|
||||||
|
api.messages.list({
|
||||||
|
status: filterStatus || undefined,
|
||||||
|
q: searchQuery || undefined,
|
||||||
|
limit: PAGE_SIZE,
|
||||||
|
offset: page * PAGE_SIZE,
|
||||||
|
}),
|
||||||
|
[filterStatus, page, searchQuery],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const messages = data?.items
|
||||||
|
const total = data?.total ?? 0
|
||||||
|
const pageStart = total === 0 ? 0 : page * PAGE_SIZE + 1
|
||||||
|
const pageEnd = Math.min((page + 1) * PAGE_SIZE, total)
|
||||||
|
const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))
|
||||||
|
const canPrev = page > 0
|
||||||
|
const canNext = (page + 1) * PAGE_SIZE < total
|
||||||
|
|
||||||
const handleRetry = async (id: number) => {
|
const handleRetry = async (id: number) => {
|
||||||
setRetryingId(id)
|
setRetryingId(id)
|
||||||
|
setActionMsg(null)
|
||||||
try {
|
try {
|
||||||
await api.messages.retry(id)
|
await api.messages.retry(id)
|
||||||
|
setActionMsg({ ok: true, text: `Mensagem #${id} reencaminhada com sucesso.` })
|
||||||
reload()
|
reload()
|
||||||
|
} catch (e) {
|
||||||
|
setActionMsg({
|
||||||
|
ok: false,
|
||||||
|
text: e instanceof Error ? e.message : `Retry falhou (#${id})`,
|
||||||
|
})
|
||||||
} finally {
|
} finally {
|
||||||
setRetryingId(null)
|
setRetryingId(null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleRetryBatch = async () => {
|
||||||
|
setBatchRetrying(true)
|
||||||
|
setActionMsg(null)
|
||||||
|
try {
|
||||||
|
const r = await api.messages.retryBatch({ limit: 5 })
|
||||||
|
const ok = !r.rate_limited && (r.succeeded > 0 || r.pending_total === 0)
|
||||||
|
setActionMsg({
|
||||||
|
ok,
|
||||||
|
text: r.rate_limited
|
||||||
|
? `Fila pausada — limite horário (${r.max_forwards_per_hour ?? 400}/h). ${r.pending_total ?? r.pending ?? '?'} ainda pendentes.`
|
||||||
|
: r.attempted === 0
|
||||||
|
? 'Fila vazia — nada a reenviar.'
|
||||||
|
: `Fila: ${r.succeeded}/${r.attempted} enviados neste tick (${r.pending_total ?? '?'} pendentes).`,
|
||||||
|
})
|
||||||
|
await loadQueueStatus()
|
||||||
|
reload()
|
||||||
|
} catch (e) {
|
||||||
|
setActionMsg({
|
||||||
|
ok: false,
|
||||||
|
text: e instanceof Error ? e.message : 'Retry em lote falhou',
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
setBatchRetrying(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(0)
|
||||||
|
}, [filterStatus, searchQuery])
|
||||||
|
|
||||||
|
const handleRequeueAll = async () => {
|
||||||
|
const forwarded = queueInfo
|
||||||
|
? (await api.stats.get().catch(() => null))?.messages_forwarded
|
||||||
|
: null
|
||||||
|
const ok = confirm(
|
||||||
|
`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 ` +
|
||||||
|
`(limite ${queueInfo?.max_forwards_per_hour ?? 400}/hora). ` +
|
||||||
|
`BizDocs ignora duplicados.\n\n` +
|
||||||
|
(forwarded != null ? `${forwarded} mensagens serão reenviadas gradualmente.` : ''),
|
||||||
|
)
|
||||||
|
if (!ok) return
|
||||||
|
setBatchRetrying(true)
|
||||||
|
setActionMsg(null)
|
||||||
|
try {
|
||||||
|
const r = await api.messages.requeueForwarded()
|
||||||
|
setActionMsg({
|
||||||
|
ok: true,
|
||||||
|
text: `${r.requeued} mensagens na fila. ETA ~${r.eta_hours_at_limit ?? '?'}h (${r.pending} pendentes).`,
|
||||||
|
})
|
||||||
|
await loadQueueStatus()
|
||||||
|
reload()
|
||||||
|
} catch (e) {
|
||||||
|
setActionMsg({
|
||||||
|
ok: false,
|
||||||
|
text: e instanceof Error ? e.message : 'Falha ao enfileirar',
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
setBatchRetrying(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRetryAll = async () => {
|
||||||
|
let failedCount = filterStatus === 'failed' ? total : 0
|
||||||
|
if (failedCount === 0) {
|
||||||
|
try {
|
||||||
|
const stats = await api.stats.get()
|
||||||
|
failedCount = stats.messages_failed
|
||||||
|
} catch {
|
||||||
|
failedCount = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (failedCount === 0) {
|
||||||
|
setActionMsg({ ok: true, text: 'Não há mensagens falhadas para repetir.' })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const batch = queueInfo?.batch_size_per_tick ?? 5
|
||||||
|
const maxHour = queueInfo?.max_forwards_per_hour ?? 400
|
||||||
|
const ok = confirm(
|
||||||
|
`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.`,
|
||||||
|
)
|
||||||
|
if (!ok) return
|
||||||
|
|
||||||
|
setBatchRetrying(true)
|
||||||
|
setActionMsg(null)
|
||||||
|
try {
|
||||||
|
const r = await api.messages.retryBatch({ all: true })
|
||||||
|
const pending = r.pending ?? failedCount
|
||||||
|
const eta = r.eta_hours_at_limit
|
||||||
|
setActionMsg({
|
||||||
|
ok: true,
|
||||||
|
text:
|
||||||
|
pending === 0
|
||||||
|
? 'Não há mensagens falhadas na fila.'
|
||||||
|
: `${pending} mensagens na fila. ETA ~${eta ?? '?'}h. O worker processa automaticamente.`,
|
||||||
|
})
|
||||||
|
await loadQueueStatus()
|
||||||
|
reload()
|
||||||
|
} catch (e) {
|
||||||
|
setActionMsg({
|
||||||
|
ok: false,
|
||||||
|
text: e instanceof Error ? e.message : 'Falha ao enfileirar',
|
||||||
|
})
|
||||||
|
} finally {
|
||||||
|
setBatchRetrying(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<div className="flex items-center justify-between mb-6">
|
<div className="flex items-center justify-between mb-6">
|
||||||
@@ -32,6 +197,34 @@ export default function Emails() {
|
|||||||
<p className="text-sm text-gray-500 mt-0.5">Histórico de mensagens processadas</p>
|
<p className="text-sm text-gray-500 mt-0.5">Histórico de mensagens processadas</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleRequeueAll}
|
||||||
|
disabled={batchRetrying || loading}
|
||||||
|
className="text-sm px-3 py-1.5 border border-emerald-300 text-emerald-800 bg-emerald-50 rounded-md hover:bg-emerald-100 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{batchRetrying ? 'A enfileirar…' : 'Reenviar todas (fila)'}
|
||||||
|
</button>
|
||||||
|
{(filterStatus === 'failed' || filterStatus === '') && (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleRetryBatch}
|
||||||
|
disabled={batchRetrying || loading}
|
||||||
|
className="text-sm px-3 py-1.5 border border-amber-300 text-amber-800 bg-amber-50 rounded-md hover:bg-amber-100 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{batchRetrying ? 'A processar…' : 'Processar tick da fila (5)'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleRetryAll}
|
||||||
|
disabled={batchRetrying || loading}
|
||||||
|
className="text-sm px-3 py-1.5 border border-indigo-300 text-indigo-800 bg-indigo-50 rounded-md hover:bg-indigo-100 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
Enfileirar todas as falhadas
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<select
|
<select
|
||||||
value={filterStatus}
|
value={filterStatus}
|
||||||
onChange={(e) => setFilterStatus(e.target.value)}
|
onChange={(e) => setFilterStatus(e.target.value)}
|
||||||
@@ -41,6 +234,7 @@ export default function Emails() {
|
|||||||
<option value="pending">Pendente</option>
|
<option value="pending">Pendente</option>
|
||||||
<option value="forwarded">Reencaminhado</option>
|
<option value="forwarded">Reencaminhado</option>
|
||||||
<option value="failed">Falhado</option>
|
<option value="failed">Falhado</option>
|
||||||
|
<option value="missing_from_mailbox">Apagado da mailbox</option>
|
||||||
</select>
|
</select>
|
||||||
<button
|
<button
|
||||||
onClick={reload}
|
onClick={reload}
|
||||||
@@ -51,78 +245,178 @@ export default function Emails() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4 flex items-center gap-2 max-w-xl">
|
||||||
|
<div className="relative flex-1">
|
||||||
|
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
value={searchInput}
|
||||||
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
|
placeholder="Pesquisar assunto, remetente, pasta, Message-ID ou #id…"
|
||||||
|
className="w-full pl-9 pr-9 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||||
|
/>
|
||||||
|
{searchInput && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSearchInput('')}
|
||||||
|
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600"
|
||||||
|
title="Limpar pesquisa"
|
||||||
|
>
|
||||||
|
<X size={14} />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{searchQuery && (
|
||||||
|
<span className="text-xs text-gray-500 whitespace-nowrap">
|
||||||
|
{total} resultado{total === 1 ? '' : 's'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{queueInfo && (queueInfo.pending > 0 || queueInfo.forwards_used_last_hour > 0) && (
|
||||||
|
<div className="mb-4 px-4 py-3 rounded-md text-sm border bg-sky-50 border-sky-200 text-sky-900">
|
||||||
|
<strong>Fila de reenvio:</strong> {queueInfo.pending} pendente
|
||||||
|
{queueInfo.pending > 0 && queueInfo.eta_hours_at_limit != null && (
|
||||||
|
<> — ETA ~{queueInfo.eta_hours_at_limit}h</>
|
||||||
|
)}
|
||||||
|
{' · '}
|
||||||
|
{queueInfo.forwards_used_last_hour}/{queueInfo.max_forwards_per_hour} enviados na última hora
|
||||||
|
{queueInfo.forwards_remaining_this_hour != null && (
|
||||||
|
<> ({queueInfo.forwards_remaining_this_hour} restantes)</>
|
||||||
|
)}
|
||||||
|
{' · '}
|
||||||
|
{queueInfo.batch_size_per_tick} por minuto
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{loading && !messages && (
|
{loading && !messages && (
|
||||||
<div className="flex justify-center py-12">
|
<div className="flex justify-center py-12">
|
||||||
<Spinner />
|
<Spinner />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{actionMsg && (
|
||||||
|
<div
|
||||||
|
className={`mb-4 px-4 py-3 rounded-md text-sm border ${
|
||||||
|
actionMsg.ok
|
||||||
|
? 'bg-green-50 border-green-200 text-green-800'
|
||||||
|
: 'bg-red-50 border-red-200 text-red-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{actionMsg.text}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
|
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
|
||||||
{error}
|
{error}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{messages && messages.length === 0 && (
|
{messages && messages.length === 0 && !loading && (
|
||||||
<div className="text-center py-12 text-gray-400 text-sm">
|
<div className="text-center py-12 text-gray-400 text-sm">
|
||||||
Nenhuma mensagem{filterStatus ? ` com estado "${filterStatus}"` : ''}.
|
Nenhuma mensagem
|
||||||
|
{searchQuery ? ` para "${searchQuery}"` : ''}
|
||||||
|
{filterStatus ? ` com estado "${filterStatus}"` : ''}.
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{messages && messages.length > 0 && (
|
{messages && messages.length > 0 && (
|
||||||
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
<>
|
||||||
<table className="w-full text-sm">
|
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||||
<thead className="bg-gray-50 border-b border-gray-200">
|
<table className="w-full text-sm">
|
||||||
<tr>
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
|
<tr>
|
||||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
|
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
|
||||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</th>
|
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
|
||||||
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Recebido</th>
|
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</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">Data email</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-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Pasta</th>
|
||||||
</tr>
|
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
|
||||||
</thead>
|
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
|
||||||
<tbody className="divide-y divide-gray-100">
|
|
||||||
{messages.map((m) => (
|
|
||||||
<tr key={m.id} className="hover:bg-gray-50">
|
|
||||||
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
|
|
||||||
<td className="px-4 py-3 font-medium truncate max-w-xs" title={m.subject}>
|
|
||||||
{m.subject || '(sem assunto)'}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-gray-600 text-xs truncate max-w-[180px]">{m.sender}</td>
|
|
||||||
<td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
|
|
||||||
{new Date(m.received_at).toLocaleString('pt-PT')}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<div>
|
|
||||||
<StatusBadge status={m.status} />
|
|
||||||
{m.error && (
|
|
||||||
<p className="text-xs text-red-500 mt-0.5 truncate max-w-xs" title={m.error}>
|
|
||||||
{m.error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-right">
|
|
||||||
{m.status === 'failed' && (
|
|
||||||
<button
|
|
||||||
title="Tentar novamente"
|
|
||||||
onClick={() => handleRetry(m.id)}
|
|
||||||
disabled={retryingId === m.id}
|
|
||||||
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
|
|
||||||
>
|
|
||||||
{retryingId === m.id ? (
|
|
||||||
<Spinner className="h-4 w-4" />
|
|
||||||
) : (
|
|
||||||
<RotateCcw size={14} />
|
|
||||||
)}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
</thead>
|
||||||
</tbody>
|
<tbody className="divide-y divide-gray-100">
|
||||||
</table>
|
{messages.map((m: Message) => (
|
||||||
</div>
|
<tr key={m.id} className="hover:bg-gray-50">
|
||||||
|
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
|
||||||
|
<td className="px-4 py-3 font-medium truncate max-w-xs">
|
||||||
|
<span title={`${m.message_key}\nProcessado: ${new Date(m.created_at).toLocaleString('pt-PT')}`}>
|
||||||
|
{m.subject || '(sem assunto)'}
|
||||||
|
</span>
|
||||||
|
<p className="text-xs text-gray-400 font-normal truncate" title={m.message_key}>
|
||||||
|
{formatMessageKey(m.message_key)}
|
||||||
|
</p>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-gray-600 text-xs truncate max-w-[180px]">{m.sender}</td>
|
||||||
|
<td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
|
||||||
|
{new Date(m.received_at).toLocaleString('pt-PT')}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-gray-500 text-xs truncate max-w-[120px]" title={m.folder}>
|
||||||
|
{m.folder}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<div>
|
||||||
|
<StatusBadge status={m.status} />
|
||||||
|
{m.error && (
|
||||||
|
<p className="text-xs text-red-500 mt-0.5 truncate max-w-xs" title={m.error}>
|
||||||
|
{m.error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-right">
|
||||||
|
{m.status === 'failed' && (
|
||||||
|
<button
|
||||||
|
title="Tentar novamente"
|
||||||
|
onClick={() => handleRetry(m.id)}
|
||||||
|
disabled={retryingId === m.id}
|
||||||
|
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
|
||||||
|
>
|
||||||
|
{retryingId === m.id ? (
|
||||||
|
<Spinner className="h-4 w-4" />
|
||||||
|
) : (
|
||||||
|
<RotateCcw size={14} />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between mt-4 text-sm text-gray-600">
|
||||||
|
<span>
|
||||||
|
{total === 0
|
||||||
|
? '0 mensagens'
|
||||||
|
: `${pageStart}–${pageEnd} de ${total} mensagem${total === 1 ? '' : 's'}`}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="text-xs text-gray-400">
|
||||||
|
Página {page + 1} de {totalPages}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPage((p) => p - 1)}
|
||||||
|
disabled={!canPrev || loading}
|
||||||
|
className="flex items-center gap-1 px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
<ChevronLeft size={14} />
|
||||||
|
Anterior
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPage((p) => p + 1)}
|
||||||
|
disabled={!canNext || loading}
|
||||||
|
className="flex items-center gap-1 px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
Seguinte
|
||||||
|
<ChevronRight size={14} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { useState, FormEvent } from 'react'
|
||||||
|
import { useAuth } from '../auth'
|
||||||
|
|
||||||
|
export default function Login() {
|
||||||
|
const { login } = useAuth()
|
||||||
|
const [user, setUser] = useState('')
|
||||||
|
const [pass, setPass] = useState('')
|
||||||
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
const [loading, setLoading] = useState(false)
|
||||||
|
|
||||||
|
const handleSubmit = async (e: FormEvent) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError(null)
|
||||||
|
setLoading(true)
|
||||||
|
try {
|
||||||
|
const encoded = btoa(`${user}:${pass}`)
|
||||||
|
const res = await fetch('/api/stats', {
|
||||||
|
headers: { Authorization: `Basic ${encoded}` },
|
||||||
|
})
|
||||||
|
if (res.status === 401) {
|
||||||
|
setError('Credenciais inválidas')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
login(user, pass)
|
||||||
|
} catch {
|
||||||
|
setError('Erro de ligação ao servidor')
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-50 flex items-center justify-center">
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-8 w-full max-w-sm shadow-sm">
|
||||||
|
<h1 className="text-xl font-semibold text-gray-900 mb-1">BizDocs Forwarder</h1>
|
||||||
|
<p className="text-sm text-gray-500 mb-6">Iniciar sessão</p>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-gray-700 mb-1">Utilizador</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={user}
|
||||||
|
onChange={e => setUser(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
required
|
||||||
|
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-medium text-gray-700 mb-1">Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={pass}
|
||||||
|
onChange={e => setPass(e.target.value)}
|
||||||
|
required
|
||||||
|
className="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<p className="text-xs text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={loading}
|
||||||
|
className="w-full bg-indigo-600 text-white text-sm py-2 rounded-md hover:bg-indigo-700 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{loading ? 'A autenticar…' : 'Entrar'}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = migrations
|
||||||
|
prepend_sys_path = .
|
||||||
|
src
|
||||||
|
version_path_separator = os
|
||||||
|
|
||||||
|
sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
FROM php:8.5-cli-alpine
|
||||||
|
|
||||||
|
RUN apk add --no-cache bash git curl docker-cli docker-cli-compose
|
||||||
|
|
||||||
|
WORKDIR /opt/deploy
|
||||||
|
COPY deploy-pull.sh webhook-receiver.php ./
|
||||||
|
RUN chmod +x deploy-pull.sh
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
CMD ["php", "-S", "0.0.0.0:8080", "webhook-receiver.php"]
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
BACKUP_DIR=/opt/forwarder/backups
|
||||||
|
KEEP_DAYS=14
|
||||||
|
TS=$(date +%Y%m%d_%H%M%S)
|
||||||
|
FILE="$BACKUP_DIR/forwarder_${TS}.sql.gz"
|
||||||
|
mkdir -p "$BACKUP_DIR"
|
||||||
|
set -a; source /opt/forwarder/.env; set +a
|
||||||
|
docker exec forwarder-mysql-1 \
|
||||||
|
mysqldump --no-tablespaces -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" \
|
||||||
|
| gzip > "$FILE"
|
||||||
|
SIZE=$(du -h "$FILE" | cut -f1)
|
||||||
|
echo "Backup: $FILE ($SIZE)"
|
||||||
|
find "$BACKUP_DIR" -name "forwarder_*.sql.gz" -mtime +$KEEP_DAYS -delete
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# BizDocs Forwarder — pull from Gitea + docker compose rebuild (CT 243 / /opt/forwarder).
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
REPO_DIR="${FORWARDER_REPO_DIR:-/opt/forwarder}"
|
||||||
|
DEPLOY_BRANCH="${DEPLOY_BRANCH:-main}"
|
||||||
|
COMPOSE="docker compose"
|
||||||
|
STATUS_FILE="$REPO_DIR/storage/deploy-logs/last-deploy.status"
|
||||||
|
|
||||||
|
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [forwarder-deploy] $*"; }
|
||||||
|
|
||||||
|
remove_stale_service_containers() {
|
||||||
|
local service="$1"
|
||||||
|
local container="forwarder-${service}-1"
|
||||||
|
docker rm -f "$container" 2>/dev/null || true
|
||||||
|
docker ps -a --format '{{.Names}}' | grep "_${container}$" | xargs -r docker rm -f || true
|
||||||
|
}
|
||||||
|
|
||||||
|
write_status() {
|
||||||
|
mkdir -p "$(dirname "$STATUS_FILE")"
|
||||||
|
echo "$1" > "$STATUS_FILE"
|
||||||
|
}
|
||||||
|
|
||||||
|
on_error() {
|
||||||
|
write_status "failed $(date -Iseconds) — see latest deploy-*.log"
|
||||||
|
}
|
||||||
|
trap on_error ERR
|
||||||
|
|
||||||
|
if [ ! -d "$REPO_DIR/.git" ]; then
|
||||||
|
log "FATAL: git repo missing at $REPO_DIR"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
cd "$REPO_DIR"
|
||||||
|
|
||||||
|
log "Fetching origin/$DEPLOY_BRANCH"
|
||||||
|
git fetch origin "$DEPLOY_BRANCH"
|
||||||
|
git reset --hard "origin/$DEPLOY_BRANCH"
|
||||||
|
GIT_SHA=$(git rev-parse --short HEAD)
|
||||||
|
log "HEAD $GIT_SHA — $(git log -1 --format=%s)"
|
||||||
|
|
||||||
|
if [ ! -f .env ] && [ -f /etc/forwarder/forwarder.env ]; then
|
||||||
|
log "Linking .env from /etc/forwarder/forwarder.env"
|
||||||
|
ln -sf /etc/forwarder/forwarder.env .env
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -f .env ]; then
|
||||||
|
log "FATAL: .env missing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
export FORWARDER_GIT_SHA="$GIT_SHA"
|
||||||
|
|
||||||
|
LOG_FILE="$REPO_DIR/storage/deploy-logs/deploy-$(date +%Y%m%d-%H%M%S).log"
|
||||||
|
mkdir -p "$(dirname "$LOG_FILE")"
|
||||||
|
|
||||||
|
log "Building API + worker ($GIT_SHA)"
|
||||||
|
{
|
||||||
|
$COMPOSE build --build-arg FORWARDER_GIT_SHA="$GIT_SHA" api worker migrate
|
||||||
|
log "Running migrations"
|
||||||
|
$COMPOSE run --rm migrate
|
||||||
|
remove_stale_service_containers api
|
||||||
|
remove_stale_service_containers worker
|
||||||
|
$COMPOSE up -d --force-recreate api worker
|
||||||
|
log "Building admin UI ($GIT_SHA)"
|
||||||
|
$COMPOSE build --build-arg GIT_SHA="$GIT_SHA" web
|
||||||
|
remove_stale_service_containers web
|
||||||
|
$COMPOSE up -d --force-recreate web
|
||||||
|
HEALTH_URL="${HEALTH_CHECK_URL:-http://127.0.0.1:8000/api/health}"
|
||||||
|
for i in 1 2 3 4 5; do
|
||||||
|
curl -sf --max-time 8 "$HEALTH_URL" >/dev/null && break
|
||||||
|
log "API not ready yet (attempt $i/5), retrying in 5s..."
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
curl -sf --max-time 8 "$HEALTH_URL" >/dev/null
|
||||||
|
write_status "ok $GIT_SHA $(date -Iseconds)"
|
||||||
|
log "Deploy OK ($GIT_SHA)"
|
||||||
|
log "Refreshing deploy-hook (self-restart — runs detached)"
|
||||||
|
$COMPOSE build deploy-hook
|
||||||
|
nohup $COMPOSE up -d --force-recreate deploy-hook &
|
||||||
|
} >> "$LOG_FILE" 2>&1
|
||||||
|
# webhook: http://forwarder-hook.bitreport.pt/ (NPM proxy, commit 2026-07-01T01:13:13Z)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://api:8000/api/;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 200 'BizDocs Forwarder API — use /api/health\n';
|
||||||
|
add_header Content-Type text/plain;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gitea push webhook → deploy-pull.sh (BizDocs Forwarder standalone repo).
|
||||||
|
* Env: DEPLOY_WEBHOOK_SECRET, FORWARDER_REPO_DIR, DEPLOY_BRANCH
|
||||||
|
*/
|
||||||
|
|
||||||
|
header('Content-Type: application/json');
|
||||||
|
|
||||||
|
$secret = getenv('DEPLOY_WEBHOOK_SECRET') ?: '';
|
||||||
|
$repoDir = getenv('FORWARDER_REPO_DIR') ?: '/opt/forwarder';
|
||||||
|
$deployBranch = getenv('DEPLOY_BRANCH') ?: 'main';
|
||||||
|
$allowedRepo = 'bitreport.pt/forwarder';
|
||||||
|
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
||||||
|
$statusFile = $repoDir . '/storage/deploy-logs/last-deploy.status';
|
||||||
|
$status = null;
|
||||||
|
if (is_file($statusFile)) {
|
||||||
|
$status = trim((string) file_get_contents($statusFile));
|
||||||
|
}
|
||||||
|
$gitHead = null;
|
||||||
|
$headFile = $repoDir . '/.git/refs/heads/' . $deployBranch;
|
||||||
|
if (is_file($headFile)) {
|
||||||
|
$gitHead = substr(trim((string) file_get_contents($headFile)), 0, 7);
|
||||||
|
}
|
||||||
|
http_response_code(200);
|
||||||
|
echo json_encode([
|
||||||
|
'status' => 'ok',
|
||||||
|
'message' => 'Forwarder deploy webhook. POST Gitea push events.',
|
||||||
|
'repo_dir' => $repoDir,
|
||||||
|
'git_head' => $gitHead,
|
||||||
|
'last_deploy' => $status,
|
||||||
|
], JSON_UNESCAPED_SLASHES);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||||
|
http_response_code(405);
|
||||||
|
echo json_encode(['error' => 'Method not allowed']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($secret === '') {
|
||||||
|
http_response_code(500);
|
||||||
|
echo json_encode(['error' => 'DEPLOY_WEBHOOK_SECRET not configured']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$rawBody = file_get_contents('php://input');
|
||||||
|
if ($rawBody === false || $rawBody === '') {
|
||||||
|
http_response_code(400);
|
||||||
|
echo json_encode(['error' => 'Empty body']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$signatureHeader = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? '';
|
||||||
|
if ($signatureHeader === '' && !empty($_SERVER['HTTP_X_HUB_SIGNATURE_256'])) {
|
||||||
|
$raw = trim((string) $_SERVER['HTTP_X_HUB_SIGNATURE_256']);
|
||||||
|
$signatureHeader = str_starts_with($raw, 'sha256=') ? substr($raw, 7) : $raw;
|
||||||
|
}
|
||||||
|
if ($signatureHeader === '' || !hash_equals(hash_hmac('sha256', $rawBody, $secret), $signatureHeader)) {
|
||||||
|
http_response_code(403);
|
||||||
|
echo json_encode(['error' => 'Invalid signature']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$event = $_SERVER['HTTP_X_GITEA_EVENT'] ?? '';
|
||||||
|
if ($event !== 'push') {
|
||||||
|
http_response_code(200);
|
||||||
|
echo json_encode(['status' => 'ignored', 'reason' => 'Not a push event']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = json_decode($rawBody, true);
|
||||||
|
if (!is_array($payload)) {
|
||||||
|
http_response_code(400);
|
||||||
|
echo json_encode(['error' => 'Invalid JSON']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$repoFullName = strtolower((string) ($payload['repository']['full_name'] ?? ''));
|
||||||
|
if ($repoFullName !== $allowedRepo) {
|
||||||
|
http_response_code(403);
|
||||||
|
echo json_encode(['error' => 'Repository not allowed', 'repo' => $repoFullName]);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$ref = (string) ($payload['ref'] ?? '');
|
||||||
|
if ($ref !== 'refs/heads/' . $deployBranch) {
|
||||||
|
http_response_code(200);
|
||||||
|
echo json_encode(['status' => 'ignored', 'reason' => 'Branch mismatch', 'ref' => $ref]);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$deployScript = $repoDir . '/deploy/deploy-pull.sh';
|
||||||
|
if (!is_file($deployScript)) {
|
||||||
|
$deployScript = __DIR__ . '/deploy-pull.sh';
|
||||||
|
}
|
||||||
|
if (!is_file($deployScript)) {
|
||||||
|
http_response_code(500);
|
||||||
|
echo json_encode(['error' => 'deploy-pull.sh missing']);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
|
||||||
|
$logFile = $repoDir . '/storage/deploy-logs/deploy-' . date('Ymd-His') . '.log';
|
||||||
|
@mkdir(dirname($logFile), 0750, true);
|
||||||
|
|
||||||
|
$cmd = sprintf(
|
||||||
|
'nohup env FORWARDER_REPO_DIR=%s DEPLOY_BRANCH=%s bash %s >> %s 2>&1 &',
|
||||||
|
escapeshellarg($repoDir),
|
||||||
|
escapeshellarg($deployBranch),
|
||||||
|
escapeshellarg($deployScript),
|
||||||
|
escapeshellarg($logFile)
|
||||||
|
);
|
||||||
|
|
||||||
|
exec($cmd);
|
||||||
|
|
||||||
|
http_response_code(202);
|
||||||
|
echo json_encode([
|
||||||
|
'status' => 'queued',
|
||||||
|
'log' => $logFile,
|
||||||
|
'head' => $payload['after'] ?? null,
|
||||||
|
]);
|
||||||
+54
-43
@@ -3,76 +3,87 @@ services:
|
|||||||
image: mysql:8.0
|
image: mysql:8.0
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
|
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root}
|
||||||
MYSQL_DATABASE: ${MYSQL_DATABASE:-forwarder}
|
MYSQL_DATABASE: ${MYSQL_DATABASE:-forwarder}
|
||||||
MYSQL_USER: ${MYSQL_USER:-forwarder_app}
|
MYSQL_USER: ${MYSQL_USER:-forwarder}
|
||||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
|
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-forwarder}
|
||||||
|
ports:
|
||||||
|
- "3306:3306"
|
||||||
volumes:
|
volumes:
|
||||||
- mysql_data:/var/lib/mysql
|
- mysql_data:/var/lib/mysql
|
||||||
- ./api/migrations/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
|
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uforwarder", "-p${MYSQL_PASSWORD:-forwarder}"]
|
||||||
interval: 10s
|
interval: 10s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 5
|
retries: 5
|
||||||
start_period: 30s
|
start_period: 30s
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
build: .
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
mysql:
|
||||||
|
condition: service_healthy
|
||||||
|
command: ["alembic", "upgrade", "head"]
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
api:
|
api:
|
||||||
build:
|
build:
|
||||||
context: ./api
|
context: .
|
||||||
dockerfile: Dockerfile
|
args:
|
||||||
|
FORWARDER_GIT_SHA: ${FORWARDER_GIT_SHA:-unknown}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
environment:
|
env_file:
|
||||||
- MYSQL_HOST=mysql
|
- .env
|
||||||
- MYSQL_PORT=3306
|
|
||||||
- MYSQL_DATABASE=${MYSQL_DATABASE:-forwarder}
|
|
||||||
- MYSQL_USER=${MYSQL_USER:-forwarder_app}
|
|
||||||
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
|
|
||||||
- SECRET_KEY=${SECRET_KEY}
|
|
||||||
depends_on:
|
depends_on:
|
||||||
mysql:
|
migrate:
|
||||||
condition: service_healthy
|
condition: service_completed_successfully
|
||||||
healthcheck:
|
command: ["uvicorn", "forwarder.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--app-dir", "src"]
|
||||||
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
|
|
||||||
interval: 30s
|
|
||||||
timeout: 10s
|
|
||||||
retries: 3
|
|
||||||
start_period: 15s
|
|
||||||
|
|
||||||
worker:
|
worker:
|
||||||
build:
|
build:
|
||||||
context: ./worker
|
context: .
|
||||||
dockerfile: Dockerfile
|
args:
|
||||||
|
FORWARDER_GIT_SHA: ${FORWARDER_GIT_SHA:-unknown}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
env_file:
|
||||||
- MYSQL_HOST=mysql
|
- .env
|
||||||
- MYSQL_PORT=3306
|
|
||||||
- MYSQL_DATABASE=${MYSQL_DATABASE:-forwarder}
|
|
||||||
- MYSQL_USER=${MYSQL_USER:-forwarder_app}
|
|
||||||
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
|
|
||||||
- SECRET_KEY=${SECRET_KEY}
|
|
||||||
depends_on:
|
depends_on:
|
||||||
mysql:
|
migrate:
|
||||||
condition: service_healthy
|
condition: service_completed_successfully
|
||||||
api:
|
command: ["forwarder", "worker"]
|
||||||
condition: service_healthy
|
|
||||||
|
|
||||||
web:
|
web:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: ./admin-ui
|
||||||
dockerfile: web/Dockerfile
|
dockerfile: Dockerfile
|
||||||
|
args:
|
||||||
|
GIT_SHA: ${FORWARDER_GIT_SHA:-unknown}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "3000:80"
|
- "8080:80"
|
||||||
depends_on:
|
depends_on:
|
||||||
- api
|
- api
|
||||||
healthcheck:
|
|
||||||
test: ["CMD", "curl", "-f", "http://localhost:80/"]
|
deploy-hook:
|
||||||
interval: 30s
|
build:
|
||||||
timeout: 5s
|
context: ./deploy
|
||||||
retries: 3
|
dockerfile: Dockerfile
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "9090:8080"
|
||||||
|
environment:
|
||||||
|
FORWARDER_REPO_DIR: /opt/forwarder
|
||||||
|
DEPLOY_BRANCH: main
|
||||||
|
DEPLOY_WEBHOOK_SECRET: ${DEPLOY_WEBHOOK_SECRET:-}
|
||||||
|
volumes:
|
||||||
|
- ${FORWARDER_REPO_DIR:-.}:/opt/forwarder
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql_data:
|
mysql_data:
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import sys
|
||||||
|
from logging.config import fileConfig
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||||
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
from forwarder.db.base import Base
|
||||||
|
from forwarder.db import models # noqa: F401
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def get_url() -> str:
|
||||||
|
return get_settings().database_url
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
url = get_url()
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
configuration = config.get_section(config.config_ini_section) or {}
|
||||||
|
configuration["sqlalchemy.url"] = get_url()
|
||||||
|
connectable = engine_from_config(
|
||||||
|
configuration,
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(connection=connection, target_metadata=target_metadata)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
"""Initial schema
|
||||||
|
|
||||||
|
Revision ID: 001_initial
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-06-30
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "001_initial"
|
||||||
|
down_revision: Union[str, None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"users",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("username", sa.String(length=128), nullable=False),
|
||||||
|
sa.Column("password_hash", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("is_admin", sa.Boolean(), nullable=False, server_default=sa.text("1")),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("username"),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"accounts",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")),
|
||||||
|
sa.Column("sync_interval_minutes", sa.Integer(), nullable=False, server_default=sa.text("15")),
|
||||||
|
sa.Column("imap_host", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("imap_port", sa.Integer(), nullable=False, server_default=sa.text("993")),
|
||||||
|
sa.Column("imap_user", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("imap_password_encrypted", sa.Text(), nullable=False),
|
||||||
|
sa.Column("smtp_host", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("smtp_port", sa.Integer(), nullable=False, server_default=sa.text("587")),
|
||||||
|
sa.Column("smtp_user", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("smtp_password_encrypted", sa.Text(), nullable=False),
|
||||||
|
sa.Column("smtp_use_tls", sa.Boolean(), nullable=False, server_default=sa.text("1")),
|
||||||
|
sa.Column("destination_email", sa.String(length=255), nullable=False),
|
||||||
|
sa.Column("include_all_attachments", sa.Boolean(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("allowed_extensions", sa.JSON(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"user_accounts",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("account_id", sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]),
|
||||||
|
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"messages",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("account_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("message_key", sa.String(length=512), nullable=False),
|
||||||
|
sa.Column("folder", sa.String(length=512), nullable=False),
|
||||||
|
sa.Column("uid", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("subject", sa.String(length=1024), nullable=False, server_default=""),
|
||||||
|
sa.Column("from_addr", sa.String(length=512), nullable=False, server_default=""),
|
||||||
|
sa.Column("date", sa.String(length=128), nullable=False, server_default=""),
|
||||||
|
sa.Column(
|
||||||
|
"status",
|
||||||
|
sa.Enum("pending", "forwarded", "failed", "skipped", "dry_run", name="messagestatus"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("error_message", sa.Text(), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("account_id", "message_key", name="uq_account_message_key"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_messages_account_id", "messages", ["account_id"])
|
||||||
|
op.create_index("ix_messages_status", "messages", ["status"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"forward_attempts",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("message_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("success", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("dry_run", sa.Boolean(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("error_message", sa.Text(), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["message_id"], ["messages.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_forward_attempts_message_id", "forward_attempts", ["message_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"sync_runs",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("account_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"status",
|
||||||
|
sa.Enum("running", "completed", "failed", name="syncrunstatus"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("dry_run", sa.Boolean(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("max_emails", sa.Integer(), nullable=True),
|
||||||
|
sa.Column("messages_scanned", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("messages_matched", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("messages_forwarded", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("messages_skipped", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("messages_failed", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("error_message", sa.Text(), nullable=True),
|
||||||
|
sa.Column("started_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_sync_runs_account_id", "sync_runs", ["account_id"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"connection_tests",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("account_id", sa.Integer(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"test_type",
|
||||||
|
sa.Enum("imap", "smtp", "send", name="connectiontesttype"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("success", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column("message", sa.Text(), nullable=False),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("CURRENT_TIMESTAMP"), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["account_id"], ["accounts.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_connection_tests_account_id", "connection_tests", ["account_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_connection_tests_account_id", table_name="connection_tests")
|
||||||
|
op.drop_table("connection_tests")
|
||||||
|
op.drop_index("ix_sync_runs_account_id", table_name="sync_runs")
|
||||||
|
op.drop_table("sync_runs")
|
||||||
|
op.drop_index("ix_forward_attempts_message_id", table_name="forward_attempts")
|
||||||
|
op.drop_table("forward_attempts")
|
||||||
|
op.drop_index("ix_messages_status", table_name="messages")
|
||||||
|
op.drop_index("ix_messages_account_id", table_name="messages")
|
||||||
|
op.drop_table("messages")
|
||||||
|
op.drop_table("user_accounts")
|
||||||
|
op.drop_table("accounts")
|
||||||
|
op.drop_table("users")
|
||||||
|
op.execute("DROP TYPE IF EXISTS connectiontesttype")
|
||||||
|
op.execute("DROP TYPE IF EXISTS syncrunstatus")
|
||||||
|
op.execute("DROP TYPE IF EXISTS messagestatus")
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Add missing_from_mailbox message status."""
|
||||||
|
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "002_missing_from_mailbox"
|
||||||
|
down_revision: Union[str, None] = "001_initial"
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.execute(
|
||||||
|
"ALTER TABLE messages MODIFY COLUMN status "
|
||||||
|
"ENUM('pending', 'forwarded', 'failed', 'skipped', 'dry_run', 'missing_from_mailbox') NOT NULL"
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
"""
|
||||||
|
UPDATE messages SET status = 'missing_from_mailbox'
|
||||||
|
WHERE status = 'failed' AND (
|
||||||
|
error_message LIKE 'Could not fetch message UID%%'
|
||||||
|
OR error_message LIKE 'Could not open folder:%%'
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.execute(
|
||||||
|
"UPDATE messages SET status = 'failed' WHERE status = 'missing_from_mailbox'"
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
"ALTER TABLE messages MODIFY COLUMN status "
|
||||||
|
"ENUM('pending', 'forwarded', 'failed', 'skipped', 'dry_run') NOT NULL"
|
||||||
|
)
|
||||||
@@ -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")
|
||||||
@@ -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")
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""Add webdav_min_year for year-folder filtering (2025+)
|
||||||
|
|
||||||
|
Revision ID: 005_webdav_years
|
||||||
|
Revises: 004_webdav
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "005_webdav_years"
|
||||||
|
down_revision: Union[str, None] = "004_webdav"
|
||||||
|
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("webdav_min_year", sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("accounts", "webdav_min_year")
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""Add shop_accounts, scraped_documents, shop_scrape_runs tables
|
||||||
|
|
||||||
|
Revision ID: 006_shop_accounts
|
||||||
|
Revises: 005_webdav_include_years
|
||||||
|
Create Date: 2026-07-06
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "006_shop_accounts"
|
||||||
|
down_revision: Union[str, None] = "005_webdav_years"
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"shop_accounts",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("name", sa.String(255), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"shop_type",
|
||||||
|
sa.Enum("temu", "amazon", name="shoptype"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("enabled", sa.Boolean(), nullable=False, server_default=sa.text("1")),
|
||||||
|
sa.Column(
|
||||||
|
"sync_interval_minutes",
|
||||||
|
sa.Integer(),
|
||||||
|
nullable=False,
|
||||||
|
server_default=sa.text("60"),
|
||||||
|
),
|
||||||
|
sa.Column("shop_email_encrypted", sa.Text(), nullable=True),
|
||||||
|
sa.Column("shop_password_encrypted", sa.Text(), nullable=True),
|
||||||
|
sa.Column("session_state_encrypted", sa.Text(), nullable=True),
|
||||||
|
sa.Column("session_state_saved_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("bizdocs_email", sa.String(255), nullable=True),
|
||||||
|
sa.Column("bizdocs_password_encrypted", sa.Text(), nullable=True),
|
||||||
|
sa.Column("bizdocs_company_id", sa.String(100), nullable=True),
|
||||||
|
sa.Column("bizdocs_api_base_url", sa.String(512), nullable=True),
|
||||||
|
sa.Column("last_scraped_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"updated_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"scraped_documents",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("shop_account_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("order_id", sa.String(255), nullable=False),
|
||||||
|
sa.Column("filename", sa.String(512), nullable=False, server_default=""),
|
||||||
|
sa.Column(
|
||||||
|
"status",
|
||||||
|
sa.Enum(
|
||||||
|
"pending", "uploaded", "failed", "skipped",
|
||||||
|
name="scrapeddocumentstatus",
|
||||||
|
),
|
||||||
|
nullable=False,
|
||||||
|
server_default="pending",
|
||||||
|
),
|
||||||
|
sa.Column("bizdocs_doc_id", sa.String(255), nullable=True),
|
||||||
|
sa.Column("error_message", sa.Text(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"updated_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.ForeignKeyConstraint(["shop_account_id"], ["shop_accounts.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("shop_account_id", "order_id", name="uq_shop_account_order"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_scraped_documents_shop_account_id", "scraped_documents", ["shop_account_id"])
|
||||||
|
op.create_index("ix_scraped_documents_status", "scraped_documents", ["status"])
|
||||||
|
|
||||||
|
op.create_table(
|
||||||
|
"shop_scrape_runs",
|
||||||
|
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||||
|
sa.Column("shop_account_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"status",
|
||||||
|
sa.Enum("running", "completed", "failed", name="shopscraperrunstatus"),
|
||||||
|
nullable=False,
|
||||||
|
server_default="running",
|
||||||
|
),
|
||||||
|
sa.Column("orders_found", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("invoices_uploaded", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("invoices_failed", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("invoices_skipped", sa.Integer(), nullable=False, server_default=sa.text("0")),
|
||||||
|
sa.Column("error_message", sa.Text(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"started_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("CURRENT_TIMESTAMP"),
|
||||||
|
nullable=False,
|
||||||
|
),
|
||||||
|
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(["shop_account_id"], ["shop_accounts.id"]),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
"ix_shop_scrape_runs_shop_account_id", "shop_scrape_runs", ["shop_account_id"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("shop_scrape_runs")
|
||||||
|
op.drop_table("scraped_documents")
|
||||||
|
op.drop_table("shop_accounts")
|
||||||
|
op.execute("DROP TYPE IF EXISTS shopscraperrunstatus")
|
||||||
|
op.execute("DROP TYPE IF EXISTS scrapeddocumentstatus")
|
||||||
|
op.execute("DROP TYPE IF EXISTS shoptype")
|
||||||
@@ -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")
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=68", "wheel"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "bizdocs-forwarder"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Multi-account IMAP to BizDocs email forwarder"
|
||||||
|
readme = "README.md"
|
||||||
|
requires-python = ">=3.12"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115.0",
|
||||||
|
"uvicorn[standard]>=0.32.0",
|
||||||
|
"sqlalchemy>=2.0.36",
|
||||||
|
"alembic>=1.14.0",
|
||||||
|
"pymysql>=1.1.1",
|
||||||
|
"cryptography>=43.0.0",
|
||||||
|
"apscheduler>=3.10.4",
|
||||||
|
"pydantic>=2.10.0",
|
||||||
|
"pydantic-settings>=2.6.0",
|
||||||
|
"python-multipart>=0.0.17",
|
||||||
|
"bcrypt>=4.0.0",
|
||||||
|
"httpx>=0.28.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"pytest>=8.0.0",
|
||||||
|
"httpx>=0.28.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.scripts]
|
||||||
|
forwarder = "forwarder.cli:main"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
|
|
||||||
|
[tool.setuptools.package-data]
|
||||||
|
forwarder = ["py.typed"]
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
"""BizDocs Forwarder — multi-account IMAP to BizDocs email forwarder."""
|
||||||
|
|
||||||
|
__version__ = "0.1.0"
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
|
||||||
|
__all__ = ["main"]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
from forwarder.cli import main as cli_main
|
||||||
|
|
||||||
|
cli_main()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Whitespace-only changes.
@@ -0,0 +1,56 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
from forwarder import __version__
|
||||||
|
from forwarder.api.routes import accounts, connection, health, messages, shop_accounts, stats, sync_runs
|
||||||
|
from forwarder.error_reporter import report_error
|
||||||
|
from forwarder.services.auth_service import ensure_admin_user
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> FastAPI:
|
||||||
|
app = FastAPI(
|
||||||
|
title="BizDocs Forwarder",
|
||||||
|
version=__version__,
|
||||||
|
description="Multi-account IMAP to BizDocs email forwarder",
|
||||||
|
)
|
||||||
|
|
||||||
|
@app.exception_handler(Exception)
|
||||||
|
async def _unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
|
||||||
|
logger.exception("Unhandled exception on %s %s", request.method, request.url.path)
|
||||||
|
report_error(
|
||||||
|
exc,
|
||||||
|
severity="error",
|
||||||
|
url=str(request.url),
|
||||||
|
endpoint=f"{request.method} {request.url.path}",
|
||||||
|
context_data={"request_method": request.method, "request_path": request.url.path},
|
||||||
|
)
|
||||||
|
return JSONResponse(status_code=500, content={"detail": "Internal server error"})
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
def on_startup() -> None:
|
||||||
|
try:
|
||||||
|
ensure_admin_user()
|
||||||
|
except Exception as exc:
|
||||||
|
report_error(exc, severity="critical", endpoint="startup:ensure_admin_user")
|
||||||
|
raise
|
||||||
|
logger.info("BizDocs Forwarder API started")
|
||||||
|
|
||||||
|
app.include_router(health.router, prefix="/api")
|
||||||
|
app.include_router(accounts.router, prefix="/api")
|
||||||
|
app.include_router(messages.router, prefix="/api")
|
||||||
|
app.include_router(sync_runs.router, prefix="/api")
|
||||||
|
app.include_router(stats.router, prefix="/api")
|
||||||
|
app.include_router(connection.router, prefix="/api")
|
||||||
|
app.include_router(shop_accounts.router, prefix="/api")
|
||||||
|
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Annotated
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from forwarder.db.session import get_db
|
||||||
|
from forwarder.services.auth_service import authenticate_user
|
||||||
|
|
||||||
|
security = HTTPBasic()
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user(
|
||||||
|
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
|
||||||
|
) -> str:
|
||||||
|
user = authenticate_user(credentials.username, credentials.password)
|
||||||
|
if user is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Invalid credentials",
|
||||||
|
headers={"WWW-Authenticate": "Basic"},
|
||||||
|
)
|
||||||
|
return user.username
|
||||||
|
|
||||||
|
|
||||||
|
DbSession = Annotated[Session, Depends(get_db)]
|
||||||
|
CurrentUser = Annotated[str, Depends(get_current_user)]
|
||||||
Whitespace-only changes.
@@ -0,0 +1,418 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query, status
|
||||||
|
|
||||||
|
from forwarder.api.deps import CurrentUser, DbSession
|
||||||
|
from forwarder.api.routes.connection import ConnectionTestResult
|
||||||
|
from forwarder.api.schemas import (
|
||||||
|
AccountCreate,
|
||||||
|
AccountResponse,
|
||||||
|
AccountUpdate,
|
||||||
|
ConnectionTestResponse,
|
||||||
|
ImapFoldersResponse,
|
||||||
|
InlineConnectionConfig,
|
||||||
|
SyncRunResponse,
|
||||||
|
)
|
||||||
|
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.smtp_client import SmtpConfig, test_smtp_connection
|
||||||
|
from forwarder.services import account_service
|
||||||
|
from forwarder.services.sync_service import sync_account
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/accounts", tags=["accounts"])
|
||||||
|
|
||||||
|
|
||||||
|
def _to_response(account) -> AccountResponse:
|
||||||
|
data = account_service.account_to_dict(account)
|
||||||
|
return AccountResponse(**data)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/test/imap", response_model=ConnectionTestResponse)
|
||||||
|
def test_imap_presave(
|
||||||
|
inline: InlineConnectionConfig,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> ConnectionTestResponse:
|
||||||
|
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")
|
||||||
|
success, message = account_service.run_imap_test(db, None, data)
|
||||||
|
return ConnectionTestResponse(success=success, message=message)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/test/smtp", response_model=ConnectionTestResponse)
|
||||||
|
def test_smtp_presave(
|
||||||
|
inline: InlineConnectionConfig,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> ConnectionTestResponse:
|
||||||
|
data = inline.model_dump(exclude_unset=True)
|
||||||
|
required = ("smtp_host", "smtp_user", "smtp_password")
|
||||||
|
for field in required:
|
||||||
|
if not data.get(field):
|
||||||
|
raise HTTPException(status_code=400, detail=f"{field} is required")
|
||||||
|
success, message = account_service.run_smtp_test(db, None, data)
|
||||||
|
return ConnectionTestResponse(success=success, message=message)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/test/send", response_model=ConnectionTestResponse)
|
||||||
|
def test_send_presave(
|
||||||
|
inline: InlineConnectionConfig,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> ConnectionTestResponse:
|
||||||
|
data = inline.model_dump(exclude_unset=True)
|
||||||
|
required = ("smtp_host", "smtp_user", "smtp_password", "destination_email")
|
||||||
|
for field in required:
|
||||||
|
if not data.get(field):
|
||||||
|
raise HTTPException(status_code=400, detail=f"{field} is required")
|
||||||
|
success, message = account_service.run_send_test(db, None, data)
|
||||||
|
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.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)]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{account_id}", response_model=AccountResponse)
|
||||||
|
def get_account(account_id: int, db: DbSession, _user: CurrentUser) -> AccountResponse:
|
||||||
|
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
|
||||||
|
return _to_response(account)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=AccountResponse, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_account(
|
||||||
|
payload: AccountCreate, db: DbSession, _user: CurrentUser
|
||||||
|
) -> AccountResponse:
|
||||||
|
account = account_service.create_account(db, payload.model_dump())
|
||||||
|
return _to_response(account)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{account_id}", response_model=AccountResponse)
|
||||||
|
def update_account(
|
||||||
|
account_id: int,
|
||||||
|
payload: AccountUpdate,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> AccountResponse:
|
||||||
|
try:
|
||||||
|
account = account_service.update_account(
|
||||||
|
db, account_id, payload.model_dump(exclude_unset=True)
|
||||||
|
)
|
||||||
|
except account_service.AccountNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
return _to_response(account)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
def delete_account(account_id: int, db: DbSession, _user: CurrentUser) -> None:
|
||||||
|
try:
|
||||||
|
account_service.delete_account(db, account_id)
|
||||||
|
except account_service.AccountNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _inline_dict(inline: InlineConnectionConfig | None) -> dict | None:
|
||||||
|
if inline is None:
|
||||||
|
return None
|
||||||
|
data = inline.model_dump(exclude_unset=True)
|
||||||
|
if not data:
|
||||||
|
return None
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{account_id}/test", response_model=ConnectionTestResult)
|
||||||
|
def test_account(
|
||||||
|
account_id: int,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> ConnectionTestResult:
|
||||||
|
"""Run source + delivery tests for a saved account (combined result for the UI)."""
|
||||||
|
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
|
||||||
|
|
||||||
|
is_webdav = account.source_type == SourceType.webdav
|
||||||
|
imap_ok = True
|
||||||
|
imap_msg = None
|
||||||
|
webdav_ok = True
|
||||||
|
webdav_msg = None
|
||||||
|
|
||||||
|
if is_webdav:
|
||||||
|
try:
|
||||||
|
webdav_ok, webdav_msg = account_service.run_webdav_test(db, account_id, None)
|
||||||
|
except ValueError as exc:
|
||||||
|
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(
|
||||||
|
imap_ok=imap_ok,
|
||||||
|
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_error=None if smtp_ok else smtp_msg,
|
||||||
|
bizdocs_ok=bizdocs_ok,
|
||||||
|
bizdocs_error=None if bizdocs_ok else bizdocs_msg,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{account_id}/test/imap", response_model=ConnectionTestResponse)
|
||||||
|
def test_imap(
|
||||||
|
account_id: int,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
inline: InlineConnectionConfig | None = None,
|
||||||
|
) -> ConnectionTestResponse:
|
||||||
|
"""Test IMAP for a saved account; optional body overrides stored credentials."""
|
||||||
|
try:
|
||||||
|
success, message = account_service.run_imap_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/smtp", response_model=ConnectionTestResponse)
|
||||||
|
def test_smtp(
|
||||||
|
account_id: int,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
inline: InlineConnectionConfig | None = None,
|
||||||
|
) -> ConnectionTestResponse:
|
||||||
|
try:
|
||||||
|
success, message = account_service.run_smtp_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/send", response_model=ConnectionTestResponse)
|
||||||
|
def test_send(
|
||||||
|
account_id: int,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
inline: InlineConnectionConfig | None = None,
|
||||||
|
) -> ConnectionTestResponse:
|
||||||
|
try:
|
||||||
|
success, message = account_service.run_send_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("/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)
|
||||||
|
def trigger_sync(
|
||||||
|
account_id: int,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
dry_run: bool = Query(default=False),
|
||||||
|
max_emails: int | None = Query(default=None, ge=1),
|
||||||
|
) -> SyncRunResponse:
|
||||||
|
try:
|
||||||
|
account_service.get_account(db, account_id)
|
||||||
|
except account_service.AccountNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
sync_run = sync_account(db, account_id, dry_run=dry_run, max_emails=max_emails)
|
||||||
|
return SyncRunResponse(
|
||||||
|
id=sync_run.id,
|
||||||
|
account_id=sync_run.account_id,
|
||||||
|
status=sync_run.status.value,
|
||||||
|
dry_run=sync_run.dry_run,
|
||||||
|
max_emails=sync_run.max_emails,
|
||||||
|
messages_scanned=sync_run.messages_scanned,
|
||||||
|
messages_matched=sync_run.messages_matched,
|
||||||
|
messages_forwarded=sync_run.messages_forwarded,
|
||||||
|
messages_skipped=sync_run.messages_skipped,
|
||||||
|
messages_failed=sync_run.messages_failed,
|
||||||
|
error_message=sync_run.error_message,
|
||||||
|
started_at=sync_run.started_at,
|
||||||
|
finished_at=sync_run.finished_at,
|
||||||
|
)
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from forwarder.api.deps import CurrentUser
|
||||||
|
from forwarder.email.imap_client import ImapConfig, test_imap_connection
|
||||||
|
from forwarder.email.smtp_client import SmtpConfig, test_smtp_connection
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/connection", tags=["connection"])
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionTestPayload(BaseModel):
|
||||||
|
imap_host: str = ""
|
||||||
|
imap_port: int = 993
|
||||||
|
imap_user: str = ""
|
||||||
|
imap_password: str = ""
|
||||||
|
smtp_host: str = ""
|
||||||
|
smtp_port: int = 587
|
||||||
|
smtp_user: str = ""
|
||||||
|
smtp_password: str = ""
|
||||||
|
bizdocs_api_key: str = ""
|
||||||
|
bizdocs_entity_id: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionTestResult(BaseModel):
|
||||||
|
imap_ok: bool = True
|
||||||
|
imap_error: str | None = None
|
||||||
|
webdav_ok: bool = True
|
||||||
|
webdav_error: str | None = None
|
||||||
|
smtp_ok: bool
|
||||||
|
smtp_error: str | None = None
|
||||||
|
bizdocs_ok: bool = True
|
||||||
|
bizdocs_error: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/test", response_model=ConnectionTestResult)
|
||||||
|
def test_connection(
|
||||||
|
payload: ConnectionTestPayload,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> ConnectionTestResult:
|
||||||
|
imap_cfg = ImapConfig(
|
||||||
|
host=payload.imap_host,
|
||||||
|
port=payload.imap_port,
|
||||||
|
user=payload.imap_user,
|
||||||
|
password=payload.imap_password,
|
||||||
|
)
|
||||||
|
smtp_cfg = SmtpConfig(
|
||||||
|
host=payload.smtp_host,
|
||||||
|
port=payload.smtp_port,
|
||||||
|
user=payload.smtp_user,
|
||||||
|
password=payload.smtp_password,
|
||||||
|
)
|
||||||
|
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as executor:
|
||||||
|
imap_future = executor.submit(test_imap_connection, imap_cfg)
|
||||||
|
smtp_future = executor.submit(test_smtp_connection, smtp_cfg)
|
||||||
|
imap_ok, imap_msg = imap_future.result()
|
||||||
|
smtp_ok, smtp_msg = smtp_future.result()
|
||||||
|
|
||||||
|
return ConnectionTestResult(
|
||||||
|
imap_ok=imap_ok,
|
||||||
|
imap_error=None if imap_ok else imap_msg,
|
||||||
|
smtp_ok=smtp_ok,
|
||||||
|
smtp_error=None if smtp_ok else smtp_msg,
|
||||||
|
bizdocs_ok=True,
|
||||||
|
bizdocs_error=None,
|
||||||
|
)
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from forwarder import __version__
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health", response_model=dict)
|
||||||
|
def health() -> dict:
|
||||||
|
import os
|
||||||
|
|
||||||
|
return {
|
||||||
|
"status": "ok",
|
||||||
|
"version": __version__,
|
||||||
|
"git_sha": os.getenv("FORWARDER_GIT_SHA", "unknown"),
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, Query
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
|
from forwarder.api.deps import CurrentUser, DbSession
|
||||||
|
from forwarder.api.schemas import MessageListResponse, MessageResponse
|
||||||
|
from forwarder.db.models import Account, Message, MessageStatus
|
||||||
|
from forwarder.services.message_search import build_message_search_filter
|
||||||
|
from forwarder.services.forward_queue_service import (
|
||||||
|
get_queue_status,
|
||||||
|
process_forward_queue,
|
||||||
|
requeue_forwarded_messages,
|
||||||
|
)
|
||||||
|
from forwarder.email.parsing import parse_email_datetime
|
||||||
|
from forwarder.services.sync_service import (
|
||||||
|
MessageMissingFromMailboxError,
|
||||||
|
retry_single_message,
|
||||||
|
)
|
||||||
|
from forwarder.services.rate_limit import ForwardRateLimitError
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/messages", tags=["messages"])
|
||||||
|
|
||||||
|
|
||||||
|
def _build_message_response(m: Message, account_name: str) -> MessageResponse:
|
||||||
|
forwarded_at = None
|
||||||
|
if m.forward_attempts:
|
||||||
|
success_attempts = [a for a in m.forward_attempts if a.success]
|
||||||
|
if success_attempts:
|
||||||
|
forwarded_at = max(a.created_at for a in success_attempts)
|
||||||
|
|
||||||
|
email_dt = parse_email_datetime(m.date)
|
||||||
|
received_at = email_dt if email_dt is not None else m.created_at
|
||||||
|
|
||||||
|
return MessageResponse(
|
||||||
|
id=m.id,
|
||||||
|
account_id=m.account_id,
|
||||||
|
account_name=account_name,
|
||||||
|
message_uid=m.message_key,
|
||||||
|
subject=m.subject,
|
||||||
|
sender=m.from_addr,
|
||||||
|
received_at=received_at,
|
||||||
|
status=m.status.value,
|
||||||
|
error=m.error_message,
|
||||||
|
forwarded_at=forwarded_at,
|
||||||
|
message_key=m.message_key,
|
||||||
|
folder=m.folder,
|
||||||
|
uid=m.uid,
|
||||||
|
from_addr=m.from_addr,
|
||||||
|
date=m.date,
|
||||||
|
error_message=m.error_message,
|
||||||
|
created_at=m.created_at,
|
||||||
|
updated_at=m.updated_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=MessageListResponse)
|
||||||
|
def list_messages(
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
account_id: int | None = Query(default=None),
|
||||||
|
status: str | None = Query(default=None),
|
||||||
|
q: str | None = Query(default=None, min_length=1, max_length=200),
|
||||||
|
limit: int = Query(default=50, ge=1, le=500),
|
||||||
|
offset: int = Query(default=0, ge=0),
|
||||||
|
) -> MessageListResponse:
|
||||||
|
status_enum: MessageStatus | None = None
|
||||||
|
if status is not None:
|
||||||
|
try:
|
||||||
|
status_enum = MessageStatus(status)
|
||||||
|
except ValueError:
|
||||||
|
return MessageListResponse(items=[], total=0, limit=limit, offset=offset)
|
||||||
|
|
||||||
|
filters = []
|
||||||
|
if account_id is not None:
|
||||||
|
filters.append(Message.account_id == account_id)
|
||||||
|
if status_enum is not None:
|
||||||
|
filters.append(Message.status == status_enum)
|
||||||
|
search_filter = build_message_search_filter(q)
|
||||||
|
if search_filter is not None:
|
||||||
|
filters.append(search_filter)
|
||||||
|
|
||||||
|
total = db.query(func.count(Message.id)).filter(*filters).scalar() or 0
|
||||||
|
|
||||||
|
rows = (
|
||||||
|
db.query(Message, Account.name)
|
||||||
|
.join(Account, Message.account_id == Account.id)
|
||||||
|
.filter(*filters)
|
||||||
|
.order_by(Message.id.desc())
|
||||||
|
.offset(offset)
|
||||||
|
.limit(limit)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
return MessageListResponse(
|
||||||
|
items=[_build_message_response(m, name) for m, name in rows],
|
||||||
|
total=total,
|
||||||
|
limit=limit,
|
||||||
|
offset=offset,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/queue/status")
|
||||||
|
def queue_status(db: DbSession, _user: CurrentUser) -> dict:
|
||||||
|
return get_queue_status(db)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/queue/process")
|
||||||
|
def queue_process(db: DbSession, _user: CurrentUser) -> dict:
|
||||||
|
"""Process one forward-queue tick (same as the worker job)."""
|
||||||
|
return process_forward_queue(db).as_dict()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/requeue-forwarded")
|
||||||
|
def requeue_forwarded(db: DbSession, _user: CurrentUser) -> dict:
|
||||||
|
"""Mark all forwarded messages as failed for gradual queue resend."""
|
||||||
|
count = requeue_forwarded_messages(db)
|
||||||
|
status = get_queue_status(db)
|
||||||
|
return {"requeued": count, **status}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/retry-batch")
|
||||||
|
def retry_batch(
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
limit: int = Query(default=5, ge=1, le=100),
|
||||||
|
account_id: int | None = Query(default=None),
|
||||||
|
all_failed: bool = Query(default=False, alias="all"),
|
||||||
|
) -> dict:
|
||||||
|
"""Retry failed messages via the forward queue (never bulk SMTP).
|
||||||
|
|
||||||
|
Use all=true to confirm all failed messages are queued for the worker.
|
||||||
|
Otherwise runs one queue tick (max batch_size per minute, hourly cap).
|
||||||
|
"""
|
||||||
|
_ = limit # kept for API compat; queue batch size comes from settings
|
||||||
|
|
||||||
|
if all_failed:
|
||||||
|
status = get_queue_status(db)
|
||||||
|
pending_query = db.query(Message).filter(Message.status == MessageStatus.failed)
|
||||||
|
if account_id is not None:
|
||||||
|
pending_query = pending_query.filter(Message.account_id == account_id)
|
||||||
|
pending = pending_query.count()
|
||||||
|
return {
|
||||||
|
"queued": True,
|
||||||
|
"attempted": 0,
|
||||||
|
"succeeded": 0,
|
||||||
|
"failed": 0,
|
||||||
|
"rate_limited": status["forwards_remaining_this_hour"] == 0,
|
||||||
|
"errors": [],
|
||||||
|
"pending": pending,
|
||||||
|
**status,
|
||||||
|
}
|
||||||
|
|
||||||
|
result = process_forward_queue(db)
|
||||||
|
return {
|
||||||
|
"queued": False,
|
||||||
|
"errors": [],
|
||||||
|
**result.as_dict(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{message_id}/retry", response_model=MessageResponse)
|
||||||
|
def retry_message(
|
||||||
|
message_id: int,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> MessageResponse:
|
||||||
|
message = db.get(Message, message_id)
|
||||||
|
if message is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Message not found")
|
||||||
|
if message.status == MessageStatus.forwarded:
|
||||||
|
raise HTTPException(status_code=409, detail="Message already forwarded")
|
||||||
|
|
||||||
|
account = db.get(Account, message.account_id)
|
||||||
|
if account is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Account not found")
|
||||||
|
|
||||||
|
if message.status == MessageStatus.missing_from_mailbox:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=410,
|
||||||
|
detail=message.error_message or "Message no longer in mailbox",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
updated = retry_single_message(db, message_id)
|
||||||
|
except MessageMissingFromMailboxError as exc:
|
||||||
|
raise HTTPException(status_code=410, detail=str(exc)) from exc
|
||||||
|
except ForwardRateLimitError as exc:
|
||||||
|
raise HTTPException(status_code=429, detail=str(exc)) from exc
|
||||||
|
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 _build_message_response(updated, account.name)
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
|
||||||
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
|
||||||
|
from forwarder.api.deps import CurrentUser, DbSession
|
||||||
|
from forwarder.api.schemas import (
|
||||||
|
ConnectionTestResponse,
|
||||||
|
ShopAccountCreate,
|
||||||
|
ShopAccountResponse,
|
||||||
|
ShopAccountUpdate,
|
||||||
|
ShopScrapeRunResponse,
|
||||||
|
)
|
||||||
|
from forwarder.bizdocs import BizdocsClient, BizdocsCredentials
|
||||||
|
from forwarder.bizdocs.errors import BizdocsError
|
||||||
|
from forwarder.crypto import decrypt_password, encrypt_password
|
||||||
|
from forwarder.db.models import ShopAccount, ShopScrapeRun, ShopType # ShopScrapeRun used in list_scrape_runs
|
||||||
|
from forwarder.services.scraper_service import scrape_shop_account
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/shop-accounts", tags=["shop-accounts"])
|
||||||
|
|
||||||
|
|
||||||
|
def _to_response(account: ShopAccount) -> ShopAccountResponse:
|
||||||
|
return ShopAccountResponse(
|
||||||
|
id=account.id,
|
||||||
|
name=account.name,
|
||||||
|
shop_type=account.shop_type.value,
|
||||||
|
enabled=account.enabled,
|
||||||
|
sync_interval_minutes=account.sync_interval_minutes,
|
||||||
|
shop_email=decrypt_password(account.shop_email_encrypted or "") or None,
|
||||||
|
bizdocs_email=account.bizdocs_email,
|
||||||
|
bizdocs_company_id=account.bizdocs_company_id,
|
||||||
|
bizdocs_api_base_url=account.bizdocs_api_base_url,
|
||||||
|
last_scraped_at=account.last_scraped_at,
|
||||||
|
session_state_saved_at=account.session_state_saved_at,
|
||||||
|
created_at=account.created_at,
|
||||||
|
updated_at=account.updated_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_or_404(db: DbSession, account_id: int) -> ShopAccount:
|
||||||
|
account = db.get(ShopAccount, account_id)
|
||||||
|
if account is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Shop account not found")
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[ShopAccountResponse])
|
||||||
|
def list_shop_accounts(db: DbSession, _user: CurrentUser) -> list[ShopAccountResponse]:
|
||||||
|
accounts = db.query(ShopAccount).order_by(ShopAccount.id).all()
|
||||||
|
return [_to_response(a) for a in accounts]
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=ShopAccountResponse, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_shop_account(
|
||||||
|
body: ShopAccountCreate,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> ShopAccountResponse:
|
||||||
|
try:
|
||||||
|
shop_type = ShopType(body.shop_type)
|
||||||
|
except ValueError:
|
||||||
|
raise HTTPException(status_code=400, detail=f"Invalid shop_type: {body.shop_type!r}")
|
||||||
|
|
||||||
|
account = ShopAccount(
|
||||||
|
name=body.name,
|
||||||
|
shop_type=shop_type,
|
||||||
|
enabled=body.enabled,
|
||||||
|
sync_interval_minutes=body.sync_interval_minutes,
|
||||||
|
shop_email_encrypted=encrypt_password(body.shop_email or ""),
|
||||||
|
shop_password_encrypted=encrypt_password(body.shop_password or ""),
|
||||||
|
bizdocs_email=body.bizdocs_email,
|
||||||
|
bizdocs_password_encrypted=encrypt_password(body.bizdocs_password or ""),
|
||||||
|
bizdocs_company_id=body.bizdocs_company_id,
|
||||||
|
bizdocs_api_base_url=body.bizdocs_api_base_url,
|
||||||
|
)
|
||||||
|
db.add(account)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(account)
|
||||||
|
return _to_response(account)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{account_id}", response_model=ShopAccountResponse)
|
||||||
|
def get_shop_account(account_id: int, db: DbSession, _user: CurrentUser) -> ShopAccountResponse:
|
||||||
|
return _to_response(_get_or_404(db, account_id))
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{account_id}", response_model=ShopAccountResponse)
|
||||||
|
def update_shop_account(
|
||||||
|
account_id: int,
|
||||||
|
body: ShopAccountUpdate,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> ShopAccountResponse:
|
||||||
|
account = _get_or_404(db, account_id)
|
||||||
|
data = body.model_dump(exclude_unset=True)
|
||||||
|
|
||||||
|
if "name" in data:
|
||||||
|
account.name = data["name"]
|
||||||
|
if "enabled" in data:
|
||||||
|
account.enabled = data["enabled"]
|
||||||
|
if "sync_interval_minutes" in data:
|
||||||
|
account.sync_interval_minutes = data["sync_interval_minutes"]
|
||||||
|
if "shop_email" in data:
|
||||||
|
account.shop_email_encrypted = encrypt_password(data["shop_email"] or "")
|
||||||
|
if "shop_password" in data:
|
||||||
|
account.shop_password_encrypted = encrypt_password(data["shop_password"] or "")
|
||||||
|
if "bizdocs_email" in data:
|
||||||
|
account.bizdocs_email = data["bizdocs_email"]
|
||||||
|
if "bizdocs_password" in data:
|
||||||
|
account.bizdocs_password_encrypted = encrypt_password(data["bizdocs_password"] or "")
|
||||||
|
if "bizdocs_company_id" in data:
|
||||||
|
account.bizdocs_company_id = data["bizdocs_company_id"]
|
||||||
|
if "bizdocs_api_base_url" in data:
|
||||||
|
account.bizdocs_api_base_url = data["bizdocs_api_base_url"]
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(account)
|
||||||
|
return _to_response(account)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{account_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
def delete_shop_account(account_id: int, db: DbSession, _user: CurrentUser) -> None:
|
||||||
|
account = _get_or_404(db, account_id)
|
||||||
|
db.delete(account)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{account_id}/test", response_model=ConnectionTestResponse)
|
||||||
|
def test_shop_account(account_id: int, db: DbSession, _user: CurrentUser) -> ConnectionTestResponse:
|
||||||
|
"""Test BizDocs credentials for this shop account."""
|
||||||
|
account = _get_or_404(db, account_id)
|
||||||
|
bizdocs_password = decrypt_password(account.bizdocs_password_encrypted or "")
|
||||||
|
credentials = BizdocsCredentials(
|
||||||
|
email=account.bizdocs_email or "",
|
||||||
|
password=bizdocs_password,
|
||||||
|
company_id=account.bizdocs_company_id or "",
|
||||||
|
api_base_url=account.bizdocs_api_base_url,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
success, message = BizdocsClient().test_connection(credentials)
|
||||||
|
except BizdocsError as exc:
|
||||||
|
success, message = False, str(exc)
|
||||||
|
return ConnectionTestResponse(success=success, message=message)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/{account_id}/trigger", status_code=status.HTTP_202_ACCEPTED)
|
||||||
|
def trigger_scrape(account_id: int, db: DbSession, _user: CurrentUser) -> dict:
|
||||||
|
"""Trigger an immediate scrape for this shop account (runs in background thread)."""
|
||||||
|
account = _get_or_404(db, account_id)
|
||||||
|
if not account.enabled:
|
||||||
|
raise HTTPException(status_code=400, detail="Shop account is disabled")
|
||||||
|
|
||||||
|
def _bg() -> None:
|
||||||
|
from forwarder.db.session import get_session_factory
|
||||||
|
bg_db = get_session_factory()()
|
||||||
|
try:
|
||||||
|
scrape_shop_account(bg_db, account_id)
|
||||||
|
finally:
|
||||||
|
bg_db.close()
|
||||||
|
|
||||||
|
threading.Thread(target=_bg, daemon=True).start()
|
||||||
|
return {"detail": "Scrape triggered", "shop_account_id": account_id}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{account_id}/runs", response_model=list[ShopScrapeRunResponse])
|
||||||
|
def list_scrape_runs(
|
||||||
|
account_id: int,
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
) -> list[ShopScrapeRunResponse]:
|
||||||
|
_get_or_404(db, account_id)
|
||||||
|
runs = (
|
||||||
|
db.query(ShopScrapeRun)
|
||||||
|
.filter(ShopScrapeRun.shop_account_id == account_id)
|
||||||
|
.order_by(ShopScrapeRun.id.desc())
|
||||||
|
.limit(50)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
ShopScrapeRunResponse(
|
||||||
|
id=r.id,
|
||||||
|
shop_account_id=r.shop_account_id,
|
||||||
|
status=r.status.value,
|
||||||
|
orders_found=r.orders_found,
|
||||||
|
invoices_uploaded=r.invoices_uploaded,
|
||||||
|
invoices_skipped=r.invoices_skipped,
|
||||||
|
invoices_failed=r.invoices_failed,
|
||||||
|
error_message=r.error_message,
|
||||||
|
started_at=r.started_at,
|
||||||
|
finished_at=r.finished_at,
|
||||||
|
)
|
||||||
|
for r in runs
|
||||||
|
]
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
|
from forwarder.api.deps import CurrentUser, DbSession
|
||||||
|
from forwarder.db.models import Account, Message, MessageStatus, SyncRun
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/stats", tags=["stats"])
|
||||||
|
|
||||||
|
|
||||||
|
class StatsResponse(BaseModel):
|
||||||
|
accounts_total: int
|
||||||
|
accounts_active: int
|
||||||
|
messages_total: int
|
||||||
|
messages_pending: int
|
||||||
|
messages_forwarded: int
|
||||||
|
messages_failed: int
|
||||||
|
messages_missing_from_mailbox: int
|
||||||
|
last_sync_at: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=StatsResponse)
|
||||||
|
def get_stats(db: DbSession, _user: CurrentUser) -> StatsResponse:
|
||||||
|
accounts_total = db.query(func.count(Account.id)).scalar() or 0
|
||||||
|
accounts_active = (
|
||||||
|
db.query(func.count(Account.id)).filter(Account.enabled.is_(True)).scalar() or 0
|
||||||
|
)
|
||||||
|
messages_total = db.query(func.count(Message.id)).scalar() or 0
|
||||||
|
messages_pending = (
|
||||||
|
db.query(func.count(Message.id))
|
||||||
|
.filter(Message.status == MessageStatus.pending)
|
||||||
|
.scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
messages_forwarded = (
|
||||||
|
db.query(func.count(Message.id))
|
||||||
|
.filter(Message.status == MessageStatus.forwarded)
|
||||||
|
.scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
messages_failed = (
|
||||||
|
db.query(func.count(Message.id))
|
||||||
|
.filter(Message.status == MessageStatus.failed)
|
||||||
|
.scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
messages_missing_from_mailbox = (
|
||||||
|
db.query(func.count(Message.id))
|
||||||
|
.filter(Message.status == MessageStatus.missing_from_mailbox)
|
||||||
|
.scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
last_run = db.query(SyncRun.started_at).order_by(SyncRun.id.desc()).first()
|
||||||
|
last_sync_at = last_run[0] if last_run else None
|
||||||
|
|
||||||
|
return StatsResponse(
|
||||||
|
accounts_total=accounts_total,
|
||||||
|
accounts_active=accounts_active,
|
||||||
|
messages_total=messages_total,
|
||||||
|
messages_pending=messages_pending,
|
||||||
|
messages_forwarded=messages_forwarded,
|
||||||
|
messages_failed=messages_failed,
|
||||||
|
messages_missing_from_mailbox=messages_missing_from_mailbox,
|
||||||
|
last_sync_at=last_sync_at,
|
||||||
|
)
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Query
|
||||||
|
|
||||||
|
from forwarder.api.deps import CurrentUser, DbSession
|
||||||
|
from forwarder.api.schemas import SyncRunResponse
|
||||||
|
from forwarder.db.models import SyncRun
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/sync-runs", tags=["sync-runs"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=list[SyncRunResponse])
|
||||||
|
def list_sync_runs(
|
||||||
|
db: DbSession,
|
||||||
|
_user: CurrentUser,
|
||||||
|
account_id: int | None = Query(default=None),
|
||||||
|
limit: int = Query(default=50, ge=1, le=200),
|
||||||
|
offset: int = Query(default=0, ge=0),
|
||||||
|
) -> list[SyncRunResponse]:
|
||||||
|
query = db.query(SyncRun).order_by(SyncRun.id.desc())
|
||||||
|
|
||||||
|
if account_id is not None:
|
||||||
|
query = query.filter(SyncRun.account_id == account_id)
|
||||||
|
|
||||||
|
rows = query.offset(offset).limit(limit).all()
|
||||||
|
return [
|
||||||
|
SyncRunResponse(
|
||||||
|
id=r.id,
|
||||||
|
account_id=r.account_id,
|
||||||
|
status=r.status.value,
|
||||||
|
dry_run=r.dry_run,
|
||||||
|
max_emails=r.max_emails,
|
||||||
|
messages_scanned=r.messages_scanned,
|
||||||
|
messages_matched=r.messages_matched,
|
||||||
|
messages_forwarded=r.messages_forwarded,
|
||||||
|
messages_skipped=r.messages_skipped,
|
||||||
|
messages_failed=r.messages_failed,
|
||||||
|
error_message=r.error_message,
|
||||||
|
started_at=r.started_at,
|
||||||
|
finished_at=r.finished_at,
|
||||||
|
)
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator
|
||||||
|
|
||||||
|
DEFAULT_BIZDOCS_DESTINATION = "[email protected]"
|
||||||
|
DEFAULT_ALLOWED_EXTENSIONS = [".pdf", ".xml", ".zip", ".png", ".jpg", ".jpeg"]
|
||||||
|
|
||||||
|
|
||||||
|
class AccountBase(BaseModel):
|
||||||
|
name: str
|
||||||
|
enabled: bool = True
|
||||||
|
sync_interval_minutes: int = 15
|
||||||
|
source_type: str = "imap"
|
||||||
|
imap_host: str | None = None
|
||||||
|
imap_port: int = 993
|
||||||
|
imap_user: str | None = None
|
||||||
|
webdav_url: str | None = None
|
||||||
|
webdav_path: str | None = None
|
||||||
|
webdav_user: str | None = None
|
||||||
|
webdav_verify_ssl: bool = True
|
||||||
|
webdav_min_year: int | None = None
|
||||||
|
delivery_mode: str = "smtp"
|
||||||
|
smtp_host: str | None = None
|
||||||
|
smtp_port: int = 587
|
||||||
|
smtp_user: str | None = None
|
||||||
|
smtp_use_tls: bool = True
|
||||||
|
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
|
||||||
|
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):
|
||||||
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
imap_password: str | None = None
|
||||||
|
webdav_password: str | None = None
|
||||||
|
smtp_password: str | None = None
|
||||||
|
bizdocs_password: str | None = None
|
||||||
|
# UI compat fields — ignored but accepted without validation error
|
||||||
|
active: bool | None = None
|
||||||
|
email: str | None = None
|
||||||
|
bizdocs_api_key: str | None = None
|
||||||
|
bizdocs_entity_id: str | None = None
|
||||||
|
|
||||||
|
@model_validator(mode="before")
|
||||||
|
@classmethod
|
||||||
|
def _apply_ui_compat_defaults(cls, data: object) -> object:
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return data
|
||||||
|
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
|
||||||
|
if not data.get("bizdocs_email") and data.get("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"):
|
||||||
|
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
|
||||||
|
|
||||||
|
@model_validator(mode="after")
|
||||||
|
def _validate_account(self) -> AccountCreate:
|
||||||
|
if self.active is not None:
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class AccountUpdate(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
name: str | None = None
|
||||||
|
enabled: bool | None = None
|
||||||
|
sync_interval_minutes: int | None = None
|
||||||
|
source_type: str | None = None
|
||||||
|
imap_host: str | None = None
|
||||||
|
imap_port: int | None = None
|
||||||
|
imap_user: 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
|
||||||
|
webdav_min_year: int | None = None
|
||||||
|
smtp_host: str | None = None
|
||||||
|
smtp_port: int | None = None
|
||||||
|
smtp_user: str | None = None
|
||||||
|
smtp_password: str | None = None
|
||||||
|
smtp_use_tls: bool | None = None
|
||||||
|
delivery_mode: 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
|
||||||
|
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")
|
||||||
|
def _sync_active(self) -> AccountUpdate:
|
||||||
|
if self.active is not None and self.enabled is None:
|
||||||
|
self.enabled = self.active
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
class AccountResponse(AccountBase):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
imap_password: str = "********"
|
||||||
|
webdav_password: str = "********"
|
||||||
|
smtp_password: str = "********"
|
||||||
|
bizdocs_password: str = "********"
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
# UI compat stubs
|
||||||
|
bizdocs_api_key: str = ""
|
||||||
|
|
||||||
|
@computed_field # type: ignore[misc]
|
||||||
|
@property
|
||||||
|
def active(self) -> bool:
|
||||||
|
return self.enabled
|
||||||
|
|
||||||
|
@computed_field # type: ignore[misc]
|
||||||
|
@property
|
||||||
|
def email(self) -> str:
|
||||||
|
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):
|
||||||
|
source_type: str | None = None
|
||||||
|
imap_host: str | None = None
|
||||||
|
imap_port: int | None = None
|
||||||
|
imap_user: 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_port: int | None = None
|
||||||
|
smtp_user: str | None = None
|
||||||
|
smtp_password: str | None = None
|
||||||
|
smtp_use_tls: bool | 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
|
||||||
|
imap_folder_selection_mode: str | None = None
|
||||||
|
imap_selected_folders: list[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionTestResponse(BaseModel):
|
||||||
|
success: bool
|
||||||
|
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
|
||||||
|
account_name: str
|
||||||
|
message_uid: str
|
||||||
|
subject: str
|
||||||
|
sender: str
|
||||||
|
received_at: datetime
|
||||||
|
status: str
|
||||||
|
error: str | None = None
|
||||||
|
forwarded_at: datetime | None = None
|
||||||
|
# Keep original fields for other consumers
|
||||||
|
message_key: str
|
||||||
|
folder: str
|
||||||
|
uid: str
|
||||||
|
from_addr: str
|
||||||
|
date: str
|
||||||
|
error_message: str | None = None
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class MessageListResponse(BaseModel):
|
||||||
|
items: list[MessageResponse]
|
||||||
|
total: int
|
||||||
|
limit: int
|
||||||
|
offset: int
|
||||||
|
|
||||||
|
|
||||||
|
class SyncRunResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
account_id: int
|
||||||
|
status: str
|
||||||
|
dry_run: bool
|
||||||
|
max_emails: int | None = None
|
||||||
|
messages_scanned: int
|
||||||
|
messages_matched: int
|
||||||
|
messages_forwarded: int
|
||||||
|
messages_skipped: int
|
||||||
|
messages_failed: int
|
||||||
|
error_message: str | None = None
|
||||||
|
started_at: datetime
|
||||||
|
finished_at: datetime | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class HealthResponse(BaseModel):
|
||||||
|
status: str
|
||||||
|
version: str
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorResponse(BaseModel):
|
||||||
|
detail: str
|
||||||
|
|
||||||
|
|
||||||
|
# ── Shop accounts (scraper) ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|
||||||
|
class ShopAccountCreate(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
name: str
|
||||||
|
shop_type: str # "amazon" | "temu"
|
||||||
|
enabled: bool = True
|
||||||
|
sync_interval_minutes: int = 60
|
||||||
|
shop_email: str | None = None
|
||||||
|
shop_password: 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 ShopAccountUpdate(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
name: str | None = None
|
||||||
|
enabled: bool | None = None
|
||||||
|
sync_interval_minutes: int | None = None
|
||||||
|
shop_email: str | None = None
|
||||||
|
shop_password: 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 ShopAccountResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
name: str
|
||||||
|
shop_type: str
|
||||||
|
enabled: bool
|
||||||
|
sync_interval_minutes: int
|
||||||
|
shop_email: str | None
|
||||||
|
bizdocs_email: str | None
|
||||||
|
bizdocs_company_id: str | None
|
||||||
|
bizdocs_api_base_url: str | None
|
||||||
|
last_scraped_at: datetime | None
|
||||||
|
session_state_saved_at: datetime | None
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class ShopScrapeRunResponse(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
shop_account_id: int
|
||||||
|
status: str
|
||||||
|
orders_found: int
|
||||||
|
invoices_uploaded: int
|
||||||
|
invoices_skipped: int
|
||||||
|
invoices_failed: int
|
||||||
|
error_message: str | None
|
||||||
|
started_at: datetime
|
||||||
|
finished_at: datetime | None
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""BizDocs mobile API client."""
|
||||||
|
|
||||||
|
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials, BizdocsSession
|
||||||
|
|
||||||
|
__all__ = ["BizdocsClient", "BizdocsCredentials", "BizdocsSession"]
|
||||||
@@ -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}")
|
||||||
@@ -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."""
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
from forwarder.error_reporter import report_error
|
||||||
|
from forwarder.services.auth_service import ensure_admin_user
|
||||||
|
from forwarder.worker.scheduler import run_worker
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(prog="forwarder", description="BizDocs Forwarder CLI")
|
||||||
|
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||||
|
|
||||||
|
worker_parser = subparsers.add_parser("worker", help="Run APScheduler sync worker")
|
||||||
|
worker_parser.add_argument(
|
||||||
|
"--interval",
|
||||||
|
type=int,
|
||||||
|
default=None,
|
||||||
|
help="Override default sync interval (minutes) for accounts without custom value",
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if args.command == "worker":
|
||||||
|
ensure_admin_user()
|
||||||
|
settings = get_settings()
|
||||||
|
default_interval = args.interval or settings.sync_interval_minutes
|
||||||
|
logging.getLogger(__name__).info(
|
||||||
|
"Starting worker (default interval: %s min)", default_interval
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
run_worker(default_interval=default_interval)
|
||||||
|
except Exception as exc:
|
||||||
|
report_error(exc, severity="critical", endpoint="cli:worker")
|
||||||
|
raise
|
||||||
|
return
|
||||||
|
|
||||||
|
parser.print_help()
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env",
|
||||||
|
env_file_encoding="utf-8",
|
||||||
|
extra="ignore",
|
||||||
|
)
|
||||||
|
|
||||||
|
database_url: str = "mysql+pymysql://forwarder:forwarder@localhost:3306/forwarder"
|
||||||
|
encryption_key: str = ""
|
||||||
|
app_secret: str = "change-me"
|
||||||
|
admin_username: str = "admin"
|
||||||
|
admin_password: str = "change-me"
|
||||||
|
sync_interval_minutes: int = 15
|
||||||
|
max_forwards_per_hour: int = 400
|
||||||
|
forward_queue_batch_size: int = 5
|
||||||
|
forward_queue_interval_seconds: int = 60
|
||||||
|
api_host: str = "0.0.0.0"
|
||||||
|
api_port: int = 8000
|
||||||
|
|
||||||
|
error_reporting_enabled: bool = True
|
||||||
|
error_reporting_token: str = ""
|
||||||
|
error_reporting_endpoint: str = "https://errors.bitreport.pt"
|
||||||
|
error_monitoring_project_name: str = "BizDocs Forwarder"
|
||||||
|
error_monitoring_project_slug: str = "bizdocs-forwarder"
|
||||||
|
error_monitoring_gitea_repo: str = "BitReport.pt/forwarder"
|
||||||
|
error_monitoring_paperclip_project_id: str = ""
|
||||||
|
error_monitoring_env: str = "production"
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return Settings()
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet, InvalidToken
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
|
||||||
|
|
||||||
|
class EncryptionError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def get_fernet() -> Fernet:
|
||||||
|
key = get_settings().encryption_key.strip()
|
||||||
|
if not key:
|
||||||
|
raise EncryptionError("ENCRYPTION_KEY is not configured")
|
||||||
|
try:
|
||||||
|
return Fernet(key.encode() if isinstance(key, str) else key)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise EncryptionError(
|
||||||
|
"ENCRYPTION_KEY must be 32 url-safe base64-encoded bytes"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_password(plain: str) -> str:
|
||||||
|
if not plain:
|
||||||
|
return ""
|
||||||
|
return get_fernet().encrypt(plain.encode()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_password(token: str) -> str:
|
||||||
|
if not token:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
return get_fernet().decrypt(token.encode()).decode()
|
||||||
|
except InvalidToken as exc:
|
||||||
|
raise EncryptionError("Failed to decrypt password") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def mask_password(_plain: str | None = None) -> str:
|
||||||
|
return "********"
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
from forwarder.db.base import Base
|
||||||
|
from forwarder.db.models import (
|
||||||
|
Account,
|
||||||
|
ConnectionTest,
|
||||||
|
ForwardAttempt,
|
||||||
|
Message,
|
||||||
|
ScrapedDocument,
|
||||||
|
ScrapedDocumentStatus,
|
||||||
|
ShopAccount,
|
||||||
|
ShopScrapeRun,
|
||||||
|
ShopScrapeRunStatus,
|
||||||
|
ShopType,
|
||||||
|
SyncRun,
|
||||||
|
User,
|
||||||
|
UserAccount,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Base",
|
||||||
|
"Account",
|
||||||
|
"ConnectionTest",
|
||||||
|
"ForwardAttempt",
|
||||||
|
"Message",
|
||||||
|
"ScrapedDocument",
|
||||||
|
"ScrapedDocumentStatus",
|
||||||
|
"ShopAccount",
|
||||||
|
"ShopScrapeRun",
|
||||||
|
"ShopScrapeRunStatus",
|
||||||
|
"ShopType",
|
||||||
|
"SyncRun",
|
||||||
|
"User",
|
||||||
|
"UserAccount",
|
||||||
|
]
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
@@ -0,0 +1,376 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import enum
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import (
|
||||||
|
JSON,
|
||||||
|
Boolean,
|
||||||
|
DateTime,
|
||||||
|
Enum,
|
||||||
|
ForeignKey,
|
||||||
|
Integer,
|
||||||
|
String,
|
||||||
|
Text,
|
||||||
|
UniqueConstraint,
|
||||||
|
func,
|
||||||
|
)
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
|
from forwarder.db.base import Base
|
||||||
|
|
||||||
|
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):
|
||||||
|
pending = "pending"
|
||||||
|
forwarded = "forwarded"
|
||||||
|
failed = "failed"
|
||||||
|
skipped = "skipped"
|
||||||
|
dry_run = "dry_run"
|
||||||
|
missing_from_mailbox = "missing_from_mailbox"
|
||||||
|
|
||||||
|
|
||||||
|
class SyncRunStatus(str, enum.Enum):
|
||||||
|
running = "running"
|
||||||
|
completed = "completed"
|
||||||
|
failed = "failed"
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionTestType(str, enum.Enum):
|
||||||
|
imap = "imap"
|
||||||
|
smtp = "smtp"
|
||||||
|
send = "send"
|
||||||
|
webdav = "webdav"
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
username: Mapped[str] = mapped_column(String(128), unique=True, nullable=False)
|
||||||
|
password_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
is_admin: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
|
||||||
|
user_accounts: Mapped[list[UserAccount]] = relationship(
|
||||||
|
back_populates="user", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Account(Base):
|
||||||
|
__tablename__ = "accounts"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
sync_interval_minutes: Mapped[int] = mapped_column(Integer, default=15, nullable=False)
|
||||||
|
|
||||||
|
source_type: Mapped[SourceType] = mapped_column(
|
||||||
|
Enum(SourceType), default=SourceType.imap, 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)
|
||||||
|
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)
|
||||||
|
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)
|
||||||
|
webdav_min_year: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
|
||||||
|
smtp_host: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||||
|
smtp_port: Mapped[int] = mapped_column(Integer, default=587, nullable=False)
|
||||||
|
smtp_user: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||||
|
smtp_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
smtp_use_tls: Mapped[bool] = mapped_column(Boolean, default=True, 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(
|
||||||
|
Boolean, default=False, nullable=False
|
||||||
|
)
|
||||||
|
allowed_extensions: Mapped[list[Any]] = mapped_column(
|
||||||
|
JSON, default=list, nullable=False
|
||||||
|
)
|
||||||
|
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True),
|
||||||
|
server_default=func.now(),
|
||||||
|
onupdate=func.now(),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
messages: Mapped[list[Message]] = relationship(
|
||||||
|
back_populates="account", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
sync_runs: Mapped[list[SyncRun]] = relationship(
|
||||||
|
back_populates="account", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
user_accounts: Mapped[list[UserAccount]] = relationship(
|
||||||
|
back_populates="account", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UserAccount(Base):
|
||||||
|
__tablename__ = "user_accounts"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||||
|
account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False)
|
||||||
|
|
||||||
|
user: Mapped[User] = relationship(back_populates="user_accounts")
|
||||||
|
account: Mapped[Account] = relationship(back_populates="user_accounts")
|
||||||
|
|
||||||
|
|
||||||
|
class Message(Base):
|
||||||
|
__tablename__ = "messages"
|
||||||
|
__table_args__ = (UniqueConstraint("account_id", "message_key", name="uq_account_message_key"),)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False, index=True)
|
||||||
|
message_key: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||||
|
folder: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||||
|
uid: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||||
|
subject: Mapped[str] = mapped_column(String(1024), default="", nullable=False)
|
||||||
|
from_addr: Mapped[str] = mapped_column(String(512), default="", nullable=False)
|
||||||
|
date: Mapped[str] = mapped_column(String(128), default="", nullable=False)
|
||||||
|
status: Mapped[MessageStatus] = mapped_column(
|
||||||
|
Enum(MessageStatus), default=MessageStatus.pending, nullable=False, index=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(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True),
|
||||||
|
server_default=func.now(),
|
||||||
|
onupdate=func.now(),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
account: Mapped[Account] = relationship(back_populates="messages")
|
||||||
|
forward_attempts: Mapped[list[ForwardAttempt]] = relationship(
|
||||||
|
back_populates="message", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ForwardAttempt(Base):
|
||||||
|
__tablename__ = "forward_attempts"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
message_id: Mapped[int] = mapped_column(ForeignKey("messages.id"), nullable=False, index=True)
|
||||||
|
success: Mapped[bool] = mapped_column(Boolean, nullable=False)
|
||||||
|
dry_run: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
|
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
|
||||||
|
message: Mapped[Message] = relationship(back_populates="forward_attempts")
|
||||||
|
|
||||||
|
|
||||||
|
class SyncRun(Base):
|
||||||
|
__tablename__ = "sync_runs"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id"), nullable=False, index=True)
|
||||||
|
status: Mapped[SyncRunStatus] = mapped_column(
|
||||||
|
Enum(SyncRunStatus), default=SyncRunStatus.running, nullable=False
|
||||||
|
)
|
||||||
|
dry_run: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||||
|
max_emails: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
messages_scanned: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
messages_matched: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
messages_forwarded: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
messages_skipped: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
messages_failed: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
started_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
|
||||||
|
account: Mapped[Account] = relationship(back_populates="sync_runs")
|
||||||
|
|
||||||
|
|
||||||
|
class ConnectionTest(Base):
|
||||||
|
__tablename__ = "connection_tests"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
account_id: Mapped[int | None] = mapped_column(
|
||||||
|
ForeignKey("accounts.id"), nullable=True, index=True
|
||||||
|
)
|
||||||
|
test_type: Mapped[ConnectionTestType] = mapped_column(
|
||||||
|
Enum(ConnectionTestType), nullable=False
|
||||||
|
)
|
||||||
|
success: Mapped[bool] = mapped_column(Boolean, nullable=False)
|
||||||
|
message: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Shop invoice scrapers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class ShopType(str, enum.Enum):
|
||||||
|
temu = "temu"
|
||||||
|
amazon = "amazon"
|
||||||
|
|
||||||
|
|
||||||
|
class ScrapedDocumentStatus(str, enum.Enum):
|
||||||
|
pending = "pending"
|
||||||
|
uploaded = "uploaded"
|
||||||
|
failed = "failed"
|
||||||
|
skipped = "skipped"
|
||||||
|
|
||||||
|
|
||||||
|
class ShopScrapeRunStatus(str, enum.Enum):
|
||||||
|
running = "running"
|
||||||
|
completed = "completed"
|
||||||
|
failed = "failed"
|
||||||
|
|
||||||
|
|
||||||
|
class ShopAccount(Base):
|
||||||
|
"""Credentials for a shop (Temu, Amazon…) to scrape invoices from."""
|
||||||
|
|
||||||
|
__tablename__ = "shop_accounts"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
shop_type: Mapped[ShopType] = mapped_column(Enum(ShopType), nullable=False)
|
||||||
|
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||||
|
sync_interval_minutes: Mapped[int] = mapped_column(Integer, default=60, nullable=False)
|
||||||
|
|
||||||
|
# Shop credentials (encrypted)
|
||||||
|
shop_email_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
shop_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
# Persisted Playwright browser state (cookies + localStorage), encrypted
|
||||||
|
session_state_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
session_state_saved_at: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=True
|
||||||
|
)
|
||||||
|
|
||||||
|
# BizDocs delivery
|
||||||
|
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)
|
||||||
|
|
||||||
|
last_scraped_at: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=True
|
||||||
|
)
|
||||||
|
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True),
|
||||||
|
server_default=func.now(),
|
||||||
|
onupdate=func.now(),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
scraped_docs: Mapped[list[ScrapedDocument]] = relationship(
|
||||||
|
back_populates="shop_account", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
scrape_runs: Mapped[list[ShopScrapeRun]] = relationship(
|
||||||
|
back_populates="shop_account", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ScrapedDocument(Base):
|
||||||
|
"""One invoice/document scraped from a shop and uploaded to BizDocs."""
|
||||||
|
|
||||||
|
__tablename__ = "scraped_documents"
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("shop_account_id", "order_id", name="uq_shop_account_order"),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
shop_account_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("shop_accounts.id"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
order_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||||
|
filename: Mapped[str] = mapped_column(String(512), default="", nullable=False)
|
||||||
|
status: Mapped[ScrapedDocumentStatus] = mapped_column(
|
||||||
|
Enum(ScrapedDocumentStatus),
|
||||||
|
default=ScrapedDocumentStatus.pending,
|
||||||
|
nullable=False,
|
||||||
|
index=True,
|
||||||
|
)
|
||||||
|
bizdocs_doc_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||||
|
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True),
|
||||||
|
server_default=func.now(),
|
||||||
|
onupdate=func.now(),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
shop_account: Mapped[ShopAccount] = relationship(back_populates="scraped_docs")
|
||||||
|
|
||||||
|
|
||||||
|
class ShopScrapeRun(Base):
|
||||||
|
"""Audit trail for one scraping run against a ShopAccount."""
|
||||||
|
|
||||||
|
__tablename__ = "shop_scrape_runs"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||||
|
shop_account_id: Mapped[int] = mapped_column(
|
||||||
|
ForeignKey("shop_accounts.id"), nullable=False, index=True
|
||||||
|
)
|
||||||
|
status: Mapped[ShopScrapeRunStatus] = mapped_column(
|
||||||
|
Enum(ShopScrapeRunStatus),
|
||||||
|
default=ShopScrapeRunStatus.running,
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
orders_found: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
invoices_uploaded: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
invoices_failed: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
invoices_skipped: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||||
|
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
started_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||||
|
)
|
||||||
|
finished_at: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=True
|
||||||
|
)
|
||||||
|
|
||||||
|
shop_account: Mapped[ShopAccount] = relationship(back_populates="scrape_runs")
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Generator
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
|
||||||
|
_engine = None
|
||||||
|
_SessionLocal = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_engine():
|
||||||
|
global _engine
|
||||||
|
if _engine is None:
|
||||||
|
_engine = create_engine(
|
||||||
|
get_settings().database_url,
|
||||||
|
pool_pre_ping=True,
|
||||||
|
pool_recycle=3600,
|
||||||
|
)
|
||||||
|
return _engine
|
||||||
|
|
||||||
|
|
||||||
|
def get_session_factory() -> sessionmaker[Session]:
|
||||||
|
global _SessionLocal
|
||||||
|
if _SessionLocal is None:
|
||||||
|
_SessionLocal = sessionmaker(
|
||||||
|
bind=get_engine(),
|
||||||
|
autocommit=False,
|
||||||
|
autoflush=False,
|
||||||
|
)
|
||||||
|
return _SessionLocal
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Generator[Session, None, None]:
|
||||||
|
db = get_session_factory()()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
Whitespace-only changes.
@@ -0,0 +1,128 @@
|
|||||||
|
"""IMAP client helpers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import email
|
||||||
|
import imaplib
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from email import policy
|
||||||
|
|
||||||
|
DEFAULT_IMAP_TIMEOUT = 30
|
||||||
|
CONNECTION_TEST_IMAP_TIMEOUT = 5
|
||||||
|
|
||||||
|
SKIP_FOLDERS = [
|
||||||
|
"trash",
|
||||||
|
"junk",
|
||||||
|
"spam",
|
||||||
|
"deleted",
|
||||||
|
"draft",
|
||||||
|
"sent",
|
||||||
|
"enviados",
|
||||||
|
"lixo",
|
||||||
|
"rascunhos",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ImapConfig:
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
user: str
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
def decode_mbox_name(raw_name: bytes | str) -> str:
|
||||||
|
if isinstance(raw_name, bytes):
|
||||||
|
raw_name = raw_name.decode(errors="replace")
|
||||||
|
return raw_name.strip('"')
|
||||||
|
|
||||||
|
|
||||||
|
def should_skip_folder(folder: str) -> bool:
|
||||||
|
lowered = folder.lower()
|
||||||
|
for fragment in SKIP_FOLDERS:
|
||||||
|
if fragment in lowered:
|
||||||
|
return True
|
||||||
|
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:
|
||||||
|
return []
|
||||||
|
|
||||||
|
folders: list[str] = []
|
||||||
|
for box in boxes:
|
||||||
|
if box is None:
|
||||||
|
continue
|
||||||
|
decoded = box.decode(errors="replace") if isinstance(box, bytes) else str(box)
|
||||||
|
match = re.search(r' "/" (.+)$', decoded) or re.search(r' "." (.+)$', decoded)
|
||||||
|
if not match:
|
||||||
|
continue
|
||||||
|
folders.append(decode_mbox_name(match.group(1)))
|
||||||
|
return folders
|
||||||
|
|
||||||
|
|
||||||
|
def select_folder_readonly(imap: imaplib.IMAP4_SSL, folder: str) -> bool:
|
||||||
|
mailbox = f'"{folder}"' if " " in folder else folder
|
||||||
|
status, _ = imap.select(mailbox, readonly=True)
|
||||||
|
return status == "OK"
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_message(
|
||||||
|
imap: imaplib.IMAP4_SSL, uid: bytes
|
||||||
|
) -> email.message.EmailMessage | None:
|
||||||
|
status, msg_data = imap.uid("fetch", uid, "(RFC822)")
|
||||||
|
if status != "OK" or not msg_data or not msg_data[0]:
|
||||||
|
return None
|
||||||
|
raw_email = msg_data[0][1]
|
||||||
|
if not isinstance(raw_email, (bytes, bytearray)):
|
||||||
|
return None
|
||||||
|
return email.message_from_bytes(raw_email, policy=policy.default)
|
||||||
|
|
||||||
|
|
||||||
|
def connect_imap(
|
||||||
|
config: ImapConfig,
|
||||||
|
timeout: float = DEFAULT_IMAP_TIMEOUT,
|
||||||
|
) -> imaplib.IMAP4_SSL:
|
||||||
|
imap = imaplib.IMAP4_SSL(config.host, config.port, timeout=timeout)
|
||||||
|
imap.login(config.user, config.password)
|
||||||
|
return imap
|
||||||
|
|
||||||
|
|
||||||
|
def test_imap_connection(
|
||||||
|
config: ImapConfig,
|
||||||
|
timeout: float = CONNECTION_TEST_IMAP_TIMEOUT,
|
||||||
|
) -> tuple[bool, str]:
|
||||||
|
imap = None
|
||||||
|
try:
|
||||||
|
imap = connect_imap(config, timeout=timeout)
|
||||||
|
folders = list_mailboxes(imap)
|
||||||
|
return True, f"IMAP OK — {len(folders)} mailbox(es) found"
|
||||||
|
except Exception as exc:
|
||||||
|
return False, str(exc)
|
||||||
|
finally:
|
||||||
|
if imap is not None:
|
||||||
|
try:
|
||||||
|
imap.logout()
|
||||||
|
except imaplib.IMAP4.error:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
"""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
|
||||||
|
|
||||||
|
_PDF_MAGIC = b"%PDF-"
|
||||||
|
_PDF_HEADER_SCAN_BYTES = 1024
|
||||||
|
|
||||||
|
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 _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
|
||||||
|
return _find_pdf_magic(data) is not None
|
||||||
|
|
||||||
|
|
||||||
|
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":
|
||||||
|
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)
|
||||||
|
|
||||||
|
if ext == ".zip" or content_type in ("application/zip", "application/x-zip-compressed"):
|
||||||
|
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'})"
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
"""Email parsing utilities."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import email
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from email.header import decode_header, make_header
|
||||||
|
from email.message import EmailMessage
|
||||||
|
from email.utils import parsedate_to_datetime
|
||||||
|
|
||||||
|
from forwarder.email.invoice_validation import is_plausible_invoice_file
|
||||||
|
|
||||||
|
DEFAULT_ALLOWED_EXTENSIONS = {".pdf", ".xml", ".zip", ".png", ".jpg", ".jpeg"}
|
||||||
|
|
||||||
|
ALLOWED_MIME_TYPES = {
|
||||||
|
"application/pdf",
|
||||||
|
"application/xml",
|
||||||
|
"text/xml",
|
||||||
|
"application/zip",
|
||||||
|
"application/x-zip-compressed",
|
||||||
|
"image/png",
|
||||||
|
"image/jpeg",
|
||||||
|
"image/jpg",
|
||||||
|
}
|
||||||
|
|
||||||
|
MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def clean_header(value: str | None) -> str:
|
||||||
|
if not value:
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
return str(make_header(decode_header(value)))
|
||||||
|
except Exception:
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def clean_subject(subject: str | None) -> str:
|
||||||
|
cleaned = clean_header(subject)
|
||||||
|
if cleaned:
|
||||||
|
return cleaned
|
||||||
|
return "(no subject)"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_message_id(message_id: str | None) -> str | None:
|
||||||
|
if not message_id:
|
||||||
|
return None
|
||||||
|
cleaned = message_id.strip()
|
||||||
|
if cleaned.startswith("<") and cleaned.endswith(">"):
|
||||||
|
cleaned = cleaned[1:-1].strip()
|
||||||
|
if cleaned:
|
||||||
|
return cleaned
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_email_datetime(date_header: str | None) -> datetime | None:
|
||||||
|
"""Parse RFC2822 Date header to timezone-aware datetime."""
|
||||||
|
if not date_header or not date_header.strip():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
dt = parsedate_to_datetime(date_header.strip())
|
||||||
|
except (TypeError, ValueError, IndexError, OverflowError):
|
||||||
|
return None
|
||||||
|
if dt.tzinfo is None:
|
||||||
|
dt = dt.replace(tzinfo=timezone.utc)
|
||||||
|
return dt
|
||||||
|
|
||||||
|
|
||||||
|
def get_message_key(folder: str, uid: bytes | str, msg: email.message.EmailMessage) -> str:
|
||||||
|
msg_id = normalize_message_id(msg.get("Message-ID"))
|
||||||
|
if msg_id:
|
||||||
|
return msg_id
|
||||||
|
uid_str = uid.decode() if isinstance(uid, bytes) else str(uid)
|
||||||
|
return f"{folder}:{uid_str}"
|
||||||
|
|
||||||
|
|
||||||
|
def part_filename(part: email.message.Message) -> str:
|
||||||
|
filename = part.get_filename()
|
||||||
|
if filename:
|
||||||
|
return clean_header(filename).lower()
|
||||||
|
name = part.get_param("name", header="content-disposition")
|
||||||
|
if name:
|
||||||
|
return clean_header(name).lower()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
filename = part_filename(part)
|
||||||
|
content_type = (part.get_content_type() or "").lower()
|
||||||
|
|
||||||
|
if disposition == "inline":
|
||||||
|
return False
|
||||||
|
|
||||||
|
if disposition == "attachment":
|
||||||
|
if filename:
|
||||||
|
return True
|
||||||
|
return content_type in ALLOWED_MIME_TYPES
|
||||||
|
|
||||||
|
if filename:
|
||||||
|
_, ext = os.path.splitext(filename)
|
||||||
|
if ext in DEFAULT_ALLOWED_EXTENSIONS:
|
||||||
|
return True
|
||||||
|
|
||||||
|
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(
|
||||||
|
part: email.message.Message,
|
||||||
|
*,
|
||||||
|
include_all_attachments: bool,
|
||||||
|
allowed_extensions: set[str],
|
||||||
|
) -> bool:
|
||||||
|
if not is_real_attachment(part):
|
||||||
|
return False
|
||||||
|
|
||||||
|
if include_all_attachments:
|
||||||
|
return True
|
||||||
|
|
||||||
|
filename = part_filename(part)
|
||||||
|
if filename:
|
||||||
|
_, ext = os.path.splitext(filename)
|
||||||
|
if ext in allowed_extensions:
|
||||||
|
return True
|
||||||
|
|
||||||
|
content_type = (part.get_content_type() or "").lower()
|
||||||
|
return content_type in ALLOWED_MIME_TYPES
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class InvoiceAttachment:
|
||||||
|
filename: str
|
||||||
|
data: bytes
|
||||||
|
maintype: str
|
||||||
|
subtype: str
|
||||||
|
|
||||||
|
|
||||||
|
def _split_content_type(content_type: str) -> tuple[str, str]:
|
||||||
|
maintype, _, subtype = content_type.partition("/")
|
||||||
|
if not subtype:
|
||||||
|
return "application", "octet-stream"
|
||||||
|
return maintype, subtype
|
||||||
|
|
||||||
|
|
||||||
|
def collect_matching_attachments(
|
||||||
|
msg: EmailMessage,
|
||||||
|
*,
|
||||||
|
include_all_attachments: bool = False,
|
||||||
|
allowed_extensions: set[str] | None = None,
|
||||||
|
) -> list[InvoiceAttachment]:
|
||||||
|
"""Extract invoice attachments (PDF/XML/ZIP) from a message for SMTP relay."""
|
||||||
|
if allowed_extensions is None:
|
||||||
|
allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS
|
||||||
|
|
||||||
|
collected: list[InvoiceAttachment] = []
|
||||||
|
seen_names: set[str] = set()
|
||||||
|
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.is_multipart():
|
||||||
|
continue
|
||||||
|
if not _part_passes_invoice_checks(
|
||||||
|
part,
|
||||||
|
include_all_attachments=include_all_attachments,
|
||||||
|
allowed_extensions=allowed_extensions,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
payload = part.get_payload(decode=True)
|
||||||
|
if not payload:
|
||||||
|
continue
|
||||||
|
|
||||||
|
filename = part_filename(part) or part.get_filename() or ""
|
||||||
|
filename = clean_header(filename) or "attachment"
|
||||||
|
if filename in seen_names:
|
||||||
|
base, ext = os.path.splitext(filename)
|
||||||
|
counter = 2
|
||||||
|
while f"{base}-{counter}{ext}" in seen_names:
|
||||||
|
counter += 1
|
||||||
|
filename = f"{base}-{counter}{ext}"
|
||||||
|
|
||||||
|
seen_names.add(filename)
|
||||||
|
maintype, subtype = _split_content_type(part.get_content_type())
|
||||||
|
collected.append(
|
||||||
|
InvoiceAttachment(
|
||||||
|
filename=filename,
|
||||||
|
data=payload,
|
||||||
|
maintype=maintype,
|
||||||
|
subtype=subtype,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return collected
|
||||||
|
|
||||||
|
|
||||||
|
def has_matching_attachment(
|
||||||
|
msg: EmailMessage,
|
||||||
|
*,
|
||||||
|
include_all_attachments: bool = False,
|
||||||
|
allowed_extensions: set[str] | None = None,
|
||||||
|
) -> bool:
|
||||||
|
if allowed_extensions is None:
|
||||||
|
allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS
|
||||||
|
|
||||||
|
for part in msg.walk():
|
||||||
|
if part.is_multipart():
|
||||||
|
continue
|
||||||
|
if _part_passes_invoice_checks(
|
||||||
|
part,
|
||||||
|
include_all_attachments=include_all_attachments,
|
||||||
|
allowed_extensions=allowed_extensions,
|
||||||
|
):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"""SMTP client helpers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import smtplib
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from email.message import EmailMessage
|
||||||
|
|
||||||
|
from forwarder.email.parsing import (
|
||||||
|
DEFAULT_ALLOWED_EXTENSIONS,
|
||||||
|
clean_subject,
|
||||||
|
collect_matching_attachments,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_SMTP_TIMEOUT = 30
|
||||||
|
CONNECTION_TEST_SMTP_TIMEOUT = 5
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SmtpConfig:
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
user: str
|
||||||
|
password: str
|
||||||
|
use_tls: bool = True
|
||||||
|
|
||||||
|
|
||||||
|
def create_smtp_client(
|
||||||
|
config: SmtpConfig,
|
||||||
|
timeout: float = DEFAULT_SMTP_TIMEOUT,
|
||||||
|
) -> smtplib.SMTP:
|
||||||
|
if config.port == 465 and not config.use_tls:
|
||||||
|
client = smtplib.SMTP_SSL(config.host, config.port, timeout=timeout)
|
||||||
|
else:
|
||||||
|
client = smtplib.SMTP(config.host, config.port, timeout=timeout)
|
||||||
|
if config.use_tls:
|
||||||
|
client.starttls()
|
||||||
|
client.login(config.user, config.password)
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def build_forward_message(
|
||||||
|
original_msg: EmailMessage,
|
||||||
|
*,
|
||||||
|
from_addr: str,
|
||||||
|
destination_email: str,
|
||||||
|
include_all_attachments: bool = False,
|
||||||
|
allowed_extensions: set[str] | None = None,
|
||||||
|
) -> EmailMessage:
|
||||||
|
"""Build a clean outbound message with invoice files only.
|
||||||
|
|
||||||
|
Does not relay the original RFC822 (avoids spam filters, loops, and MailChannels
|
||||||
|
blocks on inherited bulk-mail headers). Keeps the original subject without Fwd:.
|
||||||
|
"""
|
||||||
|
if allowed_extensions is None:
|
||||||
|
allowed_extensions = DEFAULT_ALLOWED_EXTENSIONS
|
||||||
|
|
||||||
|
attachments = collect_matching_attachments(
|
||||||
|
original_msg,
|
||||||
|
include_all_attachments=include_all_attachments,
|
||||||
|
allowed_extensions=allowed_extensions,
|
||||||
|
)
|
||||||
|
if not attachments:
|
||||||
|
raise ValueError("No matching invoice attachments to forward")
|
||||||
|
|
||||||
|
subject = clean_subject(original_msg.get("Subject"))
|
||||||
|
sender = original_msg.get("From", "")
|
||||||
|
date = original_msg.get("Date", "")
|
||||||
|
|
||||||
|
outbound = EmailMessage()
|
||||||
|
outbound["From"] = from_addr
|
||||||
|
outbound["To"] = destination_email
|
||||||
|
outbound["Subject"] = subject
|
||||||
|
|
||||||
|
body = (
|
||||||
|
"Documento reencaminhado para arquivo digital.\n\n"
|
||||||
|
f"Remetente original: {sender}\n"
|
||||||
|
f"Data original: {date}\n"
|
||||||
|
f"Assunto original: {subject}\n"
|
||||||
|
f"Anexos: {', '.join(a.filename for a in attachments)}\n"
|
||||||
|
)
|
||||||
|
outbound.set_content(body)
|
||||||
|
|
||||||
|
for attachment in attachments:
|
||||||
|
outbound.add_attachment(
|
||||||
|
attachment.data,
|
||||||
|
maintype=attachment.maintype,
|
||||||
|
subtype=attachment.subtype,
|
||||||
|
filename=attachment.filename,
|
||||||
|
)
|
||||||
|
|
||||||
|
return outbound
|
||||||
|
|
||||||
|
|
||||||
|
def forward_invoice_attachments(
|
||||||
|
original_msg: EmailMessage,
|
||||||
|
*,
|
||||||
|
smtp_config: SmtpConfig,
|
||||||
|
destination_email: str,
|
||||||
|
smtp: smtplib.SMTP | None = None,
|
||||||
|
include_all_attachments: bool = False,
|
||||||
|
allowed_extensions: set[str] | None = None,
|
||||||
|
) -> None:
|
||||||
|
outbound = build_forward_message(
|
||||||
|
original_msg,
|
||||||
|
from_addr=smtp_config.user,
|
||||||
|
destination_email=destination_email,
|
||||||
|
include_all_attachments=include_all_attachments,
|
||||||
|
allowed_extensions=allowed_extensions,
|
||||||
|
)
|
||||||
|
|
||||||
|
owns_client = smtp is None
|
||||||
|
client = smtp
|
||||||
|
if client is None:
|
||||||
|
client = create_smtp_client(smtp_config)
|
||||||
|
|
||||||
|
try:
|
||||||
|
client.send_message(
|
||||||
|
outbound,
|
||||||
|
from_addr=smtp_config.user,
|
||||||
|
to_addrs=[destination_email],
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
if owns_client:
|
||||||
|
try:
|
||||||
|
client.quit()
|
||||||
|
except smtplib.SMTPException:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def test_smtp_connection(
|
||||||
|
config: SmtpConfig,
|
||||||
|
timeout: float = CONNECTION_TEST_SMTP_TIMEOUT,
|
||||||
|
) -> tuple[bool, str]:
|
||||||
|
client = None
|
||||||
|
try:
|
||||||
|
client = create_smtp_client(config, timeout=timeout)
|
||||||
|
return True, "SMTP login OK"
|
||||||
|
except Exception as exc:
|
||||||
|
return False, str(exc)
|
||||||
|
finally:
|
||||||
|
if client is not None:
|
||||||
|
try:
|
||||||
|
client.quit()
|
||||||
|
except smtplib.SMTPException:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def send_test_email(
|
||||||
|
config: SmtpConfig,
|
||||||
|
destination_email: str,
|
||||||
|
) -> tuple[bool, str]:
|
||||||
|
client = None
|
||||||
|
try:
|
||||||
|
client = create_smtp_client(config)
|
||||||
|
msg = EmailMessage()
|
||||||
|
msg["From"] = config.user
|
||||||
|
msg["To"] = destination_email
|
||||||
|
msg["Subject"] = "BizDocs Forwarder test"
|
||||||
|
msg.set_content("This is a test message from BizDocs Forwarder.")
|
||||||
|
client.send_message(msg)
|
||||||
|
return True, f"Test email sent to {destination_email}"
|
||||||
|
except Exception as exc:
|
||||||
|
return False, str(exc)
|
||||||
|
finally:
|
||||||
|
if client is not None:
|
||||||
|
try:
|
||||||
|
client.quit()
|
||||||
|
except smtplib.SMTPException:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
"""Error hub client for BizDocs Forwarder.
|
||||||
|
|
||||||
|
Posts runtime exceptions to errors.bitreport.pt so failures enter the
|
||||||
|
Paperclip ERRSIG triage flow. Aligned with the v1/ingest/events contract
|
||||||
|
used by errorReporter.mjs and paperclip_exception_reporter.py.
|
||||||
|
|
||||||
|
Best-effort: never raises, never blocks the caller.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import traceback
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from collections.abc import Mapping
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_DEFAULT_ENDPOINT = "https://errors.bitreport.pt"
|
||||||
|
_DEFAULT_PROJECT_SLUG = "bizdocs-forwarder"
|
||||||
|
_DEFAULT_GITEA_REPO = "BitReport.pt/forwarder"
|
||||||
|
_DEFAULT_PROJECT_NAME = "BizDocs Forwarder"
|
||||||
|
_COOLDLOCK = threading.Lock()
|
||||||
|
_COOLDOWNS: dict[str, float] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _env(name: str, default: str = "") -> str:
|
||||||
|
return os.environ.get(name, "").strip() or default
|
||||||
|
|
||||||
|
|
||||||
|
def _env_flag(name: str, default: bool) -> bool:
|
||||||
|
raw = os.environ.get(name, "").strip().lower()
|
||||||
|
if raw == "":
|
||||||
|
return default
|
||||||
|
return raw in {"1", "true", "yes", "on"}
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorHubConfig:
|
||||||
|
"""Lazy singleton for error hub configuration from env vars."""
|
||||||
|
|
||||||
|
_instance: ErrorHubConfig | None = None
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.endpoint = _env("ERROR_REPORTING_ENDPOINT", _DEFAULT_ENDPOINT).rstrip("/")
|
||||||
|
self.token = _env("ERROR_REPORTING_TOKEN")
|
||||||
|
self.project_name = _env("ERROR_MONITORING_PROJECT_NAME", _DEFAULT_PROJECT_NAME)
|
||||||
|
self.project_slug = _env("ERROR_MONITORING_PROJECT_SLUG", _DEFAULT_PROJECT_SLUG)
|
||||||
|
self.gitea_repo = _env("ERROR_MONITORING_GITEA_REPO", _DEFAULT_GITEA_REPO)
|
||||||
|
self.paperclip_project_id = _env("ERROR_MONITORING_PAPERCLIP_PROJECT_ID")
|
||||||
|
self.environment = _env("ERROR_MONITORING_ENV", "production")
|
||||||
|
self.timeout_sec = 5.0
|
||||||
|
self.enabled = _env_flag("ERROR_REPORTING_ENABLED", True)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def get(cls) -> ErrorHubConfig:
|
||||||
|
if cls._instance is None:
|
||||||
|
cls._instance = cls()
|
||||||
|
return cls._instance
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def reset(cls) -> None:
|
||||||
|
cls._instance = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def configured(self) -> bool:
|
||||||
|
return bool(self.token)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_event(
|
||||||
|
message: str,
|
||||||
|
stacktrace: str,
|
||||||
|
*,
|
||||||
|
error_type: str = "Exception",
|
||||||
|
severity: str = "error",
|
||||||
|
context_data: Mapping[str, Any] | None = None,
|
||||||
|
file_path: str = "",
|
||||||
|
line_number: int = 0,
|
||||||
|
url: str = "",
|
||||||
|
endpoint: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
cfg = ErrorHubConfig.get()
|
||||||
|
ctx: dict[str, Any] = {
|
||||||
|
"project_name": cfg.project_name,
|
||||||
|
"project_slug": cfg.project_slug,
|
||||||
|
"environment": cfg.environment,
|
||||||
|
"error_type": error_type,
|
||||||
|
"gitea_repo": cfg.gitea_repo,
|
||||||
|
}
|
||||||
|
if file_path:
|
||||||
|
ctx["file_path"] = file_path
|
||||||
|
if line_number:
|
||||||
|
ctx["line_number"] = line_number
|
||||||
|
if url:
|
||||||
|
ctx["url"] = url
|
||||||
|
if endpoint:
|
||||||
|
ctx["endpoint"] = endpoint
|
||||||
|
if cfg.paperclip_project_id:
|
||||||
|
ctx["paperclip_project_id"] = cfg.paperclip_project_id
|
||||||
|
if context_data:
|
||||||
|
for k, v in context_data.items():
|
||||||
|
if k not in ctx:
|
||||||
|
ctx[k] = v if not isinstance(v, (dict, list)) else json.dumps(v, default=str)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"schema_version": 1,
|
||||||
|
"occurred_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||||
|
"level": severity,
|
||||||
|
"message": message[:2000],
|
||||||
|
"stacktrace": stacktrace[:12000],
|
||||||
|
"context": ctx,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _post_event(event: dict[str, Any]) -> bool:
|
||||||
|
cfg = ErrorHubConfig.get()
|
||||||
|
if not cfg.configured or not cfg.enabled:
|
||||||
|
if not cfg.configured:
|
||||||
|
logger.debug("[ERROR_HUB_NOT_CONFIGURED] token missing, skipping report")
|
||||||
|
return False
|
||||||
|
|
||||||
|
url = f"{cfg.endpoint}/v1/ingest/events"
|
||||||
|
payload = json.dumps({"events": [event]}, ensure_ascii=False).encode("utf-8")
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json; charset=utf-8",
|
||||||
|
"User-Agent": "BizDocs-Forwarder-ErrorReporter/1.0",
|
||||||
|
"Authorization": f"Bearer {cfg.token}",
|
||||||
|
}
|
||||||
|
req = urllib.request.Request(url, method="POST", data=payload, headers=headers)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=cfg.timeout_sec) as resp:
|
||||||
|
return resp.status // 100 == 2
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
logger.error(
|
||||||
|
"[ERROR_HUB_INGEST_FAILED] status=%s url=%s", exc.code, url
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
except Exception:
|
||||||
|
logger.error("[ERROR_HUB_INGEST_FAILED] connection error to %s", url, exc_info=False)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def report_error(
|
||||||
|
error: BaseException | str,
|
||||||
|
*,
|
||||||
|
severity: str = "error",
|
||||||
|
context_data: Mapping[str, Any] | None = None,
|
||||||
|
url: str = "",
|
||||||
|
endpoint: str = "",
|
||||||
|
file_path: str = "",
|
||||||
|
line_number: int = 0,
|
||||||
|
) -> bool:
|
||||||
|
"""Report an error to the error hub. Best-effort, never raises."""
|
||||||
|
if isinstance(error, str):
|
||||||
|
message = error[:2000]
|
||||||
|
error_type = "Exception"
|
||||||
|
stacktrace = traceback.format_stack()[-3:-1]
|
||||||
|
stacktrace_text = "".join(stacktrace) if stacktrace else message
|
||||||
|
else:
|
||||||
|
message = f"{type(error).__name__}: {error}"[:2000]
|
||||||
|
error_type = type(error).__name__
|
||||||
|
stacktrace_text = "".join(
|
||||||
|
traceback.format_exception(type(error), error, error.__traceback__)
|
||||||
|
)[:12000]
|
||||||
|
|
||||||
|
event = _build_event(
|
||||||
|
message=message,
|
||||||
|
stacktrace=stacktrace_text,
|
||||||
|
error_type=error_type,
|
||||||
|
severity=severity,
|
||||||
|
context_data=context_data,
|
||||||
|
file_path=file_path,
|
||||||
|
line_number=line_number,
|
||||||
|
url=url,
|
||||||
|
endpoint=endpoint,
|
||||||
|
)
|
||||||
|
return _post_event(event)
|
||||||
|
|
||||||
|
|
||||||
|
def report_error_with_cooldown(
|
||||||
|
key: str,
|
||||||
|
cooldown_seconds: float,
|
||||||
|
error: BaseException | str,
|
||||||
|
*,
|
||||||
|
severity: str = "error",
|
||||||
|
context_data: Mapping[str, Any] | None = None,
|
||||||
|
url: str = "",
|
||||||
|
endpoint: str = "",
|
||||||
|
) -> bool:
|
||||||
|
"""Report an error but suppress duplicates within *cooldown_seconds*."""
|
||||||
|
now = time.monotonic()
|
||||||
|
with _COOLDLOCK:
|
||||||
|
last = _COOLDOWNS.get(key, 0.0)
|
||||||
|
if now - last < cooldown_seconds:
|
||||||
|
return False
|
||||||
|
_COOLDOWNS[key] = now
|
||||||
|
|
||||||
|
return report_error(
|
||||||
|
error,
|
||||||
|
severity=severity,
|
||||||
|
context_data=context_data,
|
||||||
|
url=url,
|
||||||
|
endpoint=endpoint,
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
"""Shop invoice scrapers (Temu, Amazon, …)."""
|
||||||
|
|
||||||
|
from forwarder.scrapers.base import InvoiceDocument, InvoiceScraper
|
||||||
|
from forwarder.scrapers.registry import get_scraper
|
||||||
|
|
||||||
|
__all__ = ["InvoiceDocument", "InvoiceScraper", "get_scraper"]
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
"""Amazon invoice scraper using Playwright browser automation."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import AsyncGenerator
|
||||||
|
|
||||||
|
from forwarder.scrapers.base import InvoiceDocument, InvoiceScraper, ShopCredentials
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Amazon domains — PT/ES/DE customers may use amazon.es / amazon.de / etc.
|
||||||
|
# Default to amazon.es which is common in Portugal; can be overridden via credentials.extra["domain"]
|
||||||
|
DEFAULT_DOMAIN = "amazon.es"
|
||||||
|
|
||||||
|
# Order history page (shows VAT invoices for business accounts)
|
||||||
|
ORDERS_PATH = "/gp/your-account/order-history"
|
||||||
|
# VAT invoice download path pattern
|
||||||
|
VAT_INVOICE_PATH = "/gp/shared-cs/ajax/invoice/invoice.html"
|
||||||
|
|
||||||
|
|
||||||
|
class AmazonScraper(InvoiceScraper):
|
||||||
|
"""
|
||||||
|
Scrapes Amazon VAT invoice PDFs using Playwright.
|
||||||
|
|
||||||
|
Supports:
|
||||||
|
- amazon.es (Portugal / Spain)
|
||||||
|
- amazon.de (Germany)
|
||||||
|
- amazon.co.uk
|
||||||
|
- amazon.com
|
||||||
|
- any other supported domain via credentials.extra["domain"]
|
||||||
|
|
||||||
|
First run: logs in with email+password. Amazon may require OTP/2FA —
|
||||||
|
if so the login will time out. Use the Admin UI "Test Connection" flow
|
||||||
|
to authenticate interactively and save the session state.
|
||||||
|
|
||||||
|
Subsequent runs: restores saved Playwright storage state (cookies).
|
||||||
|
"""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _domain(self) -> str:
|
||||||
|
return self._credentials.extra.get("domain", DEFAULT_DOMAIN).lower()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def _base_url(self) -> str:
|
||||||
|
return f"https://www.{self._domain}"
|
||||||
|
|
||||||
|
async def iter_invoices(
|
||||||
|
self,
|
||||||
|
since: datetime | None = None,
|
||||||
|
max_orders: int = 100,
|
||||||
|
) -> AsyncGenerator[InvoiceDocument, None]:
|
||||||
|
try:
|
||||||
|
from playwright.async_api import async_playwright
|
||||||
|
except ImportError as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
"playwright is not installed. Run: pip install playwright && playwright install chromium"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
async with async_playwright() as pw:
|
||||||
|
browser = await pw.chromium.launch(headless=True)
|
||||||
|
context_opts: dict = {}
|
||||||
|
|
||||||
|
if self._credentials.session_state_json:
|
||||||
|
state = json.loads(self._credentials.session_state_json)
|
||||||
|
context_opts["storage_state"] = state
|
||||||
|
|
||||||
|
context = await browser.new_context(
|
||||||
|
**context_opts,
|
||||||
|
user_agent=(
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||||
|
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||||
|
"Chrome/124.0.0.0 Safari/537.36"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
page = await context.new_page()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Authentication ---
|
||||||
|
if not self._credentials.session_state_json:
|
||||||
|
await self._login(page)
|
||||||
|
else:
|
||||||
|
await page.goto(
|
||||||
|
f"{self._base_url}{ORDERS_PATH}",
|
||||||
|
wait_until="domcontentloaded",
|
||||||
|
timeout=30_000,
|
||||||
|
)
|
||||||
|
if "signin" in page.url.lower() or "ap/signin" in page.url.lower():
|
||||||
|
logger.info("Amazon: session expired, re-logging in")
|
||||||
|
await self._login(page)
|
||||||
|
|
||||||
|
# --- Collect orders from order history pages ---
|
||||||
|
orders_seen = 0
|
||||||
|
year = datetime.now(tz=timezone.utc).year
|
||||||
|
|
||||||
|
for year_offset in range(3): # current year + 2 previous
|
||||||
|
if orders_seen >= max_orders:
|
||||||
|
break
|
||||||
|
|
||||||
|
check_year = year - year_offset
|
||||||
|
order_ids = await self._list_order_ids_for_year(page, check_year, since)
|
||||||
|
|
||||||
|
for order_id in order_ids:
|
||||||
|
if orders_seen >= max_orders:
|
||||||
|
break
|
||||||
|
orders_seen += 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = await self._download_invoice(context, page, order_id)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Amazon: failed to download invoice for order %s: %s", order_id, exc
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if result is None:
|
||||||
|
logger.debug("Amazon: no VAT invoice for order %s", order_id)
|
||||||
|
continue
|
||||||
|
|
||||||
|
pdf_bytes, order_date = result
|
||||||
|
yield InvoiceDocument(
|
||||||
|
order_id=order_id,
|
||||||
|
filename=f"amazon_invoice_{order_id}.pdf",
|
||||||
|
data=pdf_bytes,
|
||||||
|
order_date=order_date,
|
||||||
|
description=f"Amazon order {order_id}",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Persist updated session state
|
||||||
|
updated_state = await context.storage_state()
|
||||||
|
self._updated_session_state = json.dumps(updated_state)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await context.close()
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
async def _login(self, page) -> None:
|
||||||
|
"""Perform email+password login on Amazon."""
|
||||||
|
logger.info("Amazon: logging in as %s on %s", self._credentials.email, self._domain)
|
||||||
|
await page.goto(
|
||||||
|
f"{self._base_url}/ap/signin",
|
||||||
|
wait_until="domcontentloaded",
|
||||||
|
timeout=30_000,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Email step
|
||||||
|
await page.wait_for_selector("#ap_email", timeout=10_000)
|
||||||
|
await page.fill("#ap_email", self._credentials.email)
|
||||||
|
await page.click("#continue")
|
||||||
|
|
||||||
|
# Password step
|
||||||
|
await page.wait_for_selector("#ap_password", timeout=10_000)
|
||||||
|
await page.fill("#ap_password", self._credentials.password)
|
||||||
|
await page.click("#signInSubmit")
|
||||||
|
await page.wait_for_load_state("domcontentloaded", timeout=20_000)
|
||||||
|
|
||||||
|
if "signin" in page.url.lower() or "ap/signin" in page.url.lower():
|
||||||
|
# May be OTP page
|
||||||
|
otp_input = page.locator("#auth-mfa-otpcode")
|
||||||
|
if await otp_input.count() > 0:
|
||||||
|
raise RuntimeError(
|
||||||
|
"Amazon requires OTP/2FA. "
|
||||||
|
"Use the Admin UI to authenticate interactively and save the session state."
|
||||||
|
)
|
||||||
|
raise RuntimeError(
|
||||||
|
"Amazon login failed — check credentials or CAPTCHA. "
|
||||||
|
"Use Admin UI to authenticate interactively."
|
||||||
|
)
|
||||||
|
|
||||||
|
logger.info("Amazon: login successful")
|
||||||
|
|
||||||
|
async def _list_order_ids_for_year(
|
||||||
|
self,
|
||||||
|
page,
|
||||||
|
year: int,
|
||||||
|
since: datetime | None,
|
||||||
|
) -> list[str]:
|
||||||
|
"""Return all order IDs for the given year from Amazon order history."""
|
||||||
|
url = (
|
||||||
|
f"{self._base_url}{ORDERS_PATH}"
|
||||||
|
f"?opt=ab&digitalOrders=1&unifiedOrders=1&returnTo=&orderFilter=year-{year}"
|
||||||
|
)
|
||||||
|
await page.goto(url, wait_until="domcontentloaded", timeout=30_000)
|
||||||
|
|
||||||
|
order_ids: list[str] = []
|
||||||
|
while True:
|
||||||
|
# Extract order IDs from the page
|
||||||
|
# Amazon marks orders with data attributes or aria-labels containing the order number
|
||||||
|
elements = await page.query_selector_all(
|
||||||
|
"[data-order-id], .order-id, .a-size-mini.a-color-secondary.value"
|
||||||
|
)
|
||||||
|
for el in elements:
|
||||||
|
text = await el.inner_text()
|
||||||
|
# Order IDs match pattern like: 402-1234567-8901234
|
||||||
|
matches = re.findall(r"\d{3}-\d{7}-\d{7}", text)
|
||||||
|
for oid in matches:
|
||||||
|
if oid not in order_ids:
|
||||||
|
order_ids.append(oid)
|
||||||
|
|
||||||
|
# Check for "next page" pagination
|
||||||
|
next_btn = page.locator(
|
||||||
|
'li.a-last a, .a-pagination .a-last a, [aria-label="Next page"]'
|
||||||
|
)
|
||||||
|
if await next_btn.count() > 0:
|
||||||
|
await next_btn.first.click()
|
||||||
|
await page.wait_for_load_state("domcontentloaded", timeout=15_000)
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
logger.debug("Amazon: found %s order IDs for year %s", len(order_ids), year)
|
||||||
|
return order_ids
|
||||||
|
|
||||||
|
async def _download_invoice(
|
||||||
|
self,
|
||||||
|
context,
|
||||||
|
page,
|
||||||
|
order_id: str,
|
||||||
|
) -> tuple[bytes, datetime | None] | None:
|
||||||
|
"""
|
||||||
|
Attempt to download the VAT invoice PDF for an Amazon order.
|
||||||
|
|
||||||
|
Returns (pdf_bytes, order_date) or None if no invoice available.
|
||||||
|
"""
|
||||||
|
# Navigate to the order detail page to find the invoice link
|
||||||
|
order_url = f"{self._base_url}/gp/your-account/order-details?orderID={order_id}"
|
||||||
|
await page.goto(order_url, wait_until="domcontentloaded", timeout=30_000)
|
||||||
|
|
||||||
|
# Look for VAT invoice link
|
||||||
|
invoice_link = page.locator(
|
||||||
|
'a[href*="invoice"], a[href*="Invoice"], '
|
||||||
|
'a:has-text("VAT invoice"), a:has-text("Fatura"), '
|
||||||
|
'a:has-text("Rechnung"), a:has-text("Invoice")'
|
||||||
|
).first
|
||||||
|
|
||||||
|
if await invoice_link.count() == 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
invoice_href = await invoice_link.get_attribute("href")
|
||||||
|
if not invoice_href:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not invoice_href.startswith("http"):
|
||||||
|
invoice_href = self._base_url + invoice_href
|
||||||
|
|
||||||
|
# Download the invoice — it may be HTML (printable receipt) or PDF
|
||||||
|
inv_page = await context.new_page()
|
||||||
|
try:
|
||||||
|
# Intercept PDF download
|
||||||
|
pdf_bytes: bytes | None = None
|
||||||
|
|
||||||
|
async def handle_download(download):
|
||||||
|
nonlocal pdf_bytes
|
||||||
|
path = await download.path()
|
||||||
|
if path:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
pdf_bytes = f.read()
|
||||||
|
|
||||||
|
inv_page.on("download", handle_download)
|
||||||
|
|
||||||
|
response = await inv_page.goto(invoice_href, wait_until="domcontentloaded", timeout=20_000)
|
||||||
|
if response and response.status == 200:
|
||||||
|
content_type = response.headers.get("content-type", "")
|
||||||
|
if "pdf" in content_type:
|
||||||
|
pdf_bytes = await response.body()
|
||||||
|
elif not pdf_bytes:
|
||||||
|
# It's a printable HTML receipt — generate PDF via Playwright
|
||||||
|
pdf_bytes = await inv_page.pdf(
|
||||||
|
format="A4",
|
||||||
|
print_background=True,
|
||||||
|
margin={"top": "1cm", "bottom": "1cm", "left": "1cm", "right": "1cm"},
|
||||||
|
)
|
||||||
|
|
||||||
|
if not pdf_bytes:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Parse order date from the order detail page (already loaded)
|
||||||
|
order_date = await self._parse_order_date(page)
|
||||||
|
return pdf_bytes, order_date
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await inv_page.close()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def _parse_order_date(page) -> datetime | None:
|
||||||
|
"""Extract order placement date from an Amazon order detail page."""
|
||||||
|
try:
|
||||||
|
# Amazon shows "Order placed: DD Month YYYY" in the order header
|
||||||
|
date_el = page.locator(
|
||||||
|
".order-date-invoice-item, "
|
||||||
|
"[data-testid='order-date'], "
|
||||||
|
".a-color-secondary span"
|
||||||
|
).first
|
||||||
|
if await date_el.count() > 0:
|
||||||
|
text = await date_el.inner_text()
|
||||||
|
# Simple heuristic: find a 4-digit year
|
||||||
|
match = re.search(r"\d{1,2}\s+\w+\s+(\d{4})", text)
|
||||||
|
if match:
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text.strip(), "%d %B %Y").replace(
|
||||||
|
tzinfo=timezone.utc
|
||||||
|
)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Base class and data types for shop invoice scrapers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import abc
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class InvoiceDocument:
|
||||||
|
"""An invoice retrieved from a shop."""
|
||||||
|
|
||||||
|
order_id: str
|
||||||
|
filename: str
|
||||||
|
data: bytes
|
||||||
|
order_date: datetime | None = None
|
||||||
|
# Human-readable label shown in logs
|
||||||
|
description: str = ""
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not self.description:
|
||||||
|
self.description = self.order_id
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ShopCredentials:
|
||||||
|
email: str
|
||||||
|
password: str
|
||||||
|
# Persisted Playwright browser state JSON (cookies + localStorage).
|
||||||
|
# None on first run; set by the scraper after a successful login.
|
||||||
|
session_state_json: str | None = None
|
||||||
|
extra: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class InvoiceScraper(abc.ABC):
|
||||||
|
"""
|
||||||
|
Abstract base for per-shop invoice scrapers.
|
||||||
|
|
||||||
|
Each subclass targets one shop type (Temu, Amazon…). The scraper:
|
||||||
|
1. Authenticates using `credentials` (either fresh login or saved state).
|
||||||
|
2. Lists order IDs for which invoices exist.
|
||||||
|
3. Downloads each invoice as raw bytes.
|
||||||
|
4. Optionally persists an updated session state back to the caller.
|
||||||
|
|
||||||
|
Usage::
|
||||||
|
|
||||||
|
scraper = TemuScraper(credentials)
|
||||||
|
async for doc in scraper.iter_invoices(since=last_scraped_at):
|
||||||
|
upload_to_bizdocs(doc)
|
||||||
|
# Persist updated session for next run:
|
||||||
|
updated_state = scraper.get_updated_session_state()
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, credentials: ShopCredentials) -> None:
|
||||||
|
self._credentials = credentials
|
||||||
|
self._updated_session_state: str | None = None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Abstract interface
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
async def iter_invoices(
|
||||||
|
self,
|
||||||
|
since: datetime | None = None,
|
||||||
|
max_orders: int = 100,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Async generator yielding InvoiceDocument instances.
|
||||||
|
|
||||||
|
`since`: skip orders older than this timestamp.
|
||||||
|
`max_orders`: cap to avoid runaway scrapes on first-ever run.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Session state round-trip
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
|
||||||
|
def get_updated_session_state(self) -> str | None:
|
||||||
|
"""Return serialised Playwright browser state after a run, if refreshed."""
|
||||||
|
return self._updated_session_state
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""Map ShopType enum → InvoiceScraper class."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from forwarder.scrapers.base import InvoiceScraper, ShopCredentials
|
||||||
|
|
||||||
|
|
||||||
|
def get_scraper(shop_type: str, credentials: ShopCredentials) -> InvoiceScraper:
|
||||||
|
"""Instantiate the correct scraper for *shop_type*."""
|
||||||
|
if shop_type == "temu":
|
||||||
|
from forwarder.scrapers.temu import TemuScraper
|
||||||
|
return TemuScraper(credentials)
|
||||||
|
if shop_type == "amazon":
|
||||||
|
from forwarder.scrapers.amazon import AmazonScraper
|
||||||
|
return AmazonScraper(credentials)
|
||||||
|
raise ValueError(f"Unknown shop type: {shop_type!r}")
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
"""Temu invoice scraper using Playwright browser automation."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import AsyncGenerator
|
||||||
|
|
||||||
|
from forwarder.scrapers.base import InvoiceDocument, InvoiceScraper, ShopCredentials
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
TEMU_BASE = "https://www.temu.com"
|
||||||
|
LOGIN_URL = f"{TEMU_BASE}/login.html"
|
||||||
|
ORDERS_URL = f"{TEMU_BASE}/user-orders.html"
|
||||||
|
# Temu internal API used by both web and the Chrome invoice extension
|
||||||
|
ORDERS_API = f"{TEMU_BASE}/api/poppy/v1/order/order_list"
|
||||||
|
INVOICE_API = f"{TEMU_BASE}/api/poppy/v1/invoice/download"
|
||||||
|
|
||||||
|
# How many pages of orders to fetch per run
|
||||||
|
MAX_PAGES = 10
|
||||||
|
PAGE_SIZE = 20
|
||||||
|
|
||||||
|
|
||||||
|
class TemuScraper(InvoiceScraper):
|
||||||
|
"""
|
||||||
|
Scrapes Temu order invoices using Playwright.
|
||||||
|
|
||||||
|
Temu's invoice PDFs are served via their internal API once the user is
|
||||||
|
logged in. The scraper:
|
||||||
|
|
||||||
|
1. Launches a headless Chromium browser.
|
||||||
|
2. Restores a saved session state (cookies) if available, else performs
|
||||||
|
an email+password login.
|
||||||
|
3. Fetches order list pages via the internal JSON API.
|
||||||
|
4. For each order with an invoice available, downloads the PDF bytes.
|
||||||
|
5. Saves the updated browser state for next run.
|
||||||
|
|
||||||
|
Note: Temu may show a CAPTCHA on first login. If the session_state_json
|
||||||
|
in ShopCredentials is empty, the first run logs a warning and the admin
|
||||||
|
should use the Admin UI "Test Connection" flow to complete authentication
|
||||||
|
interactively and save the session state.
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def iter_invoices(
|
||||||
|
self,
|
||||||
|
since: datetime | None = None,
|
||||||
|
max_orders: int = 100,
|
||||||
|
) -> AsyncGenerator[InvoiceDocument, None]:
|
||||||
|
try:
|
||||||
|
from playwright.async_api import async_playwright
|
||||||
|
except ImportError as exc:
|
||||||
|
raise RuntimeError(
|
||||||
|
"playwright is not installed. Run: pip install playwright && playwright install chromium"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
async with async_playwright() as pw:
|
||||||
|
browser = await pw.chromium.launch(headless=True)
|
||||||
|
context_opts: dict = {}
|
||||||
|
|
||||||
|
if self._credentials.session_state_json:
|
||||||
|
state = json.loads(self._credentials.session_state_json)
|
||||||
|
context_opts["storage_state"] = state
|
||||||
|
|
||||||
|
context = await browser.new_context(
|
||||||
|
**context_opts,
|
||||||
|
user_agent=(
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||||
|
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||||
|
"Chrome/124.0.0.0 Safari/537.36"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
page = await context.new_page()
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Authentication ---
|
||||||
|
if not self._credentials.session_state_json:
|
||||||
|
await self._login(page)
|
||||||
|
|
||||||
|
# Validate session by navigating to orders page
|
||||||
|
await page.goto(ORDERS_URL, wait_until="domcontentloaded", timeout=30_000)
|
||||||
|
if "login" in page.url.lower():
|
||||||
|
logger.info("Temu: session expired, re-logging in")
|
||||||
|
await self._login(page)
|
||||||
|
|
||||||
|
# --- Fetch orders via internal API ---
|
||||||
|
orders_fetched = 0
|
||||||
|
for page_num in range(MAX_PAGES):
|
||||||
|
if orders_fetched >= max_orders:
|
||||||
|
break
|
||||||
|
|
||||||
|
order_list = await self._fetch_order_page(context, page_num + 1)
|
||||||
|
if not order_list:
|
||||||
|
break
|
||||||
|
|
||||||
|
for order in order_list:
|
||||||
|
if orders_fetched >= max_orders:
|
||||||
|
break
|
||||||
|
|
||||||
|
order_id = str(order.get("order_sn") or order.get("orderId") or "")
|
||||||
|
if not order_id:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Skip old orders if `since` is set
|
||||||
|
if since:
|
||||||
|
order_time = self._parse_order_time(order)
|
||||||
|
if order_time and order_time < since:
|
||||||
|
logger.debug("Temu: order %s before since cutoff, stopping", order_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
orders_fetched += 1
|
||||||
|
|
||||||
|
try:
|
||||||
|
pdf_bytes = await self._download_invoice(context, order_id)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Temu: failed to download invoice for order %s: %s", order_id, exc)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not pdf_bytes:
|
||||||
|
logger.debug("Temu: no invoice for order %s", order_id)
|
||||||
|
continue
|
||||||
|
|
||||||
|
order_date = self._parse_order_time(order)
|
||||||
|
filename = f"temu_invoice_{order_id}.pdf"
|
||||||
|
yield InvoiceDocument(
|
||||||
|
order_id=order_id,
|
||||||
|
filename=filename,
|
||||||
|
data=pdf_bytes,
|
||||||
|
order_date=order_date,
|
||||||
|
description=f"Temu order {order_id}",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Persist updated session state
|
||||||
|
updated_state = await context.storage_state()
|
||||||
|
self._updated_session_state = json.dumps(updated_state)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
await context.close()
|
||||||
|
await browser.close()
|
||||||
|
|
||||||
|
async def _login(self, page) -> None:
|
||||||
|
"""Perform email+password login on Temu."""
|
||||||
|
logger.info("Temu: logging in as %s", self._credentials.email)
|
||||||
|
await page.goto(LOGIN_URL, wait_until="domcontentloaded", timeout=30_000)
|
||||||
|
|
||||||
|
# Fill email
|
||||||
|
await page.wait_for_selector('input[type="text"], input[type="email"]', timeout=10_000)
|
||||||
|
email_input = page.locator('input[type="email"]').first
|
||||||
|
if await email_input.count() == 0:
|
||||||
|
email_input = page.locator('input[type="text"]').first
|
||||||
|
await email_input.fill(self._credentials.email)
|
||||||
|
|
||||||
|
# Fill password
|
||||||
|
password_input = page.locator('input[type="password"]').first
|
||||||
|
await password_input.fill(self._credentials.password)
|
||||||
|
|
||||||
|
# Submit
|
||||||
|
await page.keyboard.press("Enter")
|
||||||
|
await page.wait_for_load_state("domcontentloaded", timeout=20_000)
|
||||||
|
|
||||||
|
if "login" in page.url.lower():
|
||||||
|
raise RuntimeError(
|
||||||
|
"Temu login failed — page still showing login. "
|
||||||
|
"Possible CAPTCHA. Use Admin UI to authenticate interactively."
|
||||||
|
)
|
||||||
|
logger.info("Temu: login successful")
|
||||||
|
|
||||||
|
async def _fetch_order_page(self, context, page_num: int) -> list[dict]:
|
||||||
|
"""Fetch one page of orders from Temu's internal order list API."""
|
||||||
|
page = await context.new_page()
|
||||||
|
try:
|
||||||
|
response = await page.request.get(
|
||||||
|
ORDERS_API,
|
||||||
|
params={
|
||||||
|
"page": page_num,
|
||||||
|
"page_size": PAGE_SIZE,
|
||||||
|
"order_status": "0", # all statuses
|
||||||
|
},
|
||||||
|
timeout=15_000,
|
||||||
|
)
|
||||||
|
if response.status != 200:
|
||||||
|
logger.warning("Temu order list API returned %s", response.status)
|
||||||
|
return []
|
||||||
|
|
||||||
|
body = await response.json()
|
||||||
|
# Temu API response: {"result": {"order_list": [...], ...}}
|
||||||
|
result = body.get("result") or body
|
||||||
|
if isinstance(result, dict):
|
||||||
|
return result.get("order_list") or result.get("orders") or []
|
||||||
|
return []
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Temu: order page %s fetch failed: %s", page_num, exc)
|
||||||
|
return []
|
||||||
|
finally:
|
||||||
|
await page.close()
|
||||||
|
|
||||||
|
async def _download_invoice(self, context, order_id: str) -> bytes | None:
|
||||||
|
"""Download the invoice PDF for a single Temu order."""
|
||||||
|
page = await context.new_page()
|
||||||
|
try:
|
||||||
|
response = await page.request.get(
|
||||||
|
INVOICE_API,
|
||||||
|
params={"order_sn": order_id},
|
||||||
|
timeout=20_000,
|
||||||
|
)
|
||||||
|
if response.status == 404:
|
||||||
|
return None
|
||||||
|
if response.status != 200:
|
||||||
|
raise RuntimeError(f"HTTP {response.status}")
|
||||||
|
|
||||||
|
content_type = response.headers.get("content-type", "")
|
||||||
|
if "pdf" in content_type or "octet-stream" in content_type:
|
||||||
|
return await response.body()
|
||||||
|
|
||||||
|
# Some Temu responses return a JSON with a PDF URL
|
||||||
|
body = await response.json()
|
||||||
|
pdf_url = (
|
||||||
|
body.get("result", {}).get("invoice_url")
|
||||||
|
or body.get("invoice_url")
|
||||||
|
or body.get("url")
|
||||||
|
)
|
||||||
|
if pdf_url:
|
||||||
|
pdf_resp = await page.request.get(pdf_url, timeout=20_000)
|
||||||
|
if pdf_resp.status == 200:
|
||||||
|
return await pdf_resp.body()
|
||||||
|
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
await page.close()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _parse_order_time(order: dict) -> datetime | None:
|
||||||
|
for key in ("create_time", "order_time", "created_at", "orderTime"):
|
||||||
|
value = order.get(key)
|
||||||
|
if isinstance(value, (int, float)) and value > 0:
|
||||||
|
try:
|
||||||
|
ts = value / 1000 if value > 1e10 else value
|
||||||
|
return datetime.fromtimestamp(ts, tz=timezone.utc)
|
||||||
|
except (OSError, OverflowError):
|
||||||
|
continue
|
||||||
|
if isinstance(value, str) and value:
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
Whitespace-only changes.
@@ -0,0 +1,519 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from forwarder.crypto import decrypt_password, encrypt_password, mask_password
|
||||||
|
from forwarder.db.models import (
|
||||||
|
Account,
|
||||||
|
ConnectionTest,
|
||||||
|
ConnectionTestType,
|
||||||
|
DEFAULT_ALLOWED_EXTENSIONS,
|
||||||
|
DeliveryMode,
|
||||||
|
SourceType,
|
||||||
|
)
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class AccountNotFoundError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_extensions(extensions: list[str] | None) -> list[str]:
|
||||||
|
if not extensions:
|
||||||
|
return list(DEFAULT_ALLOWED_EXTENSIONS)
|
||||||
|
normalized: list[str] = []
|
||||||
|
for ext in extensions:
|
||||||
|
if not ext:
|
||||||
|
continue
|
||||||
|
if not ext.startswith("."):
|
||||||
|
ext = f".{ext}"
|
||||||
|
normalized.append(ext.lower())
|
||||||
|
if not normalized:
|
||||||
|
return list(DEFAULT_ALLOWED_EXTENSIONS)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
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 = {
|
||||||
|
"id": account.id,
|
||||||
|
"name": account.name,
|
||||||
|
"enabled": account.enabled,
|
||||||
|
"sync_interval_minutes": account.sync_interval_minutes,
|
||||||
|
"source_type": source_type,
|
||||||
|
"imap_host": account.imap_host,
|
||||||
|
"imap_port": account.imap_port,
|
||||||
|
"imap_user": account.imap_user,
|
||||||
|
"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,
|
||||||
|
"webdav_min_year": account.webdav_min_year,
|
||||||
|
"delivery_mode": delivery_mode,
|
||||||
|
"smtp_host": account.smtp_host,
|
||||||
|
"smtp_port": account.smtp_port,
|
||||||
|
"smtp_user": account.smtp_user,
|
||||||
|
"smtp_password": mask_password(),
|
||||||
|
"smtp_use_tls": account.smtp_use_tls,
|
||||||
|
"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,
|
||||||
|
"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,
|
||||||
|
}
|
||||||
|
if include_secrets:
|
||||||
|
if account.imap_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
|
||||||
|
|
||||||
|
|
||||||
|
def list_accounts(db: Session) -> list[Account]:
|
||||||
|
return db.query(Account).order_by(Account.id).all()
|
||||||
|
|
||||||
|
|
||||||
|
def get_account(db: Session, account_id: int) -> Account:
|
||||||
|
account = db.get(Account, account_id)
|
||||||
|
if account is None:
|
||||||
|
raise AccountNotFoundError(f"Account {account_id} not found")
|
||||||
|
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:
|
||||||
|
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(
|
||||||
|
name=data["name"],
|
||||||
|
enabled=data.get("enabled", True),
|
||||||
|
sync_interval_minutes=settings_sync if settings_sync is not None else 15,
|
||||||
|
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_user=data.get("imap_user") if source_type == SourceType.imap else None,
|
||||||
|
imap_password_encrypted=(
|
||||||
|
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),
|
||||||
|
webdav_min_year=data.get("webdav_min_year") if source_type == SourceType.webdav else None,
|
||||||
|
delivery_mode=delivery_mode,
|
||||||
|
smtp_host=data.get("smtp_host"),
|
||||||
|
smtp_port=data.get("smtp_port", 587),
|
||||||
|
smtp_user=data.get("smtp_user"),
|
||||||
|
smtp_password_encrypted=(
|
||||||
|
encrypt_password(data["smtp_password"]) if data.get("smtp_password") else None
|
||||||
|
),
|
||||||
|
smtp_use_tls=data.get("smtp_use_tls", True),
|
||||||
|
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),
|
||||||
|
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()
|
||||||
|
db.refresh(account)
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
def update_account(db: Session, account_id: int, data: dict) -> Account:
|
||||||
|
account = get_account(db, account_id)
|
||||||
|
|
||||||
|
for field in (
|
||||||
|
"name",
|
||||||
|
"enabled",
|
||||||
|
"sync_interval_minutes",
|
||||||
|
"imap_host",
|
||||||
|
"imap_port",
|
||||||
|
"imap_user",
|
||||||
|
"webdav_url",
|
||||||
|
"webdav_path",
|
||||||
|
"webdav_user",
|
||||||
|
"webdav_verify_ssl",
|
||||||
|
"webdav_min_year",
|
||||||
|
"smtp_host",
|
||||||
|
"smtp_port",
|
||||||
|
"smtp_user",
|
||||||
|
"smtp_use_tls",
|
||||||
|
"destination_email",
|
||||||
|
"include_all_attachments",
|
||||||
|
"imap_folder_selection_mode",
|
||||||
|
"imap_selected_folders",
|
||||||
|
"bizdocs_email",
|
||||||
|
"bizdocs_company_id",
|
||||||
|
"bizdocs_api_base_url",
|
||||||
|
):
|
||||||
|
if field in data and data[field] is not None:
|
||||||
|
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:
|
||||||
|
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)
|
||||||
|
|
||||||
|
webdav_password = data.get("webdav_password")
|
||||||
|
if webdav_password:
|
||||||
|
account.webdav_password_encrypted = encrypt_password(webdav_password)
|
||||||
|
|
||||||
|
smtp_password = data.get("smtp_password")
|
||||||
|
if 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)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(account)
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
def delete_account(db: Session, account_id: int) -> None:
|
||||||
|
account = get_account(db, account_id)
|
||||||
|
db.delete(account)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_imap_config(db: Session, account_id: int | None, inline: dict | None) -> ImapConfig:
|
||||||
|
if inline:
|
||||||
|
password = inline.get("imap_password") or inline.get("password") or ""
|
||||||
|
if not password and account_id is not None:
|
||||||
|
account = get_account(db, account_id)
|
||||||
|
password = decrypt_password(account.imap_password_encrypted)
|
||||||
|
return ImapConfig(
|
||||||
|
host=inline["imap_host"],
|
||||||
|
port=int(inline.get("imap_port", 993)),
|
||||||
|
user=inline["imap_user"],
|
||||||
|
password=password,
|
||||||
|
)
|
||||||
|
|
||||||
|
if account_id is None:
|
||||||
|
raise ValueError("account_id or inline config required")
|
||||||
|
|
||||||
|
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(
|
||||||
|
host=account.imap_host,
|
||||||
|
port=account.imap_port,
|
||||||
|
user=account.imap_user,
|
||||||
|
password=decrypt_password(account.imap_password_encrypted),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
if inline:
|
||||||
|
password = inline.get("smtp_password") or inline.get("password") or ""
|
||||||
|
if not password and account_id is not None:
|
||||||
|
account = get_account(db, account_id)
|
||||||
|
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(
|
||||||
|
host=host,
|
||||||
|
port=int(inline.get("smtp_port", 587)),
|
||||||
|
user=user,
|
||||||
|
password=password,
|
||||||
|
use_tls=inline.get("smtp_use_tls", True),
|
||||||
|
)
|
||||||
|
|
||||||
|
if account_id is None:
|
||||||
|
raise ValueError("account_id or inline config required")
|
||||||
|
|
||||||
|
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(
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_destination(db: Session, account_id: int | None, inline: dict | None) -> str:
|
||||||
|
if inline and inline.get("destination_email"):
|
||||||
|
return inline["destination_email"]
|
||||||
|
if account_id is None:
|
||||||
|
raise ValueError("destination_email required")
|
||||||
|
account = get_account(db, account_id)
|
||||||
|
return account.destination_email
|
||||||
|
|
||||||
|
|
||||||
|
def record_connection_test(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
account_id: int | None,
|
||||||
|
test_type: ConnectionTestType,
|
||||||
|
success: bool,
|
||||||
|
message: str,
|
||||||
|
) -> ConnectionTest:
|
||||||
|
row = ConnectionTest(
|
||||||
|
account_id=account_id,
|
||||||
|
test_type=test_type,
|
||||||
|
success=success,
|
||||||
|
message=message,
|
||||||
|
)
|
||||||
|
db.add(row)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(row)
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def run_imap_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]:
|
||||||
|
config = resolve_imap_config(db, account_id, inline)
|
||||||
|
success, message = test_imap_connection(config)
|
||||||
|
record_connection_test(
|
||||||
|
db, account_id=account_id, test_type=ConnectionTestType.imap,
|
||||||
|
success=success, message=message,
|
||||||
|
)
|
||||||
|
return success, message
|
||||||
|
|
||||||
|
|
||||||
|
def run_smtp_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]:
|
||||||
|
config = resolve_smtp_config(db, account_id, inline)
|
||||||
|
success, message = test_smtp_connection(config)
|
||||||
|
record_connection_test(
|
||||||
|
db, account_id=account_id, test_type=ConnectionTestType.smtp,
|
||||||
|
success=success, message=message,
|
||||||
|
)
|
||||||
|
return success, message
|
||||||
|
|
||||||
|
|
||||||
|
def run_send_test(db: Session, account_id: int | None, inline: dict | None) -> tuple[bool, str]:
|
||||||
|
config = resolve_smtp_config(db, account_id, inline)
|
||||||
|
destination = resolve_destination(db, account_id, inline)
|
||||||
|
success, message = send_test_email(config, destination)
|
||||||
|
record_connection_test(
|
||||||
|
db, account_id=account_id, test_type=ConnectionTestType.send,
|
||||||
|
success=success, message=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
|
||||||
|
|
||||||
|
|
||||||
|
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),
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import bcrypt
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
from forwarder.db.models import User
|
||||||
|
from forwarder.db.session import get_session_factory
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain: str, hashed: str) -> bool:
|
||||||
|
return bcrypt.checkpw(plain.encode(), hashed.encode())
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_admin_user() -> None:
|
||||||
|
settings = get_settings()
|
||||||
|
db = get_session_factory()()
|
||||||
|
try:
|
||||||
|
existing = db.query(User).filter(User.username == settings.admin_username).first()
|
||||||
|
if existing is not None:
|
||||||
|
return
|
||||||
|
admin = User(
|
||||||
|
username=settings.admin_username,
|
||||||
|
password_hash=hash_password(settings.admin_password),
|
||||||
|
is_admin=True,
|
||||||
|
)
|
||||||
|
db.add(admin)
|
||||||
|
db.commit()
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def authenticate_user(username: str, password: str) -> User | None:
|
||||||
|
db = get_session_factory()()
|
||||||
|
try:
|
||||||
|
user = db.query(User).filter(User.username == username).first()
|
||||||
|
if user is None:
|
||||||
|
return None
|
||||||
|
if not verify_password(password, user.password_hash):
|
||||||
|
return None
|
||||||
|
return user
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
@@ -0,0 +1,219 @@
|
|||||||
|
"""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 (
|
||||||
|
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
|
||||||
|
|
||||||
|
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):
|
||||||
|
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:
|
||||||
|
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)
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""Background forward queue — drains failed messages within rate limits."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
from forwarder.db.models import Message, MessageStatus
|
||||||
|
from forwarder.services.rate_limit import (
|
||||||
|
ForwardRateLimitError,
|
||||||
|
check_forward_allowed,
|
||||||
|
count_forwards_last_hour,
|
||||||
|
forwards_remaining_this_hour,
|
||||||
|
)
|
||||||
|
from forwarder.services.sync_service import (
|
||||||
|
MessageMissingFromMailboxError,
|
||||||
|
retry_single_message,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ForwardQueueResult:
|
||||||
|
attempted: int = 0
|
||||||
|
succeeded: int = 0
|
||||||
|
failed: int = 0
|
||||||
|
rate_limited: bool = False
|
||||||
|
pending_total: int = 0
|
||||||
|
|
||||||
|
def as_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"attempted": self.attempted,
|
||||||
|
"succeeded": self.succeeded,
|
||||||
|
"failed": self.failed,
|
||||||
|
"rate_limited": self.rate_limited,
|
||||||
|
"pending_total": self.pending_total,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def count_queue_pending(db: Session) -> int:
|
||||||
|
return (
|
||||||
|
db.query(Message)
|
||||||
|
.filter(Message.status == MessageStatus.failed)
|
||||||
|
.count()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_queue_status(db: Session) -> dict:
|
||||||
|
settings = get_settings()
|
||||||
|
pending = count_queue_pending(db)
|
||||||
|
used = count_forwards_last_hour(db)
|
||||||
|
remaining = forwards_remaining_this_hour(db)
|
||||||
|
batch = settings.forward_queue_batch_size
|
||||||
|
per_hour = settings.max_forwards_per_hour
|
||||||
|
eta_hours = None
|
||||||
|
if pending > 0 and per_hour > 0:
|
||||||
|
eta_hours = round(pending / per_hour, 1)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"pending": pending,
|
||||||
|
"forwards_used_last_hour": used,
|
||||||
|
"forwards_remaining_this_hour": remaining,
|
||||||
|
"max_forwards_per_hour": per_hour,
|
||||||
|
"batch_size_per_tick": batch,
|
||||||
|
"tick_interval_seconds": settings.forward_queue_interval_seconds,
|
||||||
|
"eta_hours_at_limit": eta_hours,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def requeue_forwarded_messages(db: Session) -> int:
|
||||||
|
"""Mark forwarded messages as failed so the queue re-sends them."""
|
||||||
|
rows = (
|
||||||
|
db.query(Message)
|
||||||
|
.filter(Message.status == MessageStatus.forwarded)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for message in rows:
|
||||||
|
message.status = MessageStatus.failed
|
||||||
|
message.error_message = None
|
||||||
|
db.commit()
|
||||||
|
logger.info("Requeued %s forwarded message(s) for resend", len(rows))
|
||||||
|
return len(rows)
|
||||||
|
|
||||||
|
|
||||||
|
def process_forward_queue(db: Session) -> ForwardQueueResult:
|
||||||
|
"""Send up to batch_size failed messages, respecting the hourly cap."""
|
||||||
|
settings = get_settings()
|
||||||
|
result = ForwardQueueResult(pending_total=count_queue_pending(db))
|
||||||
|
|
||||||
|
if result.pending_total == 0:
|
||||||
|
return result
|
||||||
|
|
||||||
|
remaining = forwards_remaining_this_hour(db)
|
||||||
|
if remaining is not None and remaining <= 0:
|
||||||
|
result.rate_limited = True
|
||||||
|
logger.info("Forward queue idle: hourly limit reached (%s/h)", settings.max_forwards_per_hour)
|
||||||
|
return result
|
||||||
|
|
||||||
|
batch_limit = settings.forward_queue_batch_size
|
||||||
|
if remaining is not None:
|
||||||
|
batch_limit = min(batch_limit, remaining)
|
||||||
|
|
||||||
|
messages = (
|
||||||
|
db.query(Message)
|
||||||
|
.filter(Message.status == MessageStatus.failed)
|
||||||
|
.order_by(Message.id.asc())
|
||||||
|
.limit(batch_limit)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
for message in messages:
|
||||||
|
try:
|
||||||
|
check_forward_allowed(db)
|
||||||
|
retry_single_message(db, message.id)
|
||||||
|
result.succeeded += 1
|
||||||
|
except MessageMissingFromMailboxError as exc:
|
||||||
|
logger.info("Message %s no longer in mailbox: %s", message.id, exc)
|
||||||
|
except ForwardRateLimitError:
|
||||||
|
result.rate_limited = True
|
||||||
|
logger.info("Forward queue paused: hourly limit reached")
|
||||||
|
break
|
||||||
|
except Exception as exc:
|
||||||
|
result.failed += 1
|
||||||
|
logger.error("Forward queue failed for message %s: %s", message.id, exc)
|
||||||
|
result.attempted += 1
|
||||||
|
|
||||||
|
result.pending_total = count_queue_pending(db)
|
||||||
|
if result.attempted:
|
||||||
|
logger.info(
|
||||||
|
"Forward queue tick: %s ok, %s failed, %s pending",
|
||||||
|
result.succeeded,
|
||||||
|
result.failed,
|
||||||
|
result.pending_total,
|
||||||
|
)
|
||||||
|
return result
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Message list search helpers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy import ColumnElement, or_
|
||||||
|
|
||||||
|
from forwarder.db.models import Message
|
||||||
|
|
||||||
|
|
||||||
|
def build_message_search_filter(term: str | None) -> ColumnElement[bool] | None:
|
||||||
|
if term is None:
|
||||||
|
return None
|
||||||
|
cleaned = term.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
|
||||||
|
escaped = cleaned.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||||
|
pattern = f"%{escaped}%"
|
||||||
|
clauses = [
|
||||||
|
Message.subject.like(pattern, escape="\\"),
|
||||||
|
Message.from_addr.like(pattern, escape="\\"),
|
||||||
|
Message.folder.like(pattern, escape="\\"),
|
||||||
|
Message.message_key.like(pattern, escape="\\"),
|
||||||
|
Message.uid.like(pattern, escape="\\"),
|
||||||
|
]
|
||||||
|
if cleaned.isdigit():
|
||||||
|
clauses.append(Message.id == int(cleaned))
|
||||||
|
return or_(*clauses)
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""Outbound SMTP forward rate limiting (protects domain sending reputation)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
from forwarder.db.models import ForwardAttempt
|
||||||
|
|
||||||
|
|
||||||
|
class ForwardRateLimitError(Exception):
|
||||||
|
"""Raised when the hourly forward cap is reached."""
|
||||||
|
|
||||||
|
def __init__(self, *, limit: int, used: int) -> None:
|
||||||
|
self.limit = limit
|
||||||
|
self.used = used
|
||||||
|
super().__init__(f"Forward rate limit reached ({used}/{limit} per hour)")
|
||||||
|
|
||||||
|
|
||||||
|
def count_forwards_last_hour(db: Session) -> int:
|
||||||
|
since = datetime.now(timezone.utc) - timedelta(hours=1)
|
||||||
|
return (
|
||||||
|
db.query(func.count(ForwardAttempt.id))
|
||||||
|
.filter(
|
||||||
|
ForwardAttempt.success.is_(True),
|
||||||
|
ForwardAttempt.dry_run.is_(False),
|
||||||
|
ForwardAttempt.created_at >= since,
|
||||||
|
)
|
||||||
|
.scalar()
|
||||||
|
or 0
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def forwards_remaining_this_hour(db: Session) -> int | None:
|
||||||
|
settings = get_settings()
|
||||||
|
if settings.max_forwards_per_hour <= 0:
|
||||||
|
return None
|
||||||
|
used = count_forwards_last_hour(db)
|
||||||
|
return max(0, settings.max_forwards_per_hour - used)
|
||||||
|
|
||||||
|
|
||||||
|
def check_forward_allowed(db: Session) -> None:
|
||||||
|
settings = get_settings()
|
||||||
|
limit = settings.max_forwards_per_hour
|
||||||
|
if limit <= 0:
|
||||||
|
return
|
||||||
|
used = count_forwards_last_hour(db)
|
||||||
|
if used >= limit:
|
||||||
|
raise ForwardRateLimitError(limit=limit, used=used)
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
"""Orchestrate shop invoice scraping → BizDocs upload."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from forwarder.bizdocs import BizdocsClient, BizdocsCredentials
|
||||||
|
from forwarder.bizdocs.errors import BizdocsError
|
||||||
|
from forwarder.crypto import decrypt_password, encrypt_password
|
||||||
|
from forwarder.db.models import (
|
||||||
|
ScrapedDocument,
|
||||||
|
ScrapedDocumentStatus,
|
||||||
|
ShopAccount,
|
||||||
|
ShopScrapeRun,
|
||||||
|
ShopScrapeRunStatus,
|
||||||
|
)
|
||||||
|
from forwarder.error_reporter import report_error_with_cooldown
|
||||||
|
from forwarder.scrapers import get_scraper
|
||||||
|
from forwarder.scrapers.base import ShopCredentials
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _get_shop_account(db: Session, shop_account_id: int) -> ShopAccount:
|
||||||
|
account = db.get(ShopAccount, shop_account_id)
|
||||||
|
if account is None:
|
||||||
|
raise ValueError(f"ShopAccount {shop_account_id} not found")
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
def _get_processed_order_ids(db: Session, shop_account_id: int) -> set[str]:
|
||||||
|
rows = (
|
||||||
|
db.query(ScrapedDocument.order_id)
|
||||||
|
.filter(
|
||||||
|
ScrapedDocument.shop_account_id == shop_account_id,
|
||||||
|
ScrapedDocument.status == ScrapedDocumentStatus.uploaded,
|
||||||
|
)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {row[0] for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def _upsert_scraped_doc(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
shop_account_id: int,
|
||||||
|
order_id: str,
|
||||||
|
filename: str,
|
||||||
|
status: ScrapedDocumentStatus,
|
||||||
|
bizdocs_doc_id: str | None = None,
|
||||||
|
error_message: str | None = None,
|
||||||
|
) -> ScrapedDocument:
|
||||||
|
doc = (
|
||||||
|
db.query(ScrapedDocument)
|
||||||
|
.filter(
|
||||||
|
ScrapedDocument.shop_account_id == shop_account_id,
|
||||||
|
ScrapedDocument.order_id == order_id,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if doc is None:
|
||||||
|
doc = ScrapedDocument(
|
||||||
|
shop_account_id=shop_account_id,
|
||||||
|
order_id=order_id,
|
||||||
|
)
|
||||||
|
db.add(doc)
|
||||||
|
doc.filename = filename
|
||||||
|
doc.status = status
|
||||||
|
doc.bizdocs_doc_id = bizdocs_doc_id
|
||||||
|
doc.error_message = error_message
|
||||||
|
db.commit()
|
||||||
|
db.refresh(doc)
|
||||||
|
return doc
|
||||||
|
|
||||||
|
|
||||||
|
def scrape_shop_account(db: Session, shop_account_id: int) -> ShopScrapeRun:
|
||||||
|
"""
|
||||||
|
Run one scrape cycle for a ShopAccount.
|
||||||
|
|
||||||
|
Fetches new invoices from the shop, uploads them to BizDocs,
|
||||||
|
and records results in the DB.
|
||||||
|
|
||||||
|
Returns the ShopScrapeRun record.
|
||||||
|
"""
|
||||||
|
account = _get_shop_account(db, shop_account_id)
|
||||||
|
run = ShopScrapeRun(
|
||||||
|
shop_account_id=shop_account_id,
|
||||||
|
status=ShopScrapeRunStatus.running,
|
||||||
|
)
|
||||||
|
db.add(run)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(run)
|
||||||
|
|
||||||
|
try:
|
||||||
|
_run_scrape(db, account, run)
|
||||||
|
run.status = ShopScrapeRunStatus.completed
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Scrape failed for shop account %s", shop_account_id)
|
||||||
|
run.status = ShopScrapeRunStatus.failed
|
||||||
|
run.error_message = str(exc)
|
||||||
|
report_error_with_cooldown(
|
||||||
|
f"scraper:shop_account:{shop_account_id}",
|
||||||
|
300.0,
|
||||||
|
exc,
|
||||||
|
severity="error",
|
||||||
|
context_data={"shop_account_id": shop_account_id},
|
||||||
|
endpoint="scraper_service:scrape_shop_account",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
run.finished_at = datetime.now(tz=timezone.utc)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(run)
|
||||||
|
|
||||||
|
return run
|
||||||
|
|
||||||
|
|
||||||
|
def _run_scrape(db: Session, account: ShopAccount, run: ShopScrapeRun) -> None:
|
||||||
|
"""Inner scrape loop — raises on unrecoverable errors."""
|
||||||
|
# Build shop credentials
|
||||||
|
credentials = ShopCredentials(
|
||||||
|
email=decrypt_password(account.shop_email_encrypted or ""),
|
||||||
|
password=decrypt_password(account.shop_password_encrypted or ""),
|
||||||
|
session_state_json=(
|
||||||
|
decrypt_password(account.session_state_encrypted)
|
||||||
|
if account.session_state_encrypted
|
||||||
|
else None
|
||||||
|
),
|
||||||
|
extra={},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build BizDocs client
|
||||||
|
bizdocs_password = decrypt_password(account.bizdocs_password_encrypted or "")
|
||||||
|
|
||||||
|
bizdocs_creds = BizdocsCredentials(
|
||||||
|
email=account.bizdocs_email or "",
|
||||||
|
password=bizdocs_password or "",
|
||||||
|
company_id=account.bizdocs_company_id or "",
|
||||||
|
api_base_url=account.bizdocs_api_base_url,
|
||||||
|
)
|
||||||
|
bizdocs = BizdocsClient()
|
||||||
|
bizdocs_session = bizdocs.login(bizdocs_creds)
|
||||||
|
|
||||||
|
# Already-uploaded order IDs — skip them
|
||||||
|
processed = _get_processed_order_ids(db, account.id)
|
||||||
|
|
||||||
|
scraper = get_scraper(account.shop_type.value, credentials)
|
||||||
|
|
||||||
|
async def _run_async():
|
||||||
|
nonlocal run
|
||||||
|
async for doc in scraper.iter_invoices(since=account.last_scraped_at, max_orders=200):
|
||||||
|
run.orders_found += 1
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
if doc.order_id in processed:
|
||||||
|
logger.debug("Skipping already-uploaded order %s", doc.order_id)
|
||||||
|
run.invoices_skipped += 1
|
||||||
|
_upsert_scraped_doc(
|
||||||
|
db,
|
||||||
|
shop_account_id=account.id,
|
||||||
|
order_id=doc.order_id,
|
||||||
|
filename=doc.filename,
|
||||||
|
status=ScrapedDocumentStatus.skipped,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
doc_id = bizdocs.upload_document(
|
||||||
|
bizdocs_session,
|
||||||
|
company_id=bizdocs_creds.company_id,
|
||||||
|
filename=doc.filename,
|
||||||
|
data=doc.data,
|
||||||
|
)
|
||||||
|
run.invoices_uploaded += 1
|
||||||
|
logger.info(
|
||||||
|
"Uploaded %s → bizdocs doc %s (order %s)",
|
||||||
|
doc.filename,
|
||||||
|
doc_id,
|
||||||
|
doc.order_id,
|
||||||
|
)
|
||||||
|
_upsert_scraped_doc(
|
||||||
|
db,
|
||||||
|
shop_account_id=account.id,
|
||||||
|
order_id=doc.order_id,
|
||||||
|
filename=doc.filename,
|
||||||
|
status=ScrapedDocumentStatus.uploaded,
|
||||||
|
bizdocs_doc_id=doc_id,
|
||||||
|
)
|
||||||
|
except BizdocsError as exc:
|
||||||
|
run.invoices_failed += 1
|
||||||
|
logger.error(
|
||||||
|
"BizDocs upload failed for order %s: %s", doc.order_id, exc
|
||||||
|
)
|
||||||
|
_upsert_scraped_doc(
|
||||||
|
db,
|
||||||
|
shop_account_id=account.id,
|
||||||
|
order_id=doc.order_id,
|
||||||
|
filename=doc.filename,
|
||||||
|
status=ScrapedDocumentStatus.failed,
|
||||||
|
error_message=str(exc),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
asyncio.run(_run_async())
|
||||||
|
|
||||||
|
# Persist updated session state (cookies refreshed during scrape)
|
||||||
|
updated_state = scraper.get_updated_session_state()
|
||||||
|
if updated_state:
|
||||||
|
account.session_state_encrypted = encrypt_password(updated_state)
|
||||||
|
account.session_state_saved_at = datetime.now(tz=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
account.last_scraped_at = datetime.now(tz=timezone.utc)
|
||||||
|
db.commit()
|
||||||
@@ -0,0 +1,576 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import imaplib
|
||||||
|
import logging
|
||||||
|
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,
|
||||||
|
ForwardAttempt,
|
||||||
|
Message,
|
||||||
|
MessageStatus,
|
||||||
|
SourceType,
|
||||||
|
SyncRun,
|
||||||
|
SyncRunStatus,
|
||||||
|
)
|
||||||
|
from forwarder.email.imap_client import (
|
||||||
|
connect_imap,
|
||||||
|
fetch_message,
|
||||||
|
folder_should_be_scanned,
|
||||||
|
list_mailboxes,
|
||||||
|
select_folder_readonly,
|
||||||
|
ImapConfig,
|
||||||
|
)
|
||||||
|
from forwarder.email.parsing import (
|
||||||
|
clean_subject,
|
||||||
|
get_message_key,
|
||||||
|
has_matching_attachment,
|
||||||
|
)
|
||||||
|
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client
|
||||||
|
from forwarder.error_reporter import report_error, report_error_with_cooldown
|
||||||
|
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
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class MessageMissingFromMailboxError(Exception):
|
||||||
|
"""The message record exists but the email is no longer on IMAP."""
|
||||||
|
|
||||||
|
def __init__(self, message: Message, reason: str) -> None:
|
||||||
|
self.message = message
|
||||||
|
super().__init__(reason)
|
||||||
|
|
||||||
|
|
||||||
|
def is_missing_from_mailbox_error(error_text: str) -> bool:
|
||||||
|
if error_text.startswith("Could not fetch message UID"):
|
||||||
|
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:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.messages_scanned = 0
|
||||||
|
self.messages_matched = 0
|
||||||
|
self.messages_forwarded = 0
|
||||||
|
self.messages_skipped = 0
|
||||||
|
self.messages_failed = 0
|
||||||
|
|
||||||
|
|
||||||
|
def _get_known_message_keys(db: Session, account_id: int) -> set[str]:
|
||||||
|
"""Message-IDs already in DB — sync skips them; retries use the queue."""
|
||||||
|
rows = (
|
||||||
|
db.query(Message.message_key)
|
||||||
|
.filter(Message.account_id == account_id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return {row[0] for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def _upsert_message(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
account_id: int,
|
||||||
|
message_key: str,
|
||||||
|
folder: str,
|
||||||
|
uid: str,
|
||||||
|
subject: str,
|
||||||
|
from_addr: str,
|
||||||
|
date: str,
|
||||||
|
status: MessageStatus,
|
||||||
|
error_message: str | None = None,
|
||||||
|
bizdocs_doc_id: str | None = None,
|
||||||
|
) -> Message:
|
||||||
|
existing = (
|
||||||
|
db.query(Message)
|
||||||
|
.filter(Message.account_id == account_id, Message.message_key == message_key)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if existing is not None:
|
||||||
|
existing.status = status
|
||||||
|
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)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(existing)
|
||||||
|
return existing
|
||||||
|
|
||||||
|
msg = Message(
|
||||||
|
account_id=account_id,
|
||||||
|
message_key=message_key,
|
||||||
|
folder=folder,
|
||||||
|
uid=uid,
|
||||||
|
subject=subject,
|
||||||
|
from_addr=from_addr,
|
||||||
|
date=date,
|
||||||
|
status=status,
|
||||||
|
error_message=error_message,
|
||||||
|
bizdocs_doc_id=bizdocs_doc_id,
|
||||||
|
)
|
||||||
|
db.add(msg)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(msg)
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
def _record_forward_attempt(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
message: Message,
|
||||||
|
success: bool,
|
||||||
|
dry_run: bool,
|
||||||
|
error_message: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
attempt = ForwardAttempt(
|
||||||
|
message_id=message.id,
|
||||||
|
success=success,
|
||||||
|
dry_run=dry_run,
|
||||||
|
error_message=error_message,
|
||||||
|
)
|
||||||
|
db.add(attempt)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def sync_account(
|
||||||
|
db: Session,
|
||||||
|
account_id: int,
|
||||||
|
*,
|
||||||
|
dry_run: bool = False,
|
||||||
|
max_emails: int | None = None,
|
||||||
|
) -> SyncRun:
|
||||||
|
account = get_account(db, account_id)
|
||||||
|
sync_run = SyncRun(
|
||||||
|
account_id=account_id,
|
||||||
|
status=SyncRunStatus.running,
|
||||||
|
dry_run=dry_run,
|
||||||
|
max_emails=max_emails,
|
||||||
|
)
|
||||||
|
db.add(sync_run)
|
||||||
|
db.commit()
|
||||||
|
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()
|
||||||
|
imap = None
|
||||||
|
smtp = None
|
||||||
|
bizdocs_session = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
imap_config = ImapConfig(
|
||||||
|
host=account.imap_host,
|
||||||
|
port=account.imap_port,
|
||||||
|
user=account.imap_user,
|
||||||
|
password=decrypt_password(account.imap_password_encrypted),
|
||||||
|
)
|
||||||
|
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)
|
||||||
|
|
||||||
|
allowed_extensions = set(
|
||||||
|
account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS)
|
||||||
|
)
|
||||||
|
processed_keys = _get_known_message_keys(db, account_id)
|
||||||
|
stop_all = False
|
||||||
|
|
||||||
|
imap = connect_imap(imap_config)
|
||||||
|
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)
|
||||||
|
|
||||||
|
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 not folder_should_be_scanned(
|
||||||
|
folder,
|
||||||
|
selection_mode=selection_mode,
|
||||||
|
selected_folders=selected_folders,
|
||||||
|
):
|
||||||
|
logger.debug("Skipping folder: %s", folder)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
if not select_folder_readonly(imap, folder):
|
||||||
|
logger.warning("Could not open folder: %s", folder)
|
||||||
|
continue
|
||||||
|
except imaplib.IMAP4.error as exc:
|
||||||
|
logger.warning("Could not open folder %s: %s", folder, exc)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
status, data = imap.uid("search", None, "ALL")
|
||||||
|
except imaplib.IMAP4.error as exc:
|
||||||
|
logger.warning("Search failed in %s: %s", folder, exc)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if status != "OK" or not data or not data[0]:
|
||||||
|
continue
|
||||||
|
|
||||||
|
uids = data[0].split()
|
||||||
|
|
||||||
|
for uid in uids:
|
||||||
|
if max_emails is not None and result.messages_scanned >= max_emails:
|
||||||
|
stop_all = True
|
||||||
|
break
|
||||||
|
|
||||||
|
result.messages_scanned += 1
|
||||||
|
uid_str = uid.decode() if isinstance(uid, bytes) else str(uid)
|
||||||
|
|
||||||
|
try:
|
||||||
|
msg = fetch_message(imap, uid)
|
||||||
|
except (imaplib.IMAP4.error, OSError) as exc:
|
||||||
|
logger.error("Fetch error UID %s in %s: %s", uid_str, folder, exc)
|
||||||
|
result.messages_failed += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
if msg is None:
|
||||||
|
result.messages_failed += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
message_key = get_message_key(folder, uid, msg)
|
||||||
|
subject = clean_subject(msg.get("Subject"))
|
||||||
|
from_addr = msg.get("From", "") or ""
|
||||||
|
date = msg.get("Date", "") or ""
|
||||||
|
|
||||||
|
if message_key in processed_keys:
|
||||||
|
result.messages_skipped += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not has_matching_attachment(
|
||||||
|
msg,
|
||||||
|
include_all_attachments=account.include_all_attachments,
|
||||||
|
allowed_extensions=allowed_extensions,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
result.messages_matched += 1
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
message_row = _upsert_message(
|
||||||
|
db,
|
||||||
|
account_id=account_id,
|
||||||
|
message_key=message_key,
|
||||||
|
folder=folder,
|
||||||
|
uid=uid_str,
|
||||||
|
subject=subject,
|
||||||
|
from_addr=from_addr,
|
||||||
|
date=date,
|
||||||
|
status=MessageStatus.dry_run,
|
||||||
|
)
|
||||||
|
_record_forward_attempt(
|
||||||
|
db, message=message_row, success=True, dry_run=True,
|
||||||
|
)
|
||||||
|
processed_keys.add(message_key)
|
||||||
|
result.messages_forwarded += 1
|
||||||
|
logger.info("DRY_RUN matched: %s", subject)
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
check_forward_allowed(db)
|
||||||
|
doc_ids = deliver_message_attachments(
|
||||||
|
msg,
|
||||||
|
account,
|
||||||
|
bizdocs_password=bizdocs_password,
|
||||||
|
smtp_config=smtp_config,
|
||||||
|
smtp=smtp,
|
||||||
|
bizdocs_session=bizdocs_session,
|
||||||
|
)
|
||||||
|
doc_id_str = ",".join(doc_ids) if doc_ids else None
|
||||||
|
message_row = _upsert_message(
|
||||||
|
db,
|
||||||
|
account_id=account_id,
|
||||||
|
message_key=message_key,
|
||||||
|
folder=folder,
|
||||||
|
uid=uid_str,
|
||||||
|
subject=subject,
|
||||||
|
from_addr=from_addr,
|
||||||
|
date=date,
|
||||||
|
status=MessageStatus.forwarded,
|
||||||
|
bizdocs_doc_id=doc_id_str,
|
||||||
|
)
|
||||||
|
_record_forward_attempt(
|
||||||
|
db, message=message_row, success=True, dry_run=False,
|
||||||
|
)
|
||||||
|
processed_keys.add(message_key)
|
||||||
|
result.messages_forwarded += 1
|
||||||
|
logger.info("Forwarded: %s", subject)
|
||||||
|
except ForwardRateLimitError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Hourly forward limit reached, skipping forward (scan continues): %s",
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
message_row = _upsert_message(
|
||||||
|
db,
|
||||||
|
account_id=account_id,
|
||||||
|
message_key=message_key,
|
||||||
|
folder=folder,
|
||||||
|
uid=uid_str,
|
||||||
|
subject=subject,
|
||||||
|
from_addr=from_addr,
|
||||||
|
date=date,
|
||||||
|
status=MessageStatus.failed,
|
||||||
|
error_message=str(exc),
|
||||||
|
)
|
||||||
|
_record_forward_attempt(
|
||||||
|
db,
|
||||||
|
message=message_row,
|
||||||
|
success=False,
|
||||||
|
dry_run=False,
|
||||||
|
error_message=str(exc),
|
||||||
|
)
|
||||||
|
processed_keys.add(message_key)
|
||||||
|
result.messages_failed += 1
|
||||||
|
except Exception as exc:
|
||||||
|
error_text = str(exc)
|
||||||
|
logger.error("Forward failed for %s: %s", subject, error_text)
|
||||||
|
report_error(
|
||||||
|
exc,
|
||||||
|
context_data={
|
||||||
|
"account_id": account_id,
|
||||||
|
"subject": subject,
|
||||||
|
"folder": folder,
|
||||||
|
"uid": uid_str,
|
||||||
|
},
|
||||||
|
endpoint="sync:forward_email",
|
||||||
|
)
|
||||||
|
message_row = _upsert_message(
|
||||||
|
db,
|
||||||
|
account_id=account_id,
|
||||||
|
message_key=message_key,
|
||||||
|
folder=folder,
|
||||||
|
uid=uid_str,
|
||||||
|
subject=subject,
|
||||||
|
from_addr=from_addr,
|
||||||
|
date=date,
|
||||||
|
status=MessageStatus.failed,
|
||||||
|
error_message=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("Sync failed for account %s", account_id)
|
||||||
|
report_error_with_cooldown(
|
||||||
|
f"sync_account:{account_id}",
|
||||||
|
300.0,
|
||||||
|
exc,
|
||||||
|
severity="error",
|
||||||
|
context_data={"account_id": account_id},
|
||||||
|
endpoint="sync:account",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
if imap is not None:
|
||||||
|
try:
|
||||||
|
imap.logout()
|
||||||
|
except (imaplib.IMAP4.error, OSError):
|
||||||
|
pass
|
||||||
|
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 _mark_missing_from_mailbox(db: Session, message: Message, reason: str) -> Message:
|
||||||
|
message.status = MessageStatus.missing_from_mailbox
|
||||||
|
message.error_message = reason
|
||||||
|
message.updated_at = datetime.now(timezone.utc)
|
||||||
|
_record_forward_attempt(
|
||||||
|
db,
|
||||||
|
message=message,
|
||||||
|
success=False,
|
||||||
|
dry_run=False,
|
||||||
|
error_message=reason,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(message)
|
||||||
|
logger.info("Message %s missing from mailbox: %s", message.id, reason)
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
|
def retry_single_message(db: Session, message_id: int) -> Message:
|
||||||
|
message = db.get(Message, message_id)
|
||||||
|
if message is None:
|
||||||
|
raise ValueError(f"Message {message_id} not found")
|
||||||
|
if message.status == MessageStatus.forwarded:
|
||||||
|
raise ValueError("Message already forwarded")
|
||||||
|
if message.status == MessageStatus.missing_from_mailbox:
|
||||||
|
raise MessageMissingFromMailboxError(
|
||||||
|
message,
|
||||||
|
message.error_message or "Message no longer in mailbox",
|
||||||
|
)
|
||||||
|
|
||||||
|
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(
|
||||||
|
host=account.imap_host,
|
||||||
|
port=account.imap_port,
|
||||||
|
user=account.imap_user,
|
||||||
|
password=decrypt_password(account.imap_password_encrypted),
|
||||||
|
)
|
||||||
|
smtp_config = None
|
||||||
|
bizdocs_password = None
|
||||||
|
if account.delivery_mode == DeliveryMode.smtp:
|
||||||
|
smtp_config = SmtpConfig(
|
||||||
|
host=account.smtp_host or "",
|
||||||
|
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
|
||||||
|
smtp = None
|
||||||
|
bizdocs_session = None
|
||||||
|
try:
|
||||||
|
imap = connect_imap(imap_config)
|
||||||
|
if not select_folder_readonly(imap, message.folder):
|
||||||
|
marked = _mark_missing_from_mailbox(
|
||||||
|
db,
|
||||||
|
message,
|
||||||
|
f"Could not open folder: {message.folder}",
|
||||||
|
)
|
||||||
|
raise MessageMissingFromMailboxError(marked, marked.error_message or "")
|
||||||
|
|
||||||
|
uid_bytes = message.uid.encode() if isinstance(message.uid, str) else message.uid
|
||||||
|
msg = fetch_message(imap, uid_bytes)
|
||||||
|
if msg is None:
|
||||||
|
marked = _mark_missing_from_mailbox(
|
||||||
|
db,
|
||||||
|
message,
|
||||||
|
f"Could not fetch message UID {message.uid}",
|
||||||
|
)
|
||||||
|
raise MessageMissingFromMailboxError(marked, marked.error_message or "")
|
||||||
|
|
||||||
|
smtp = None
|
||||||
|
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_message_attachments(
|
||||||
|
msg,
|
||||||
|
account,
|
||||||
|
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("Retry forwarded: %s", message.subject)
|
||||||
|
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},
|
||||||
|
endpoint="messages:retry",
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
if imap is not None:
|
||||||
|
try:
|
||||||
|
imap.logout()
|
||||||
|
except (imaplib.IMAP4.error, OSError):
|
||||||
|
pass
|
||||||
|
if smtp is not None:
|
||||||
|
try:
|
||||||
|
smtp.quit()
|
||||||
|
except smtplib.SMTPException:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,467 @@
|
|||||||
|
"""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 (
|
||||||
|
MIN_WEBDAV_FILE_BYTES,
|
||||||
|
WebdavConfig,
|
||||||
|
WebdavNotFoundError,
|
||||||
|
download_file,
|
||||||
|
get_webdav_message_key,
|
||||||
|
list_files,
|
||||||
|
normalize_webdav_folder_path,
|
||||||
|
parse_webdav_message_key,
|
||||||
|
webdav_bytes_below_min_size,
|
||||||
|
webdav_file_below_min_size,
|
||||||
|
webdav_file_matches_min_year,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _skip_too_small_webdav_file(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
account_id: int,
|
||||||
|
message_key: str,
|
||||||
|
folder_label: str,
|
||||||
|
uid: str,
|
||||||
|
subject: str,
|
||||||
|
from_addr: str,
|
||||||
|
date: str,
|
||||||
|
size_bytes: int,
|
||||||
|
processed_keys: set[str],
|
||||||
|
result: SyncResult,
|
||||||
|
) -> None:
|
||||||
|
error_message = (
|
||||||
|
f"skipped: file too small ({size_bytes} bytes, min {MIN_WEBDAV_FILE_BYTES})"
|
||||||
|
)
|
||||||
|
_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.skipped,
|
||||||
|
error_message=error_message,
|
||||||
|
)
|
||||||
|
processed_keys.add(message_key)
|
||||||
|
result.messages_skipped += 1
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
if not webdav_file_matches_min_year(
|
||||||
|
remote_file,
|
||||||
|
account.webdav_min_year,
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
message_key = get_webdav_message_key(remote_file.relative_path)
|
||||||
|
if message_key in processed_keys:
|
||||||
|
result.messages_skipped += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
uid = remote_file.etag or str(remote_file.size)
|
||||||
|
subject = filename
|
||||||
|
from_addr = source_label = f"webdav:{account.webdav_url}"
|
||||||
|
date = remote_file.modified or ""
|
||||||
|
|
||||||
|
if webdav_file_below_min_size(remote_file):
|
||||||
|
_skip_too_small_webdav_file(
|
||||||
|
db,
|
||||||
|
account_id=account_id,
|
||||||
|
message_key=message_key,
|
||||||
|
folder_label=folder_label,
|
||||||
|
uid=uid,
|
||||||
|
subject=subject,
|
||||||
|
from_addr=from_addr,
|
||||||
|
date=date,
|
||||||
|
size_bytes=remote_file.size,
|
||||||
|
processed_keys=processed_keys,
|
||||||
|
result=result,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"WebDAV skipped (too small, PROPFIND): %s (%d bytes)",
|
||||||
|
remote_file.relative_path,
|
||||||
|
remote_file.size,
|
||||||
|
)
|
||||||
|
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
|
||||||
|
|
||||||
|
if webdav_bytes_below_min_size(data):
|
||||||
|
_skip_too_small_webdav_file(
|
||||||
|
db,
|
||||||
|
account_id=account_id,
|
||||||
|
message_key=message_key,
|
||||||
|
folder_label=folder_label,
|
||||||
|
uid=uid,
|
||||||
|
subject=subject,
|
||||||
|
from_addr=from_addr,
|
||||||
|
date=date,
|
||||||
|
size_bytes=len(data),
|
||||||
|
processed_keys=processed_keys,
|
||||||
|
result=result,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"WebDAV skipped (too small): %s (%d bytes)",
|
||||||
|
remote_file.relative_path,
|
||||||
|
len(data),
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
result.messages_matched += 1
|
||||||
|
|
||||||
|
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 webdav_bytes_below_min_size(data):
|
||||||
|
message.status = MessageStatus.skipped
|
||||||
|
message.error_message = (
|
||||||
|
f"skipped: file too small ({len(data)} bytes, min {MIN_WEBDAV_FILE_BYTES})"
|
||||||
|
)
|
||||||
|
message.updated_at = datetime.now(timezone.utc)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(message)
|
||||||
|
logger.info("WebDAV retry skipped (too small): %s", relative_path)
|
||||||
|
return message
|
||||||
|
|
||||||
|
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
|
||||||
@@ -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",
|
||||||
|
]
|
||||||
@@ -0,0 +1,457 @@
|
|||||||
|
"""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 datetime import datetime, timezone
|
||||||
|
from email.utils import parsedate_to_datetime
|
||||||
|
from urllib.parse import quote, unquote, urljoin, urlparse
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Reject HTML stubs / placeholders before download when PROPFIND reports size.
|
||||||
|
MIN_WEBDAV_FILE_BYTES = 4 * 1024
|
||||||
|
WEBDAV_LIST_TIMEOUT_SECONDS = 180.0
|
||||||
|
|
||||||
|
OC_NS = "{http://owncloud.org/ns}"
|
||||||
|
NC_NS = "{http://nextcloud.org/ns}"
|
||||||
|
DAV_NS = "{DAV:}"
|
||||||
|
|
||||||
|
PROPFIND_BODY = b"""<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<D:propfind xmlns:D="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:nc="http://nextcloud.org/ns">
|
||||||
|
<D:prop>
|
||||||
|
<D:displayname/>
|
||||||
|
<D:getetag/>
|
||||||
|
<D:getcontentlength/>
|
||||||
|
<D:getlastmodified/>
|
||||||
|
<D:creationdate/>
|
||||||
|
<oc:creation-time/>
|
||||||
|
<nc:creation-time/>
|
||||||
|
<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
|
||||||
|
created: str
|
||||||
|
oc_creation_time: str
|
||||||
|
nc_creation_time: 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 webdav_year_folder(relative_path: str) -> str | None:
|
||||||
|
for part in relative_path.strip("/").split("/"):
|
||||||
|
if len(part) == 4 and part.isdigit():
|
||||||
|
return part
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_webdav_http_date(value: str) -> datetime | None:
|
||||||
|
cleaned = value.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
parsed = parsedate_to_datetime(cleaned)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
if parsed.tzinfo is None:
|
||||||
|
return parsed.replace(tzinfo=timezone.utc)
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
|
||||||
|
def parse_webdav_iso_date(value: str) -> datetime | None:
|
||||||
|
cleaned = value.strip()
|
||||||
|
if not cleaned:
|
||||||
|
return None
|
||||||
|
if cleaned.endswith("Z"):
|
||||||
|
cleaned = cleaned[:-1] + "+00:00"
|
||||||
|
try:
|
||||||
|
parsed = datetime.fromisoformat(cleaned)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if parsed.tzinfo is None:
|
||||||
|
return parsed.replace(tzinfo=timezone.utc)
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
|
||||||
|
def webdav_file_reference_date(file: WebdavFile) -> datetime | None:
|
||||||
|
"""Reference date for year filtering.
|
||||||
|
|
||||||
|
Nextcloud often returns DAV:creationdate as Unix epoch (1970) for bulk-imported
|
||||||
|
files. Prefer getlastmodified (upload time on server), then oc/nc creation-time,
|
||||||
|
then creationdate when trustworthy.
|
||||||
|
"""
|
||||||
|
modified = parse_webdav_http_date(file.modified)
|
||||||
|
if modified is not None:
|
||||||
|
return modified
|
||||||
|
|
||||||
|
for raw in (file.oc_creation_time, file.nc_creation_time, file.created):
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
parsed = parse_webdav_iso_date(raw)
|
||||||
|
if parsed is not None and not _is_untrusted_webdav_date(parsed):
|
||||||
|
return parsed
|
||||||
|
parsed = parse_webdav_http_date(raw)
|
||||||
|
if parsed is not None and not _is_untrusted_webdav_date(parsed):
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _is_untrusted_webdav_date(value: datetime) -> bool:
|
||||||
|
"""Nextcloud often reports missing creation as Unix epoch (1970)."""
|
||||||
|
return value.year <= 1971
|
||||||
|
|
||||||
|
|
||||||
|
def webdav_folder_year_meets_min_year(relative_path: str, min_year: int) -> bool:
|
||||||
|
folder_year = webdav_year_folder(relative_path)
|
||||||
|
if folder_year is None:
|
||||||
|
return False
|
||||||
|
return int(folder_year) >= min_year
|
||||||
|
|
||||||
|
|
||||||
|
def webdav_min_year_cutoff(min_year: int) -> datetime:
|
||||||
|
return datetime(min_year, 1, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def webdav_file_matches_min_year(file: WebdavFile, min_year: int | None) -> bool:
|
||||||
|
if min_year is None:
|
||||||
|
return True
|
||||||
|
|
||||||
|
if webdav_folder_year_meets_min_year(file.relative_path, min_year):
|
||||||
|
return True
|
||||||
|
|
||||||
|
reference_date = webdav_file_reference_date(file)
|
||||||
|
if reference_date is None:
|
||||||
|
return False
|
||||||
|
return reference_date >= webdav_min_year_cutoff(min_year)
|
||||||
|
|
||||||
|
|
||||||
|
def webdav_file_below_min_size(
|
||||||
|
file: WebdavFile,
|
||||||
|
min_bytes: int = MIN_WEBDAV_FILE_BYTES,
|
||||||
|
) -> bool:
|
||||||
|
"""True when PROPFIND size is known and below min_bytes (size 0 = unknown)."""
|
||||||
|
if file.size <= 0:
|
||||||
|
return False
|
||||||
|
return file.size < min_bytes
|
||||||
|
|
||||||
|
|
||||||
|
def webdav_bytes_below_min_size(
|
||||||
|
data: bytes,
|
||||||
|
min_bytes: int = MIN_WEBDAV_FILE_BYTES,
|
||||||
|
) -> bool:
|
||||||
|
return len(data) < min_bytes
|
||||||
|
|
||||||
|
|
||||||
|
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, ns: str = DAV_NS) -> str:
|
||||||
|
node = parent.find(f"{ns}{tag}")
|
||||||
|
if node is None or node.text is None:
|
||||||
|
return ""
|
||||||
|
return node.text.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _propstat_ok(propstat: element_tree.Element) -> bool:
|
||||||
|
status = _element_text(propstat, "status")
|
||||||
|
if not status:
|
||||||
|
return True
|
||||||
|
return " 200 " in status or status.endswith(" 200 OK")
|
||||||
|
|
||||||
|
|
||||||
|
def _select_propstat(response_elem: element_tree.Element) -> element_tree.Element | None:
|
||||||
|
propstats = response_elem.findall(f"{DAV_NS}propstat")
|
||||||
|
if not propstats:
|
||||||
|
return None
|
||||||
|
for propstat in propstats:
|
||||||
|
if _propstat_ok(propstat):
|
||||||
|
return propstat
|
||||||
|
return propstats[0]
|
||||||
|
|
||||||
|
|
||||||
|
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 = _select_propstat(response_elem)
|
||||||
|
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")
|
||||||
|
created = _element_text(prop, "creationdate")
|
||||||
|
oc_creation_time = _element_text(prop, "creation-time", OC_NS)
|
||||||
|
nc_creation_time = _element_text(prop, "creation-time", NC_NS)
|
||||||
|
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,
|
||||||
|
created=created,
|
||||||
|
oc_creation_time=oc_creation_time,
|
||||||
|
nc_creation_time=nc_creation_time,
|
||||||
|
size=size,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
def _propfind(
|
||||||
|
client: httpx.Client,
|
||||||
|
url: str,
|
||||||
|
depth: str,
|
||||||
|
) -> httpx.Response:
|
||||||
|
headers = {"Depth": depth, "Content-Type": "application/xml; charset=utf-8"}
|
||||||
|
return client.request("PROPFIND", url, content=PROPFIND_BODY, headers=headers)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_propfind_collections(root_url: str, content: bytes) -> list[str]:
|
||||||
|
"""Return absolute URLs of child collections (excluding root) in a PROPFIND body."""
|
||||||
|
try:
|
||||||
|
root = element_tree.fromstring(content)
|
||||||
|
except element_tree.ParseError as exc:
|
||||||
|
raise WebdavError("Invalid PROPFIND XML response") from exc
|
||||||
|
|
||||||
|
base = root_url.rstrip("/") + "/"
|
||||||
|
children: list[str] = []
|
||||||
|
for response_elem in root.findall(f"{DAV_NS}response"):
|
||||||
|
if not _is_collection(response_elem):
|
||||||
|
continue
|
||||||
|
href = _element_text(response_elem, "href")
|
||||||
|
if not href:
|
||||||
|
continue
|
||||||
|
absolute = href if href.startswith("http") else urljoin(base, href)
|
||||||
|
if absolute.rstrip("/") == root_url.rstrip("/"):
|
||||||
|
continue
|
||||||
|
if absolute.startswith(base):
|
||||||
|
children.append(absolute)
|
||||||
|
return children
|
||||||
|
|
||||||
|
|
||||||
|
def _list_files_depth_one_recursive(config: WebdavConfig) -> list[WebdavFile]:
|
||||||
|
"""Recursive Depth:1 traversal for servers that reject Depth: infinity."""
|
||||||
|
root_url = build_webdav_root(config)
|
||||||
|
files: list[WebdavFile] = []
|
||||||
|
seen_collections: set[str] = set()
|
||||||
|
|
||||||
|
with _client(config, timeout=WEBDAV_LIST_TIMEOUT_SECONDS) as client:
|
||||||
|
queue: list[str] = [root_url]
|
||||||
|
while queue:
|
||||||
|
url = queue.pop(0)
|
||||||
|
response = _propfind(client, url, "1")
|
||||||
|
if response.status_code == 404:
|
||||||
|
raise WebdavNotFoundError(f"WebDAV folder not found: {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]}"
|
||||||
|
)
|
||||||
|
files.extend(_parse_propfind_response(root_url, response.content))
|
||||||
|
for child in _parse_propfind_collections(url, response.content):
|
||||||
|
if child not in seen_collections:
|
||||||
|
seen_collections.add(child)
|
||||||
|
queue.append(child)
|
||||||
|
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
# Status codes that typically indicate "Depth: infinity not supported".
|
||||||
|
_DEPTH_INFINITY_UNSUPPORTED = {403, 500, 501}
|
||||||
|
|
||||||
|
|
||||||
|
def list_files(config: WebdavConfig) -> list[WebdavFile]:
|
||||||
|
root_url = build_webdav_root(config)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with _client(config, timeout=WEBDAV_LIST_TIMEOUT_SECONDS) as client:
|
||||||
|
response = _propfind(client, root_url, "infinity")
|
||||||
|
except httpx.TimeoutException as exc:
|
||||||
|
raise WebdavError(
|
||||||
|
f"PROPFIND timed out after {WEBDAV_LIST_TIMEOUT_SECONDS:.0f}s: {root_url}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
if response.status_code in _DEPTH_INFINITY_UNSUPPORTED:
|
||||||
|
logger.warning(
|
||||||
|
"WebDAV PROPFIND Depth:infinity returned HTTP %s; falling back to Depth:1 recursion",
|
||||||
|
response.status_code,
|
||||||
|
)
|
||||||
|
return _list_files_depth_one_recursive(config)
|
||||||
|
|
||||||
|
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)
|
||||||
Whitespace-only changes.
@@ -0,0 +1,247 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from apscheduler.schedulers.blocking import BlockingScheduler
|
||||||
|
from apscheduler.triggers.interval import IntervalTrigger
|
||||||
|
|
||||||
|
from forwarder.db.models import Account, ShopAccount
|
||||||
|
from forwarder.db.session import get_session_factory
|
||||||
|
from forwarder.error_reporter import report_error_with_cooldown
|
||||||
|
from forwarder.services.sync_service import sync_account
|
||||||
|
|
||||||
|
from forwarder.services.forward_queue_service import process_forward_queue
|
||||||
|
from forwarder.services.scraper_service import scrape_shop_account
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
SCHEDULE_REFRESH_MINUTES = 2
|
||||||
|
FORWARD_QUEUE_JOB_ID = "forward-queue"
|
||||||
|
|
||||||
|
|
||||||
|
def _account_job_id(account_id: int) -> str:
|
||||||
|
return f"sync-account-{account_id}"
|
||||||
|
|
||||||
|
|
||||||
|
def _shop_account_job_id(shop_account_id: int) -> str:
|
||||||
|
return f"scrape-shop-{shop_account_id}"
|
||||||
|
|
||||||
|
|
||||||
|
def _sync_job(account_id: int) -> None:
|
||||||
|
db = get_session_factory()()
|
||||||
|
try:
|
||||||
|
account = db.get(Account, account_id)
|
||||||
|
if account is None:
|
||||||
|
logger.warning("Scheduled sync skipped: account %s not found", account_id)
|
||||||
|
return
|
||||||
|
if not account.enabled:
|
||||||
|
logger.info(
|
||||||
|
"Scheduled sync skipped: account %s (%s) is disabled",
|
||||||
|
account_id,
|
||||||
|
account.name,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info("Scheduled sync starting for account %s", account_id)
|
||||||
|
sync_account(db, account_id, dry_run=False)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Scheduled sync failed for account %s", account_id)
|
||||||
|
report_error_with_cooldown(
|
||||||
|
f"scheduler:sync_account:{account_id}",
|
||||||
|
300.0,
|
||||||
|
exc,
|
||||||
|
severity="error",
|
||||||
|
context_data={"account_id": account_id},
|
||||||
|
endpoint="scheduler:sync_job",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _scrape_shop_job(shop_account_id: int) -> None:
|
||||||
|
db = get_session_factory()()
|
||||||
|
try:
|
||||||
|
account = db.get(ShopAccount, shop_account_id)
|
||||||
|
if account is None:
|
||||||
|
logger.warning("Scrape skipped: shop account %s not found", shop_account_id)
|
||||||
|
return
|
||||||
|
if not account.enabled:
|
||||||
|
logger.info(
|
||||||
|
"Scrape skipped: shop account %s (%s) is disabled",
|
||||||
|
shop_account_id,
|
||||||
|
account.name,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
logger.info("Scheduled scrape starting for shop account %s (%s)", shop_account_id, account.name)
|
||||||
|
scrape_shop_account(db, shop_account_id)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Scheduled scrape failed for shop account %s", shop_account_id)
|
||||||
|
report_error_with_cooldown(
|
||||||
|
f"scheduler:scrape_shop:{shop_account_id}",
|
||||||
|
300.0,
|
||||||
|
exc,
|
||||||
|
severity="error",
|
||||||
|
context_data={"shop_account_id": shop_account_id},
|
||||||
|
endpoint="scheduler:scrape_shop_job",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _forward_queue_job() -> None:
|
||||||
|
db = get_session_factory()()
|
||||||
|
try:
|
||||||
|
process_forward_queue(db)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Forward queue job failed")
|
||||||
|
report_error_with_cooldown(
|
||||||
|
"scheduler:forward_queue",
|
||||||
|
300.0,
|
||||||
|
exc,
|
||||||
|
severity="error",
|
||||||
|
endpoint="scheduler:forward_queue",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _interval_trigger_minutes(trigger: IntervalTrigger) -> int | None:
|
||||||
|
interval = getattr(trigger, "interval", None)
|
||||||
|
if interval is None:
|
||||||
|
return None
|
||||||
|
return int(interval.total_seconds() // 60)
|
||||||
|
|
||||||
|
|
||||||
|
def _refresh_account_schedules(scheduler: BlockingScheduler, *, default_interval: int) -> None:
|
||||||
|
"""Reconcile APScheduler jobs with enabled accounts in the database."""
|
||||||
|
db = get_session_factory()()
|
||||||
|
enabled_ids: set[int] = set()
|
||||||
|
try:
|
||||||
|
accounts = db.query(Account).filter(Account.enabled.is_(True)).all()
|
||||||
|
for account in accounts:
|
||||||
|
enabled_ids.add(account.id)
|
||||||
|
interval = account.sync_interval_minutes or default_interval
|
||||||
|
job_id = _account_job_id(account.id)
|
||||||
|
existing = scheduler.get_job(job_id)
|
||||||
|
if existing is not None and _interval_trigger_minutes(existing.trigger) == interval:
|
||||||
|
continue
|
||||||
|
|
||||||
|
scheduler.add_job(
|
||||||
|
_sync_job,
|
||||||
|
trigger=IntervalTrigger(minutes=interval),
|
||||||
|
args=[account.id],
|
||||||
|
id=job_id,
|
||||||
|
replace_existing=True,
|
||||||
|
max_instances=1,
|
||||||
|
next_run_time=datetime.now(timezone.utc),
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Schedule ensured for account %s (%s) every %s minutes",
|
||||||
|
account.id,
|
||||||
|
account.name,
|
||||||
|
interval,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
for job in scheduler.get_jobs():
|
||||||
|
if not job.id.startswith("sync-account-"):
|
||||||
|
continue
|
||||||
|
account_id = int(job.id.removeprefix("sync-account-"))
|
||||||
|
if account_id not in enabled_ids:
|
||||||
|
job.remove()
|
||||||
|
logger.info("Removed schedule for disabled/deleted account %s", account_id)
|
||||||
|
|
||||||
|
|
||||||
|
def _refresh_shop_schedules(scheduler: BlockingScheduler, *, default_interval: int = 60) -> None:
|
||||||
|
"""Reconcile APScheduler jobs with enabled ShopAccounts."""
|
||||||
|
db = get_session_factory()()
|
||||||
|
enabled_ids: set[int] = set()
|
||||||
|
try:
|
||||||
|
accounts = db.query(ShopAccount).filter(ShopAccount.enabled.is_(True)).all()
|
||||||
|
for account in accounts:
|
||||||
|
enabled_ids.add(account.id)
|
||||||
|
interval = account.sync_interval_minutes or default_interval
|
||||||
|
job_id = _shop_account_job_id(account.id)
|
||||||
|
existing = scheduler.get_job(job_id)
|
||||||
|
if existing is not None and _interval_trigger_minutes(existing.trigger) == interval:
|
||||||
|
continue
|
||||||
|
|
||||||
|
scheduler.add_job(
|
||||||
|
_scrape_shop_job,
|
||||||
|
trigger=IntervalTrigger(minutes=interval),
|
||||||
|
args=[account.id],
|
||||||
|
id=job_id,
|
||||||
|
replace_existing=True,
|
||||||
|
max_instances=1,
|
||||||
|
next_run_time=datetime.now(timezone.utc),
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Schedule ensured for shop account %s (%s / %s) every %s minutes",
|
||||||
|
account.id,
|
||||||
|
account.name,
|
||||||
|
account.shop_type.value,
|
||||||
|
interval,
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
for job in scheduler.get_jobs():
|
||||||
|
if not job.id.startswith("scrape-shop-"):
|
||||||
|
continue
|
||||||
|
shop_id = int(job.id.removeprefix("scrape-shop-"))
|
||||||
|
if shop_id not in enabled_ids:
|
||||||
|
job.remove()
|
||||||
|
logger.info("Removed schedule for disabled/deleted shop account %s", shop_id)
|
||||||
|
|
||||||
|
|
||||||
|
def run_worker(*, default_interval: int = 15) -> None:
|
||||||
|
from forwarder.config import get_settings
|
||||||
|
|
||||||
|
settings = get_settings()
|
||||||
|
scheduler = BlockingScheduler()
|
||||||
|
|
||||||
|
_refresh_account_schedules(scheduler, default_interval=default_interval)
|
||||||
|
_refresh_shop_schedules(scheduler)
|
||||||
|
|
||||||
|
scheduler.add_job(
|
||||||
|
_forward_queue_job,
|
||||||
|
trigger=IntervalTrigger(seconds=settings.forward_queue_interval_seconds),
|
||||||
|
id=FORWARD_QUEUE_JOB_ID,
|
||||||
|
replace_existing=True,
|
||||||
|
max_instances=1,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Forward queue scheduled every %ss, batch size %s, max %s/hour",
|
||||||
|
settings.forward_queue_interval_seconds,
|
||||||
|
settings.forward_queue_batch_size,
|
||||||
|
settings.max_forwards_per_hour,
|
||||||
|
)
|
||||||
|
|
||||||
|
scheduler.add_job(
|
||||||
|
_refresh_account_schedules,
|
||||||
|
trigger=IntervalTrigger(minutes=SCHEDULE_REFRESH_MINUTES),
|
||||||
|
args=[scheduler],
|
||||||
|
kwargs={"default_interval": default_interval},
|
||||||
|
id="refresh-account-schedules",
|
||||||
|
replace_existing=True,
|
||||||
|
max_instances=1,
|
||||||
|
)
|
||||||
|
scheduler.add_job(
|
||||||
|
_refresh_shop_schedules,
|
||||||
|
trigger=IntervalTrigger(minutes=SCHEDULE_REFRESH_MINUTES),
|
||||||
|
args=[scheduler],
|
||||||
|
id="refresh-shop-schedules",
|
||||||
|
replace_existing=True,
|
||||||
|
max_instances=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
sync_jobs = [j for j in scheduler.get_jobs() if j.id.startswith("sync-account-")]
|
||||||
|
if not sync_jobs:
|
||||||
|
logger.warning(
|
||||||
|
"No enabled accounts — worker idle (picks up changes every %s minutes)",
|
||||||
|
SCHEDULE_REFRESH_MINUTES,
|
||||||
|
)
|
||||||
|
|
||||||
|
scheduler.start()
|
||||||
Whitespace-only changes.
@@ -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"
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Crypto / Fernet key tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from cryptography.fernet import Fernet
|
||||||
|
|
||||||
|
from forwarder.crypto import EncryptionError, decrypt_password, encrypt_password, get_fernet
|
||||||
|
|
||||||
|
|
||||||
|
def _make_settings(key: str):
|
||||||
|
fake = type("FakeSettings", (), {"encryption_key": key})()
|
||||||
|
return fake
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_fernet_with_valid_key():
|
||||||
|
key = Fernet.generate_key().decode()
|
||||||
|
with patch("forwarder.crypto.get_settings", return_value=_make_settings(key)):
|
||||||
|
f = get_fernet()
|
||||||
|
assert isinstance(f, Fernet)
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_fernet_empty_key_raises_encryption_error():
|
||||||
|
with patch("forwarder.crypto.get_settings", return_value=_make_settings("")):
|
||||||
|
with pytest.raises(EncryptionError, match="not configured"):
|
||||||
|
get_fernet()
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_fernet_invalid_key_raises_encryption_error():
|
||||||
|
with patch("forwarder.crypto.get_settings", return_value=_make_settings("not-a-valid-fernet-key")):
|
||||||
|
with pytest.raises(EncryptionError, match="32 url-safe base64"):
|
||||||
|
get_fernet()
|
||||||
|
|
||||||
|
|
||||||
|
def test_decrypt_password_with_invalid_key_raises_encryption_error():
|
||||||
|
with patch("forwarder.crypto.get_settings", return_value=_make_settings("bad-key")):
|
||||||
|
with pytest.raises(EncryptionError, match="32 url-safe base64"):
|
||||||
|
decrypt_password("some-token")
|
||||||
|
|
||||||
|
|
||||||
|
def test_encrypt_then_decrypt_roundtrip():
|
||||||
|
key = Fernet.generate_key().decode()
|
||||||
|
with patch("forwarder.crypto.get_settings", return_value=_make_settings(key)):
|
||||||
|
token = encrypt_password("secret123")
|
||||||
|
assert decrypt_password(token) == "secret123"
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
"""Forward queue service tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from forwarder.db.models import MessageStatus
|
||||||
|
from forwarder.services.forward_queue_service import (
|
||||||
|
get_queue_status,
|
||||||
|
process_forward_queue,
|
||||||
|
requeue_forwarded_messages,
|
||||||
|
)
|
||||||
|
from forwarder.services.rate_limit import ForwardRateLimitError
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_queue_status_includes_eta():
|
||||||
|
db = MagicMock()
|
||||||
|
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||||
|
settings.return_value.forward_queue_batch_size = 5
|
||||||
|
settings.return_value.forward_queue_interval_seconds = 60
|
||||||
|
settings.return_value.max_forwards_per_hour = 200
|
||||||
|
with patch("forwarder.services.forward_queue_service.count_queue_pending", return_value=400):
|
||||||
|
with patch("forwarder.services.forward_queue_service.count_forwards_last_hour", return_value=10):
|
||||||
|
with patch(
|
||||||
|
"forwarder.services.forward_queue_service.forwards_remaining_this_hour",
|
||||||
|
return_value=190,
|
||||||
|
):
|
||||||
|
status = get_queue_status(db)
|
||||||
|
|
||||||
|
assert status["pending"] == 400
|
||||||
|
assert status["eta_hours_at_limit"] == 2.0
|
||||||
|
assert status["batch_size_per_tick"] == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_process_queue_respects_batch_size():
|
||||||
|
db = MagicMock()
|
||||||
|
messages = [MagicMock(id=i) for i in (1, 2, 3, 4, 5, 6)]
|
||||||
|
query = MagicMock()
|
||||||
|
query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = messages[:5]
|
||||||
|
db.query.return_value = query
|
||||||
|
|
||||||
|
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||||
|
settings.return_value.forward_queue_batch_size = 5
|
||||||
|
settings.return_value.max_forwards_per_hour = 200
|
||||||
|
with patch("forwarder.services.forward_queue_service.count_queue_pending", side_effect=[6, 1]):
|
||||||
|
with patch("forwarder.services.forward_queue_service.forwards_remaining_this_hour", return_value=200):
|
||||||
|
with patch("forwarder.services.forward_queue_service.check_forward_allowed"):
|
||||||
|
with patch("forwarder.services.forward_queue_service.retry_single_message"):
|
||||||
|
result = process_forward_queue(db)
|
||||||
|
|
||||||
|
assert result.attempted == 5
|
||||||
|
assert result.succeeded == 5
|
||||||
|
query.filter.return_value.order_by.return_value.limit.assert_called_with(5)
|
||||||
|
|
||||||
|
|
||||||
|
def test_process_queue_stops_at_hourly_limit():
|
||||||
|
db = MagicMock()
|
||||||
|
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||||
|
settings.return_value.forward_queue_batch_size = 5
|
||||||
|
settings.return_value.max_forwards_per_hour = 200
|
||||||
|
with patch("forwarder.services.forward_queue_service.count_queue_pending", return_value=10):
|
||||||
|
with patch("forwarder.services.forward_queue_service.forwards_remaining_this_hour", return_value=0):
|
||||||
|
result = process_forward_queue(db)
|
||||||
|
|
||||||
|
assert result.rate_limited is True
|
||||||
|
assert result.attempted == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_process_queue_breaks_on_rate_limit_mid_batch():
|
||||||
|
db = MagicMock()
|
||||||
|
messages = [MagicMock(id=1), MagicMock(id=2)]
|
||||||
|
query = MagicMock()
|
||||||
|
query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = messages
|
||||||
|
db.query.return_value = query
|
||||||
|
|
||||||
|
with patch("forwarder.services.forward_queue_service.get_settings") as settings:
|
||||||
|
settings.return_value.forward_queue_batch_size = 5
|
||||||
|
settings.return_value.max_forwards_per_hour = 200
|
||||||
|
with patch("forwarder.services.forward_queue_service.count_queue_pending", side_effect=[2, 1]):
|
||||||
|
with patch("forwarder.services.forward_queue_service.forwards_remaining_this_hour", return_value=5):
|
||||||
|
with patch(
|
||||||
|
"forwarder.services.forward_queue_service.check_forward_allowed",
|
||||||
|
side_effect=[None, ForwardRateLimitError(limit=200, used=200)],
|
||||||
|
):
|
||||||
|
with patch("forwarder.services.forward_queue_service.retry_single_message"):
|
||||||
|
result = process_forward_queue(db)
|
||||||
|
|
||||||
|
assert result.attempted == 1
|
||||||
|
assert result.succeeded == 1
|
||||||
|
assert result.rate_limited is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_requeue_forwarded_messages():
|
||||||
|
db = MagicMock()
|
||||||
|
msg_a = MagicMock(status=MessageStatus.forwarded, error_message="old")
|
||||||
|
msg_b = MagicMock(status=MessageStatus.forwarded, error_message="old")
|
||||||
|
db.query.return_value.filter.return_value.all.return_value = [msg_a, msg_b]
|
||||||
|
|
||||||
|
count = requeue_forwarded_messages(db)
|
||||||
|
|
||||||
|
assert count == 2
|
||||||
|
assert msg_a.status == MessageStatus.failed
|
||||||
|
assert msg_b.status == MessageStatus.failed
|
||||||
|
assert msg_a.error_message is None
|
||||||
|
db.commit.assert_called_once()
|
||||||
@@ -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"]
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"""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_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",
|
||||||
|
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)
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""Tests for IMAP logout handling on a timed-out socket.
|
||||||
|
|
||||||
|
Regression test for BIT-33892: ``OSError: cannot read from timed out object``
|
||||||
|
raised by ``imap.logout()`` when the underlying socket has already timed out.
|
||||||
|
The ``finally`` block must swallow ``OSError`` alongside ``imaplib.IMAP4.error``
|
||||||
|
so the sync run can finish cleanly instead of crashing.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from forwarder.services.sync_service import sync_account
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_account_swallows_logout_oserror(monkeypatch):
|
||||||
|
"""logout() raising OSError (timed-out socket) must not crash sync_account."""
|
||||||
|
db = MagicMock()
|
||||||
|
|
||||||
|
account = MagicMock()
|
||||||
|
account.id = 1
|
||||||
|
account.source_type = "imap"
|
||||||
|
account.delivery_mode = "smtp"
|
||||||
|
account.imap_host = "imap.example.com"
|
||||||
|
account.imap_port = 993
|
||||||
|
account.imap_user = "[email protected]"
|
||||||
|
account.imap_password_encrypted = b"enc"
|
||||||
|
account.smtp_host = "smtp.example.com"
|
||||||
|
account.smtp_port = 587
|
||||||
|
account.smtp_user = "[email protected]"
|
||||||
|
account.smtp_password_encrypted = b"enc"
|
||||||
|
account.smtp_use_tls = True
|
||||||
|
account.allowed_extensions = None
|
||||||
|
|
||||||
|
imap = MagicMock()
|
||||||
|
imap.logout.side_effect = OSError("cannot read from timed out object")
|
||||||
|
smtp = MagicMock()
|
||||||
|
smtp.quit = MagicMock()
|
||||||
|
|
||||||
|
def fake_list_mailboxes(_imap):
|
||||||
|
return []
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch("forwarder.services.sync_service.get_account", return_value=account),
|
||||||
|
patch("forwarder.services.sync_service.decrypt_password", return_value="secret"),
|
||||||
|
patch("forwarder.services.sync_service.connect_imap", return_value=imap),
|
||||||
|
patch("forwarder.services.sync_service.create_smtp_client", return_value=smtp),
|
||||||
|
patch("forwarder.services.sync_service.list_mailboxes", side_effect=fake_list_mailboxes),
|
||||||
|
patch("forwarder.services.sync_service._get_known_message_keys", return_value=set()),
|
||||||
|
):
|
||||||
|
sync_run = sync_account(db, 1, dry_run=False)
|
||||||
|
|
||||||
|
imap.logout.assert_called_once()
|
||||||
|
smtp.quit.assert_called_once()
|
||||||
|
assert sync_run.status.value == "completed"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
"""Message search filter tests."""
|
||||||
|
|
||||||
|
from forwarder.services.message_search import build_message_search_filter
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_message_search_filter_empty():
|
||||||
|
assert build_message_search_filter(None) is None
|
||||||
|
assert build_message_search_filter("") is None
|
||||||
|
assert build_message_search_filter(" ") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_message_search_filter_returns_clause():
|
||||||
|
clause = build_message_search_filter("fatura")
|
||||||
|
assert clause is not None
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_message_search_filter_numeric_id():
|
||||||
|
clause = build_message_search_filter("767")
|
||||||
|
assert clause is not None
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"""Tests for missing-from-mailbox handling."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from forwarder.db.models import MessageStatus
|
||||||
|
from forwarder.services.sync_service import (
|
||||||
|
MessageMissingFromMailboxError,
|
||||||
|
is_missing_from_mailbox_error,
|
||||||
|
retry_single_message,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_is_missing_from_mailbox_error():
|
||||||
|
assert is_missing_from_mailbox_error("Could not fetch message UID 5480")
|
||||||
|
assert is_missing_from_mailbox_error("Could not open folder: INBOX.old")
|
||||||
|
assert not is_missing_from_mailbox_error("SMTP timeout")
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_marks_missing_when_uid_not_found():
|
||||||
|
db = MagicMock()
|
||||||
|
message = MagicMock()
|
||||||
|
message.id = 1
|
||||||
|
message.account_id = 2
|
||||||
|
message.status = MessageStatus.failed
|
||||||
|
message.folder = "INBOX"
|
||||||
|
message.uid = "5480"
|
||||||
|
message.subject = "Test"
|
||||||
|
db.get.return_value = message
|
||||||
|
|
||||||
|
account = MagicMock()
|
||||||
|
imap = MagicMock()
|
||||||
|
|
||||||
|
with patch("forwarder.services.sync_service.get_account", return_value=account):
|
||||||
|
with patch("forwarder.services.sync_service.decrypt_password", return_value="secret"):
|
||||||
|
with patch("forwarder.services.sync_service.connect_imap", return_value=imap):
|
||||||
|
with patch("forwarder.services.sync_service.select_folder_readonly", return_value=True):
|
||||||
|
with patch("forwarder.services.sync_service.fetch_message", return_value=None):
|
||||||
|
with patch("forwarder.services.sync_service._record_forward_attempt"):
|
||||||
|
with pytest.raises(MessageMissingFromMailboxError) as exc:
|
||||||
|
retry_single_message(db, 1)
|
||||||
|
|
||||||
|
assert message.status == MessageStatus.missing_from_mailbox
|
||||||
|
assert "5480" in str(exc.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_retry_skips_already_missing():
|
||||||
|
db = MagicMock()
|
||||||
|
message = MagicMock()
|
||||||
|
message.status = MessageStatus.missing_from_mailbox
|
||||||
|
message.error_message = "gone"
|
||||||
|
db.get.return_value = message
|
||||||
|
|
||||||
|
with pytest.raises(MessageMissingFromMailboxError):
|
||||||
|
retry_single_message(db, 99)
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
"""Email parsing tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from forwarder.email.parsing import parse_email_datetime
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_email_datetime_valid():
|
||||||
|
dt = parse_email_datetime("Tue, 18 Feb 2025 18:23:09 +0000")
|
||||||
|
assert dt is not None
|
||||||
|
assert dt.year == 2025
|
||||||
|
assert dt.month == 2
|
||||||
|
assert dt.day == 18
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_email_datetime_invalid():
|
||||||
|
assert parse_email_datetime("") is None
|
||||||
|
assert parse_email_datetime(None) is None
|
||||||
|
assert parse_email_datetime("not-a-date") is None
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Rate limit tests."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from forwarder.services.rate_limit import ForwardRateLimitError, check_forward_allowed
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_forward_allowed_when_under_limit():
|
||||||
|
db = MagicMock()
|
||||||
|
with patch("forwarder.services.rate_limit.get_settings") as settings:
|
||||||
|
settings.return_value.max_forwards_per_hour = 200
|
||||||
|
with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=199):
|
||||||
|
check_forward_allowed(db)
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_forward_allowed_raises_at_limit():
|
||||||
|
db = MagicMock()
|
||||||
|
with patch("forwarder.services.rate_limit.get_settings") as settings:
|
||||||
|
settings.return_value.max_forwards_per_hour = 200
|
||||||
|
with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=200):
|
||||||
|
with pytest.raises(ForwardRateLimitError) as exc:
|
||||||
|
check_forward_allowed(db)
|
||||||
|
assert exc.value.limit == 200
|
||||||
|
assert exc.value.used == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_unlimited_when_config_zero():
|
||||||
|
db = MagicMock()
|
||||||
|
with patch("forwarder.services.rate_limit.get_settings") as settings:
|
||||||
|
settings.return_value.max_forwards_per_hour = 0
|
||||||
|
with patch("forwarder.services.rate_limit.count_forwards_last_hour", return_value=9999):
|
||||||
|
check_forward_allowed(db)
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Tests for worker scheduler — disabled accounts must not sync automatically."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from apscheduler.schedulers.blocking import BlockingScheduler
|
||||||
|
|
||||||
|
from forwarder.worker import scheduler as sched
|
||||||
|
|
||||||
|
|
||||||
|
class TestSyncJobGuard:
|
||||||
|
def test_skips_when_account_disabled(self):
|
||||||
|
db = MagicMock()
|
||||||
|
account = MagicMock()
|
||||||
|
account.enabled = False
|
||||||
|
account.name = "Test Co"
|
||||||
|
db.get.return_value = account
|
||||||
|
|
||||||
|
with patch.object(sched, "get_session_factory") as factory:
|
||||||
|
factory.return_value = MagicMock(return_value=db)
|
||||||
|
with patch.object(sched, "sync_account") as sync_account:
|
||||||
|
sched._sync_job(42)
|
||||||
|
|
||||||
|
sync_account.assert_not_called()
|
||||||
|
|
||||||
|
def test_skips_when_account_missing(self):
|
||||||
|
db = MagicMock()
|
||||||
|
db.get.return_value = None
|
||||||
|
|
||||||
|
with patch.object(sched, "get_session_factory") as factory:
|
||||||
|
factory.return_value = MagicMock(return_value=db)
|
||||||
|
with patch.object(sched, "sync_account") as sync_account:
|
||||||
|
sched._sync_job(99)
|
||||||
|
|
||||||
|
sync_account.assert_not_called()
|
||||||
|
|
||||||
|
def test_runs_when_account_enabled(self):
|
||||||
|
db = MagicMock()
|
||||||
|
account = MagicMock()
|
||||||
|
account.enabled = True
|
||||||
|
account.name = "Active Co"
|
||||||
|
db.get.return_value = account
|
||||||
|
|
||||||
|
with patch.object(sched, "get_session_factory") as factory:
|
||||||
|
factory.return_value = MagicMock(return_value=db)
|
||||||
|
with patch.object(sched, "sync_account") as sync_account:
|
||||||
|
sched._sync_job(1)
|
||||||
|
|
||||||
|
sync_account.assert_called_once_with(db, 1, dry_run=False)
|
||||||
|
|
||||||
|
|
||||||
|
class TestRefreshSchedules:
|
||||||
|
def test_removes_job_for_disabled_account(self):
|
||||||
|
scheduler = BlockingScheduler()
|
||||||
|
scheduler.add_job(lambda: None, "interval", seconds=3600, id="sync-account-7")
|
||||||
|
|
||||||
|
account = MagicMock()
|
||||||
|
account.id = 1
|
||||||
|
account.enabled = True
|
||||||
|
account.name = "Active"
|
||||||
|
account.sync_interval_minutes = 15
|
||||||
|
|
||||||
|
db = MagicMock()
|
||||||
|
db.query.return_value.filter.return_value.all.return_value = [account]
|
||||||
|
|
||||||
|
with patch.object(sched, "get_session_factory") as factory:
|
||||||
|
factory.return_value = MagicMock(return_value=db)
|
||||||
|
sched._refresh_account_schedules(scheduler, default_interval=15)
|
||||||
|
|
||||||
|
job_ids = {j.id for j in scheduler.get_jobs()}
|
||||||
|
assert "sync-account-1" in job_ids
|
||||||
|
assert "sync-account-7" not in job_ids
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
"""Outbound forward sends a clean message with invoice attachments only."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from email.message import EmailMessage
|
||||||
|
|
||||||
|
from forwarder.email.smtp_client import build_forward_message
|
||||||
|
|
||||||
|
|
||||||
|
def test_forward_sends_clean_message_with_pdf_only():
|
||||||
|
original = EmailMessage()
|
||||||
|
original["From"] = "[email protected]"
|
||||||
|
original["To"] = "[email protected]"
|
||||||
|
original["Subject"] = "Invoice & Ticket Delivery"
|
||||||
|
original["X-SG-EID"] = "spam-marker"
|
||||||
|
original.set_content("marketing body")
|
||||||
|
original.add_attachment(
|
||||||
|
b"%PDF-1.4\n" + (b"x" * 1200),
|
||||||
|
maintype="application",
|
||||||
|
subtype="pdf",
|
||||||
|
filename="fatura.pdf",
|
||||||
|
)
|
||||||
|
|
||||||
|
outbound = build_forward_message(
|
||||||
|
original,
|
||||||
|
from_addr="[email protected]",
|
||||||
|
destination_email="[email protected]",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert outbound["From"] == "[email protected]"
|
||||||
|
assert outbound["To"] == "[email protected]"
|
||||||
|
assert outbound["Subject"] == "Invoice & Ticket Delivery"
|
||||||
|
assert not outbound["Subject"].lower().startswith("fwd:")
|
||||||
|
assert outbound.get("Cc") is None
|
||||||
|
assert outbound.get("X-SG-EID") is None
|
||||||
|
|
||||||
|
attachments = list(outbound.iter_attachments())
|
||||||
|
assert len(attachments) == 1
|
||||||
|
assert attachments[0].get_filename() == "fatura.pdf"
|
||||||
|
assert attachments[0].get_content_type() == "application/pdf"
|
||||||
|
|
||||||
|
text_parts = [
|
||||||
|
p.get_content()
|
||||||
|
for p in outbound.walk()
|
||||||
|
if not p.is_multipart() and p.get_content_type() == "text/plain"
|
||||||
|
]
|
||||||
|
assert text_parts
|
||||||
|
assert "Remetente original" in text_parts[0]
|
||||||
|
assert "marketing body" not in text_parts[0]
|
||||||
|
|
||||||
|
|
||||||
|
def test_forward_includes_multiple_invoice_types():
|
||||||
|
original = EmailMessage()
|
||||||
|
original["Subject"] = "Docs"
|
||||||
|
original.set_content("x")
|
||||||
|
original.add_attachment(
|
||||||
|
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(
|
||||||
|
original,
|
||||||
|
from_addr="[email protected]",
|
||||||
|
destination_email="[email protected]",
|
||||||
|
)
|
||||||
|
|
||||||
|
names = {p.get_filename() for p in outbound.iter_attachments()}
|
||||||
|
assert names == {"a.pdf", "b.xml"}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Tests for IMAP timeout handling in sync_account."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from forwarder.db.models import DeliveryMode, SourceType, SyncRunStatus
|
||||||
|
from forwarder.services.sync_service import sync_account
|
||||||
|
|
||||||
|
|
||||||
|
def _make_account() -> MagicMock:
|
||||||
|
account = MagicMock()
|
||||||
|
account.source_type = SourceType.imap
|
||||||
|
account.imap_host = "imap.example.com"
|
||||||
|
account.imap_port = 993
|
||||||
|
account.imap_user = "[email protected]"
|
||||||
|
account.imap_password_encrypted = b"encrypted"
|
||||||
|
account.delivery_mode = DeliveryMode.api
|
||||||
|
account.bizdocs_password_encrypted = b"encrypted"
|
||||||
|
account.allowed_extensions = None
|
||||||
|
account.imap_folder_selection_mode = "default"
|
||||||
|
account.imap_selected_folders = None
|
||||||
|
account.include_all_attachments = False
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
def test_sync_continues_after_fetch_timeout():
|
||||||
|
"""A TimeoutError on fetch_message must not kill the entire sync run."""
|
||||||
|
db = MagicMock()
|
||||||
|
db.query.return_value.filter.return_value.all.return_value = []
|
||||||
|
|
||||||
|
imap = MagicMock()
|
||||||
|
imap.uid.side_effect = lambda *args: ("OK", [b"1 2"]) if args[0] == "search" else ("OK", [None])
|
||||||
|
|
||||||
|
account = _make_account()
|
||||||
|
|
||||||
|
fetch_calls: list = []
|
||||||
|
|
||||||
|
def _fetch_side_effect(_imap, uid):
|
||||||
|
fetch_calls.append(uid)
|
||||||
|
raise TimeoutError("The read operation timed out")
|
||||||
|
|
||||||
|
with patch("forwarder.services.sync_service.get_account", return_value=account):
|
||||||
|
with patch("forwarder.services.sync_service.decrypt_password", return_value="secret"):
|
||||||
|
with patch("forwarder.services.sync_service.connect_imap", return_value=imap):
|
||||||
|
with patch("forwarder.services.sync_service.list_mailboxes", return_value=["INBOX"]):
|
||||||
|
with patch("forwarder.services.sync_service.select_folder_readonly", return_value=True):
|
||||||
|
with patch("forwarder.services.sync_service.fetch_message", side_effect=_fetch_side_effect):
|
||||||
|
with patch("forwarder.services.sync_service.report_error_with_cooldown"):
|
||||||
|
sync_run = sync_account(db, 1, dry_run=True)
|
||||||
|
|
||||||
|
assert sync_run.status == SyncRunStatus.completed
|
||||||
|
assert sync_run.messages_failed == 2
|
||||||
|
assert len(fetch_calls) == 2
|
||||||
@@ -0,0 +1,371 @@
|
|||||||
|
"""Tests for WebDAV client helpers and PROPFIND parsing."""
|
||||||
|
|
||||||
|
from forwarder.webdav.client import (
|
||||||
|
MIN_WEBDAV_FILE_BYTES,
|
||||||
|
WebdavConfig,
|
||||||
|
WebdavFile,
|
||||||
|
_parse_propfind_collections,
|
||||||
|
_parse_propfind_response,
|
||||||
|
build_webdav_root,
|
||||||
|
get_webdav_message_key,
|
||||||
|
list_files,
|
||||||
|
normalize_webdav_folder_path,
|
||||||
|
parse_webdav_message_key,
|
||||||
|
webdav_bytes_below_min_size,
|
||||||
|
webdav_file_below_min_size,
|
||||||
|
webdav_file_matches_min_year,
|
||||||
|
webdav_file_reference_date,
|
||||||
|
)
|
||||||
|
|
||||||
|
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:creationdate>2024-01-01T10:00:00Z</D:creationdate>
|
||||||
|
<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:getlastmodified>Mon, 15 Jun 2025 12:00:00 GMT</D:getlastmodified>
|
||||||
|
<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 _sample_file(*, modified: str = "", created: str = "", path: str = "a.pdf") -> WebdavFile:
|
||||||
|
return WebdavFile(
|
||||||
|
relative_path=path,
|
||||||
|
name="a.pdf",
|
||||||
|
href="/a.pdf",
|
||||||
|
etag="1",
|
||||||
|
modified=modified,
|
||||||
|
created=created,
|
||||||
|
oc_creation_time="",
|
||||||
|
nc_creation_time="",
|
||||||
|
size=100,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_webdav_file_matches_min_year_by_creation_date():
|
||||||
|
old = _sample_file(created="2024-06-01T10:00:00Z", modified="Mon, 01 Jan 2026 10:00:00 GMT")
|
||||||
|
assert webdav_file_reference_date(old).year == 2026
|
||||||
|
assert webdav_file_matches_min_year(old, 2025)
|
||||||
|
|
||||||
|
recent = _sample_file(modified="Mon, 15 Jun 2025 12:00:00 GMT")
|
||||||
|
assert webdav_file_matches_min_year(recent, 2025)
|
||||||
|
|
||||||
|
|
||||||
|
def test_webdav_file_reference_date_prefers_modified_over_epoch_creation():
|
||||||
|
nextcloud_import = WebdavFile(
|
||||||
|
relative_path="Faturas/2025/01_Janeiro/invoice.pdf",
|
||||||
|
name="invoice.pdf",
|
||||||
|
href="/invoice.pdf",
|
||||||
|
etag="1",
|
||||||
|
modified="Mon, 06 Jan 2025 13:38:04 GMT",
|
||||||
|
created="1970-01-01T00:00:00+00:00",
|
||||||
|
oc_creation_time="",
|
||||||
|
nc_creation_time="",
|
||||||
|
size=50000,
|
||||||
|
)
|
||||||
|
assert webdav_file_reference_date(nextcloud_import).year == 2025
|
||||||
|
assert webdav_file_matches_min_year(nextcloud_import, 2025)
|
||||||
|
|
||||||
|
|
||||||
|
def test_webdav_file_matches_min_year_by_folder_when_epoch_date():
|
||||||
|
epoch_in_2025_folder = WebdavFile(
|
||||||
|
relative_path="Faturas/2025/01_Janeiro/invoice.pdf",
|
||||||
|
name="invoice.pdf",
|
||||||
|
href="/invoice.pdf",
|
||||||
|
etag="1",
|
||||||
|
modified="",
|
||||||
|
created="1970-01-01T00:00:00+00:00",
|
||||||
|
oc_creation_time="",
|
||||||
|
nc_creation_time="",
|
||||||
|
size=50000,
|
||||||
|
)
|
||||||
|
assert webdav_file_matches_min_year(epoch_in_2025_folder, 2025)
|
||||||
|
|
||||||
|
epoch_in_2024_folder = WebdavFile(
|
||||||
|
relative_path="Faturas/2024/invoice.pdf",
|
||||||
|
name="invoice.pdf",
|
||||||
|
href="/invoice.pdf",
|
||||||
|
etag="1",
|
||||||
|
modified="",
|
||||||
|
created="1970-01-01T00:00:00+00:00",
|
||||||
|
oc_creation_time="",
|
||||||
|
nc_creation_time="",
|
||||||
|
size=50000,
|
||||||
|
)
|
||||||
|
assert not webdav_file_matches_min_year(epoch_in_2024_folder, 2025)
|
||||||
|
|
||||||
|
|
||||||
|
def test_webdav_min_file_size():
|
||||||
|
assert MIN_WEBDAV_FILE_BYTES == 4096
|
||||||
|
small = WebdavFile(
|
||||||
|
relative_path="stub.pdf",
|
||||||
|
name="stub.pdf",
|
||||||
|
href="/stub.pdf",
|
||||||
|
etag="1",
|
||||||
|
modified="",
|
||||||
|
created="",
|
||||||
|
oc_creation_time="",
|
||||||
|
nc_creation_time="",
|
||||||
|
size=1997,
|
||||||
|
)
|
||||||
|
assert webdav_file_below_min_size(small)
|
||||||
|
unknown = WebdavFile(
|
||||||
|
relative_path="x.pdf",
|
||||||
|
name="x.pdf",
|
||||||
|
href="/x.pdf",
|
||||||
|
etag="1",
|
||||||
|
modified="",
|
||||||
|
created="",
|
||||||
|
oc_creation_time="",
|
||||||
|
nc_creation_time="",
|
||||||
|
size=0,
|
||||||
|
)
|
||||||
|
assert not webdav_file_below_min_size(unknown)
|
||||||
|
large = WebdavFile(
|
||||||
|
relative_path="invoice.pdf",
|
||||||
|
name="invoice.pdf",
|
||||||
|
href="/invoice.pdf",
|
||||||
|
etag="1",
|
||||||
|
modified="",
|
||||||
|
created="",
|
||||||
|
oc_creation_time="",
|
||||||
|
nc_creation_time="",
|
||||||
|
size=5000,
|
||||||
|
)
|
||||||
|
assert not webdav_file_below_min_size(large)
|
||||||
|
assert webdav_bytes_below_min_size(b"x" * 100)
|
||||||
|
assert not webdav_bytes_below_min_size(b"x" * MIN_WEBDAV_FILE_BYTES)
|
||||||
|
|
||||||
|
|
||||||
|
PROPFIND_MULTI_PROPSTAT = b"""<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<D:multistatus xmlns:D="DAV:">
|
||||||
|
<D:response>
|
||||||
|
<D:href>/remote.php/dav/files/user/Faturas/doc.pdf</D:href>
|
||||||
|
<D:propstat>
|
||||||
|
<D:prop><D:creationdate/></D:prop>
|
||||||
|
<D:status>HTTP/1.1 404 Not Found</D:status>
|
||||||
|
</D:propstat>
|
||||||
|
<D:propstat>
|
||||||
|
<D:prop>
|
||||||
|
<D:getlastmodified>Mon, 15 Jun 2025 12:00:00 GMT</D:getlastmodified>
|
||||||
|
<D:creationdate>1970-01-01T00:00:00+00:00</D:creationdate>
|
||||||
|
<D:getcontentlength>5000</D:getcontentlength>
|
||||||
|
<D:getetag>"x"</D:getetag>
|
||||||
|
<D:resourcetype/>
|
||||||
|
</D:prop>
|
||||||
|
<D:status>HTTP/1.1 200 OK</D:status>
|
||||||
|
</D:propstat>
|
||||||
|
</D:response>
|
||||||
|
</D:multistatus>
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_propfind_uses_ok_propstat():
|
||||||
|
root = "https://cloud.example.com/remote.php/dav/files/user/Faturas/"
|
||||||
|
files = _parse_propfind_response(root, PROPFIND_MULTI_PROPSTAT)
|
||||||
|
assert len(files) == 1
|
||||||
|
assert files[0].modified == "Mon, 15 Jun 2025 12:00:00 GMT"
|
||||||
|
assert webdav_file_reference_date(files[0]).year == 2025
|
||||||
|
|
||||||
|
|
||||||
|
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
|
||||||
|
assert invoice.created == "2024-01-01T10:00:00Z"
|
||||||
|
assert not webdav_file_matches_min_year(invoice, 2025)
|
||||||
|
photo = next(item for item in files if item.name == "photo.jpg")
|
||||||
|
assert webdav_file_matches_min_year(photo, 2025)
|
||||||
|
|
||||||
|
|
||||||
|
def _propfind_response(folder_href: str, entries: list[dict]) -> bytes:
|
||||||
|
"""Build a minimal DAV multistatus body for tests."""
|
||||||
|
parts = [
|
||||||
|
b'<?xml version="1.0" encoding="utf-8"?>',
|
||||||
|
b'<D:multistatus xmlns:D="DAV:">',
|
||||||
|
]
|
||||||
|
for entry in entries:
|
||||||
|
is_collection = entry.get("collection", False)
|
||||||
|
href = entry["href"].encode()
|
||||||
|
parts.append(b" <D:response>")
|
||||||
|
parts.append(b" <D:href>" + href + b"</D:href>")
|
||||||
|
parts.append(b" <D:propstat><D:prop>")
|
||||||
|
if is_collection:
|
||||||
|
parts.append(b" <D:resourcetype><D:collection/></D:resourcetype>")
|
||||||
|
else:
|
||||||
|
parts.append(b" <D:resourcetype/>")
|
||||||
|
parts.append(b" <D:getetag>" + entry.get("etag", b'"x"') + b"</D:getetag>")
|
||||||
|
parts.append(
|
||||||
|
b" <D:getlastmodified>"
|
||||||
|
+ entry.get("modified", b"Mon, 01 Jan 2024 10:00:00 GMT")
|
||||||
|
+ b"</D:getlastmodified>"
|
||||||
|
)
|
||||||
|
parts.append(
|
||||||
|
b" <D:getcontentlength>"
|
||||||
|
+ str(entry.get("size", 5000)).encode()
|
||||||
|
+ b"</D:getcontentlength>"
|
||||||
|
)
|
||||||
|
parts.append(b" </D:prop></D:propstat>")
|
||||||
|
parts.append(b" </D:response>")
|
||||||
|
parts.append(b"</D:multistatus>")
|
||||||
|
return b"\n".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
ROOT_URL = "https://cloud.example.com/remote.php/dav/files/user/Faturas"
|
||||||
|
|
||||||
|
|
||||||
|
def _make_config() -> WebdavConfig:
|
||||||
|
return WebdavConfig(
|
||||||
|
base_url="https://cloud.example.com/remote.php/dav/files/user",
|
||||||
|
folder_path="/Faturas",
|
||||||
|
user="user",
|
||||||
|
password="secret",
|
||||||
|
verify_ssl=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_propfind_collections_skips_root():
|
||||||
|
body = _propfind_response(
|
||||||
|
ROOT_URL + "/",
|
||||||
|
[
|
||||||
|
{"href": ROOT_URL + "/", "collection": True},
|
||||||
|
{"href": ROOT_URL + "/2025/", "collection": True},
|
||||||
|
{"href": ROOT_URL + "/invoice.pdf"},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
children = _parse_propfind_collections(ROOT_URL, body)
|
||||||
|
assert children == [ROOT_URL + "/2025/"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_files_falls_back_to_depth_one_on_http_500(monkeypatch):
|
||||||
|
"""Depth:infinity returning HTTP 500 triggers recursive Depth:1 traversal."""
|
||||||
|
import httpx
|
||||||
|
import forwarder.webdav.client as webdav_client
|
||||||
|
|
||||||
|
root_body = _propfind_response(
|
||||||
|
ROOT_URL + "/",
|
||||||
|
[
|
||||||
|
{"href": ROOT_URL + "/", "collection": True},
|
||||||
|
{"href": ROOT_URL + "/2025/", "collection": True},
|
||||||
|
{"href": ROOT_URL + "/invoice.pdf", "etag": b'"abc"'},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
sub_body = _propfind_response(
|
||||||
|
ROOT_URL + "/2025/",
|
||||||
|
[
|
||||||
|
{"href": ROOT_URL + "/2025/", "collection": True},
|
||||||
|
{"href": ROOT_URL + "/2025/receipt.pdf", "etag": b'"def"', "size": 9000},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
depth = request.headers.get("Depth")
|
||||||
|
url = str(request.url).rstrip("/")
|
||||||
|
if depth == "infinity":
|
||||||
|
return httpx.Response(500, text="infinite depth disabled")
|
||||||
|
if url == ROOT_URL and depth == "1":
|
||||||
|
return httpx.Response(207, content=root_body)
|
||||||
|
if url == ROOT_URL + "/2025" and depth == "1":
|
||||||
|
return httpx.Response(207, content=sub_body)
|
||||||
|
return httpx.Response(404)
|
||||||
|
|
||||||
|
transport = httpx.MockTransport(handler)
|
||||||
|
|
||||||
|
def _fake_client(config, *, timeout=60.0):
|
||||||
|
return httpx.Client(
|
||||||
|
transport=transport,
|
||||||
|
auth=(config.user, config.password),
|
||||||
|
headers={"User-Agent": "Bizdocs-Forwarder/1.0"},
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(webdav_client, "_client", _fake_client)
|
||||||
|
|
||||||
|
files = list_files(_make_config())
|
||||||
|
paths = sorted(item.relative_path for item in files)
|
||||||
|
assert paths == ["2025/receipt.pdf", "invoice.pdf"]
|
||||||
|
receipt = next(item for item in files if item.name == "receipt.pdf")
|
||||||
|
assert receipt.size == 9000
|
||||||
|
assert webdav_file_matches_min_year(receipt, 2025)
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_files_still_raises_on_persistent_500(monkeypatch):
|
||||||
|
"""A 500 that is not resolved by Depth:1 fallback surfaces as WebdavError."""
|
||||||
|
import httpx
|
||||||
|
import forwarder.webdav.client as webdav_client
|
||||||
|
|
||||||
|
def handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
return httpx.Response(500, text="server error")
|
||||||
|
|
||||||
|
transport = httpx.MockTransport(handler)
|
||||||
|
|
||||||
|
def _fake_client(config, *, timeout=60.0):
|
||||||
|
return httpx.Client(
|
||||||
|
transport=transport,
|
||||||
|
auth=(config.user, config.password),
|
||||||
|
headers={"User-Agent": "Bizdocs-Forwarder/1.0"},
|
||||||
|
)
|
||||||
|
|
||||||
|
monkeypatch.setattr(webdav_client, "_client", _fake_client)
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
with pytest.raises(webdav_client.WebdavError):
|
||||||
|
list_files(_make_config())
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""One-off: list duplicate failed messages in DB."""
|
||||||
|
from collections import Counter, defaultdict
|
||||||
|
|
||||||
|
from forwarder.db.models import Message, MessageStatus
|
||||||
|
from forwarder.db.session import get_session_factory
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
db = get_session_factory()()
|
||||||
|
rows = (
|
||||||
|
db.query(
|
||||||
|
Message.id,
|
||||||
|
Message.subject,
|
||||||
|
Message.from_addr,
|
||||||
|
Message.date,
|
||||||
|
Message.folder,
|
||||||
|
Message.uid,
|
||||||
|
Message.message_key,
|
||||||
|
)
|
||||||
|
.filter(Message.status == MessageStatus.failed)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
by_triple: Counter[tuple[str, str, str]] = Counter()
|
||||||
|
detail: dict[tuple[str, str, str], list[tuple[int, str, str, str]]] = defaultdict(list)
|
||||||
|
for mid, subject, from_addr, date, folder, uid, message_key in rows:
|
||||||
|
key = (subject or "", from_addr or "", date or "")
|
||||||
|
by_triple[key] += 1
|
||||||
|
detail[key].append((mid, folder, uid, message_key))
|
||||||
|
|
||||||
|
dups = [(k, v) for k, v in by_triple.items() if v > 1]
|
||||||
|
print(f"failed_total={len(rows)} duplicate_groups={len(dups)}")
|
||||||
|
for (subject, from_addr, date), count in sorted(dups, key=lambda x: -x[1])[:10]:
|
||||||
|
print(f"\n--- count={count} subject={subject[:60]!r} date={date}")
|
||||||
|
for mid, folder, uid, message_key in detail[(subject, from_addr, date)][:6]:
|
||||||
|
print(f" id={mid} folder={folder!r} uid={uid} key={message_key[:80]}")
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -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 you@company.pt --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())
|
||||||
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user