Author SHA1 Message Date
XikaandPaperclip d63a9e0290 feat(scrapers): add multi-portal invoice scraper with BizDocs upload (BIT-26282)
- Amazon and Temu Playwright-based invoice scrapers
- BizDocs mobile API client (login + document upload)
- ShopAccount DB model, migration 006, scheduler integration
- REST API routes: GET/POST/PATCH/DELETE /api/shop-accounts
- POST /api/shop-accounts/{id}/trigger for on-demand scrape
- POST /api/shop-accounts/{id}/test for BizDocs credential check
- GET /api/shop-accounts/{id}/runs for scrape history

Co-Authored-By: Paperclip <[email protected]>
2026-07-06 22:29:52 +00:00
spark a5256c45a5 Merge pull request 'fix(accounts): add POST /accounts/{id}/test combined endpoint (BIT-26141)' (#2) from task/BIT-26141-fix-test-endpoint into main
fix(accounts): add POST /accounts/{id}/test combined endpoint (BIT-26141)

Merged via CTO review - all approvals received.
2026-07-06 15:14:01 +01:00
spark 48d8ef2952 Merge branch 'main' into task/BIT-26141-fix-test-endpoint 2026-07-04 19:16:18 +01:00
1sonhador c83e452f54 fix: stop refresh from resetting sync job timers every 2 minutes
Account sync jobs were replaced on each schedule refresh, so the 15-minute
interval never elapsed and WebDAV/IMAP sync never ran after worker restarts.
2026-07-04 18:38:12 +01:00
1sonhador 7e5e4584fc fix: use WebDAV getlastmodified instead of Nextcloud epoch creationdate
Nextcloud returns DAV:creationdate as 1970 for bulk-imported files; the real
upload date is getlastmodified. Also pick the HTTP 200 propstat block.
2026-07-04 18:20:32 +01:00
1sonhador 3d81005588 fix: trust WebDAV folder year over 1970 epoch dates
Files under Faturas/2025/ or /2026/ are eligible even when Nextcloud
reports creationdate 1970. Add --requeue-folder-years to reset wrongly skipped records.
2026-07-04 18:13:41 +01:00
1sonhador a0f90bd8ef fix: skip WebDAV files smaller than 4KB to avoid retry loops
HTML stubs named as PDFs were stuck in the failed forward queue forever.
2026-07-04 13:19:02 +01:00
spark d8f298cec6 Merge branch 'main' into task/BIT-26141-fix-test-endpoint 2026-07-03 01:16:05 +01:00
1sonhador d561de7d02 feat: filter WebDAV files by creation/modified date instead of folders
Use PROPFIND creationdate with getlastmodified fallback so min year 2025 applies by file date, not folder names.
2026-07-02 23:13:31 +01:00
1sonhador 1617be3aee fix: detect WebDAV year folder anywhere in path (Faturas/2025/…) 2026-07-02 23:11:15 +01:00
1sonhador f381af9c60 fix: webdav year setup tool use get_session_factory() 2026-07-02 23:09:17 +01:00
1sonhador a4f4c2a921 fix: webdav year setup tool session import 2026-07-02 23:03:10 +01:00
1sonhador b02add914e fix: remove stale containers before compose recreate on deploy
Prevent docker name conflicts when a prior deploy fails mid-recreate.
2026-07-02 23:02:43 +01:00
1sonhador d3c26a453e fix: WebDAV year filter uses min year (2025+) not fixed list
Include all year folders from 2025 onwards (2026, 2027, …) and skip or mark anything older.
2026-07-02 22:51:35 +01:00
1sonhador 28164ad9f4 feat: filter WebDAV sync by year folders (2025/2026)
Add webdav_include_years account setting, skip files outside allowed year folders during sync, and a setup tool to mark older paths as already forwarded.
2026-07-02 22:45:03 +01:00
1sonhador 529ecb31a4 fix: unblock production deploy (API schema + admin UI types)
Remove duplicate bizdocs_entity_id field that broke API startup and fix nullable trim calls in Accounts form so the admin UI Docker build passes.
2026-07-02 22:22:03 +01:00
1sonhador 0f4bb5f522 feat: BizDocs API delivery, WebDAV source, and invoice validation
Add optional API upload alongside SMTP, Nextcloud/WebDAV as a document source with the same dedup/retry flow as IMAP, stricter invoice file checks for images, and admin UI for source and delivery modes.
2026-07-02 19:21:01 +01:00
spark f165f411d9 Merge branch 'main' into task/BIT-26141-fix-test-endpoint 2026-07-01 19:16:20 +01:00
1sonhador 6840e521dd fix: clarify sync test limit vs full scan; continue on rate limit
Test button (▶) caps UIDs scanned to N; full sync (↻) reads entire mailbox.
2026-07-01 14:48:26 +01:00
1sonhador 16816e9d4e feat: search emails by subject, sender, folder, Message-ID or id
API q parameter and debounced search field on the Emails admin page.
2026-07-01 14:44:00 +01:00
1sonhador e31a1b4a7a fix: sync_account must return SyncRun not last IMAP message
Fixes 500 on POST /accounts/{id}/sync when clicking play in admin UI.
2026-07-01 14:30:03 +01:00
spark b1382b4b95 Merge branch 'main' into task/BIT-26141-fix-test-endpoint 2026-07-01 13:16:23 +01:00
1sonhador 31d32ed1b4 fix: rebuild migrate image and run migrations before API restart
Ensures new Alembic revisions apply on deploy.
2026-07-01 11:27:30 +01:00
1sonhador 50b231caa6 feat: mark messages missing from IMAP and stop queue retries
New missing_from_mailbox status for deleted UIDs; migration backfills existing fetch failures.
2026-07-01 11:21:20 +01:00
1sonhador 5b841a8850 fix: skip known Message-IDs on sync and clarify email list UI
Sync ignores any message already in DB (queue handles retries). UI shows email date, folder, and Message-ID snippet.
2026-07-01 10:45:50 +01:00
1sonhador 2ee2306c3e fix: route retry-batch through forward queue instead of bulk SMTP
all=true only confirms failed messages are queued; each tick respects 5/min and 200/h limits.
2026-07-01 10:19:39 +01:00
1sonhador 9b966cf325 feat: forward queue drains failed messages at 5/min within 200/h cap
Worker ticks every 60s; API and UI expose queue status and requeue of forwarded messages for gradual BizDocs resend.
2026-07-01 10:14:18 +01:00
1sonhador 66d7189aa5 feat: cap SMTP forwards at 200 per rolling hour
Count successful forward_attempts in the last hour and stop sync/retry
when MAX_FORWARDS_PER_HOUR is reached to protect domain sending limits.
2026-07-01 10:09:52 +01:00
1sonhador 95edd74d9f fix: send clean invoice-only emails to avoid MailChannels spam blocks
Stop relaying the original RFC822 (SendGrid headers, Fwd: subject, etc.).
Send a new message with PDF/XML/ZIP attachments and minimal metadata body.
2026-07-01 09:56:38 +01:00
1sonhador f19886d78e fix: strip Cc/Bcc on forward to prevent mailbox loop
Re-sending the original MIME kept Cc/Bcc (e.g. faturas@) so copies
returned to the monitored inbox. Drop extra recipient headers and
send SMTP RCPT only to the BizDocs destination.
2026-07-01 09:51:00 +01:00
1sonhador ea88e8833d feat: retry all failed messages from emails page
Add "Repetir todas as falhadas" with batched API calls and progress
feedback; raise retry-batch limit to 100 and support all=true on API.
2026-07-01 09:44:19 +01:00
1sonhador bd2d04aba7 feat: batch retry for failed messages and visible retry errors
Show API errors when single retry fails and add POST /messages/retry-batch
plus a "Repetir 5 falhadas" button for post-deploy testing.
2026-07-01 09:23:41 +01:00
1sonhador f55a38c032 feat: paginate emails list in API and admin UI
Return total count with offset/limit from GET /messages and add
Anterior/Seguinte controls showing 25 rows per page.
2026-07-01 09:19:17 +01:00
1sonhador b070af8503 fix: forward original email via SMTP instead of .eml attachment
Re-send the received RFC822 message with normal Fwd headers (To, From,
Subject). The previous code wrapped the message in message/rfc822 with
filename original-email.eml, which the relay rejected.
2026-07-01 09:18:11 +01:00
1sonhador f664cca6b5 fix: forward invoice PDF/XML/ZIP attachments instead of .eml wrapper
The outbound SMTP relay rejects message/rfc822 attachments named .eml.
Send the matched invoice files directly to BizDocs, which aligns with
the allowed relay extensions and the product filter rules.
2026-07-01 09:15:01 +01:00
1sonhador 87b1ad4b8a feat: sync UI controls, message retry, and worker schedule guard
Add manual sync buttons with batch limit, nginx timeouts for long syncs,
message retry endpoint, and fix worker to skip disabled accounts and
refresh schedules from the database every 2 minutes.
2026-07-01 09:10:04 +01:00
XikaandPaperclip 20966501a8 fix(deploy): retry API health check after container restart
After --force-recreate web, the API container can take >10s to become
healthy. Retry up to 5 times with 5s backoff so transient startup
latency doesn't mark a successful deploy as failed.

Co-Authored-By: Paperclip <[email protected]>
2026-07-01 01:23:15 +00:00
XikaandPaperclip 41ba0befe6 chore(deploy): document webhook URL via NPM proxy
Gitea hook #28 now delivers to http://forwarder-hook.bitreport.pt/
(NPM CT 102 → 10.10.50.43:9090) instead of direct VLAN IP,
as Gitea VLAN 1010 cannot route to VLAN 1050 directly.

Co-Authored-By: Paperclip <[email protected]>
2026-07-01 01:13:27 +00:00
XikaandPaperclip 146593bf05 chore(deploy): document webhook URL via NPM proxy
Gitea hook #28 now delivers to http://forwarder-hook.bitreport.pt/
(NPM CT 102 → 10.10.50.43:9090) instead of direct VLAN IP,
as Gitea VLAN 1010 cannot route to VLAN 1050 directly.

Co-Authored-By: Paperclip <[email protected]>
2026-07-01 01:13:19 +00:00
Xika c834560f81 fix(accounts): add POST /accounts/{id}/test combined endpoint (BIT-26141)
The admin UI calls POST /accounts/{id}/test when the user clicks "Testar
ligação", but only granular /test/imap, /test/smtp, /test/send endpoints
existed — causing a 404. Adds the missing combined endpoint that runs
IMAP + SMTP tests in parallel and returns the ConnectionTestResult schema
the frontend expects (imap_ok, smtp_ok, bizdocs_ok).

Paperclip-Issue: BIT-26141
2026-07-01 01:13:06 +00:00
XikaandPaperclip c281b2b56d fix(deploy): write status before self-restarting deploy-hook
The deploy-hook container was killing itself before write_status ran,
leaving last_deploy=null on every successful deploy. Move health check
and write_status before the detached nohup restart of the deploy-hook
container so status is persisted even when the container recreates itself.

Co-Authored-By: Paperclip <[email protected]>
2026-07-01 01:02:00 +00:00
1sonhador df016a1e34 fix(deploy): use repo deploy script + expose git_sha in health
Webhook now runs /opt/forwarder/deploy/deploy-pull.sh from git (not stale
image copy). Rolling rebuild api then web; health reports FORWARDER_GIT_SHA.
2026-07-01 01:40:43 +01:00
1sonhador 210bc7e324 fix(api): default destination_email for legacy UI payloads
Accept account creates without destination_email (defaults to BizDocs
inbox) and force admin-ui rebuild on deploy so web container picks up UI changes.
2026-07-01 01:36:07 +01:00
1sonhador eb4a95dfc2 fix(admin-ui): add destination_email field to account form
The API requires destination_email for BizDocs SMTP forwarding; the UI
still sent legacy bizdocs_api_key fields. Default [email protected].
2026-07-01 01:29:44 +01:00
XikaandPaperclip 0c63ae7fbd feat: integrate error hub (errors.bitreport.pt) for runtime error reporting
- Add forwarder/error_reporter.py: Python client for v1/ingest/events
  with cooldown-based dedup, best-effort delivery, and env-driven config
- Add FastAPI global exception handler to report unhandled 500s
- Report sync failures and forward failures from sync_service.py
- Report scheduler job failures from worker/scheduler.py with cooldown
- Report startup failures (ensure_admin_user) from app.py
- Report worker crashes from cli.py entry point
- Add error hub env vars to config.py (pydantic-settings)
- Update .env.example with ERROR_REPORTING_TOKEN and related vars
- Exclude IMAP/SMTP connection test errors per BIT-26136 scope note
- Uses project_slug=bizdocs-forwarder, gitea_repo=BitReport.pt/forwarder

Co-Authored-By: Paperclip <[email protected]>
2026-07-01 00:14:29 +00:00
1sonhador f6b276511a fix(connection): fail-fast IMAP/SMTP tests; add Gitea webhook autodeploy
Connection tests use 5s timeouts and run IMAP/SMTP in parallel so the UI
gets a clear error instead of nginx 504. Add deploy-hook service (:9090) and
deploy-pull.sh for push-to-main deploys on CT 243.
2026-07-01 01:09:53 +01:00
XikaandPaperclip d476cb0204 feat(admin-ui): add login page and HTTP Basic auth
- AuthProvider + useAuth hook (sessionStorage, base64 creds)
- Login.tsx validates credentials against /api/stats before accepting
- api.ts injects Authorization: Basic header on all requests
- App.tsx gates all routes behind login, redirects unknown paths
- Layout.tsx adds logout button
- .gitignore: allow admin-ui/src/lib/ (was blocked by root lib/ rule)

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:50:01 +00:00
XikaandPaperclip 6e6f1a44e4 fix(nginx): use hostname variable in proxy_pass to fix DNS + path rewriting
Using $variable:port with no path appended forces DNS re-resolution
while nginx still forwards the full original request URI unchanged.
Previous attempt ($upstream/api/) was dropping the request path.

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:46:47 +00:00
XikaandPaperclip 3436611714 fix(api+nginx): fix 502 proxy, add /stats + /connection/test, align UI schema
- nginx: add resolver 127.0.0.11 + $upstream var to fix Docker DNS caching
- Add GET /api/stats (accounts/messages counts, last_sync_at)
- Add POST /api/connection/test (IMAP+SMTP inline test)
- AccountResponse: computed active/email aliases, bizdocs stub fields
- MessageResponse: account_name, message_uid, sender, received_at, forwarded_at
- AccountCreate/Update: accept extra UI fields without validation error

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:43:11 +00:00
XikaandPaperclip 34f7fd9cdd feat(deploy): add MySQL backup script (daily cron, 14-day retention)
Installed in CT 244 at /opt/forwarder/backup-mysql.sh with
/etc/cron.d/forwarder-backup running at 03:00 UTC daily.

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:34:12 +00:00
XikaandPaperclip 7100440294 fix(auth): replace passlib with direct bcrypt (compat with bcrypt>=4.0)
passlib 1.7.4 detect_wrap_bug crashes with bcrypt>=4.0 which enforces
72-byte password limit. Use bcrypt directly instead.

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:28:48 +00:00
XikaandPaperclip f3d2533db5 fix(migrations): remove TEXT server_default (MySQL incompatible)
Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:15:40 +00:00
XikaandPaperclip b211d9d8df fix(compose): use alembic migrate service; drop init.sql; use env vars for mysql creds
Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:09:39 +00:00
XikaandPaperclip fd1c1b1ba3 merge: reconcile docker-compose with origin/main (use admin-ui/Dockerfile for web)
Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:07:23 +00:00
1sonhador d1e4725ac3 Add Python API, worker, MySQL migrations and wire admin-ui in Docker.
Backend FastAPI + APScheduler worker with Alembic schema; admin-ui served
via nginx with /api proxy. Unifies Paperclip UI scaffold with local platform code.
2026-07-01 00:04:57 +01:00
XikaandPaperclip d8daca15bd feat(backend): add FastAPI, worker, web nginx — full platform (BIT-26121)
- api/: FastAPI app with MySQL (accounts, forwarding_rules, messages)
  - GET/POST/PUT/DELETE /accounts + /accounts/{id}/test
  - GET /messages + /messages/{id}/retry
  - GET /stats
  - POST /connection/test
  - Auto-runs migrations/init.sql on startup
- worker/: Python IMAP poller + BizDocs upload (schedule every 5 min)
- web/: multi-stage Dockerfile — builds admin-ui via Node, serves via nginx
  - nginx proxies /api/ → api:8000, SPA fallback for React Router
- docker-compose.yml: updated web build context + mysql init.sql mount

Co-Authored-By: Paperclip <[email protected]>
2026-06-30 23:04:54 +00:00
spark 305570458b Merge pull request 'feat(admin-ui): Vite+React Admin UI — BIT-26126' (#1) from task/BIT-26126-admin-ui into main 2026-07-01 00:02:36 +01:00
Xika 8e02d4123b Merge remote-tracking branch 'origin/task/BIT-26126-admin-ui' into task/BIT-26121-backend 2026-06-30 23:01:32 +00:00
spark 09bab7ac0b feat: add .env.example with all required variables (BIT-26128) 2026-06-30 23:53:25 +01:00
spark f2f706d500 feat: add docker-compose.yml with mysql/api/worker/web stack (BIT-26128) 2026-06-30 23:53:17 +01:00
116 changed files with 11113 additions and 174 deletions

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
# Copy to .env — never commit .env
# MySQL
MYSQL_ROOT_PASSWORD=change_me_root
MYSQL_DATABASE=forwarder
MYSQL_USER=forwarder
MYSQL_PASSWORD=change_me_db
# App
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
# Worker
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
+47 -11
View File
@@ -1,19 +1,55 @@
# Node
admin-ui/node_modules/
admin-ui/dist/
# Python
__pycache__/
*.pyc
*.pyo
.env
*.py[cod]
*$py.class
*.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/
.installed.cfg
*.egg
# Virtual environments
.venv/
venv/
ENV/
# Environment
.env
.env.local
# IDE
.idea/
.vscode/
*.swp
*.swo
# Testing
.pytest_cache/
.coverage
htmlcov/
# Legacy state
processed_emails.json
# Docker
.docker/
*.log
storage/deploy-logs/*
!storage/deploy-logs/.gitkeep
# Editor
.vscode/
.idea/
# OS
.DS_Store
Thumbs.db
+26
View File
@@ -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"]
+63 -22
View File
@@ -1,35 +1,76 @@
# 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
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 |
- **Repo:** https://git.bitreport.pt/BitReport.pt/forwarder
- **Paperclip:** http://10.10.50.17:3100/BIT/projects/bizdocs-forwarder
## Stack
- Python (worker + API)
- MySQL
- Docker / Proxmox LXC (deploy target)
| Component | Path | Description |
|-----------|------|-------------|
| 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
cp .env.example .env
# Edit .env with your IMAP credentials and BizDocs API key
docker compose up -d
# Generate ENCRYPTION_KEY: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
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
- Repo: https://git.bitreport.pt/BitReport.pt/forwarder
## Local dev
```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
```
+11
View File
@@ -0,0 +1,11 @@
FROM node:20-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
+25
View File
@@ -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;
}
}
+24 -11
View File
@@ -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 Dashboard from './pages/Dashboard'
import Accounts from './pages/Accounts'
import Emails from './pages/Emails'
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() {
return (
<BrowserRouter>
<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>
</Routes>
</BrowserRouter>
<AuthProvider>
<BrowserRouter>
<AuthedRoutes />
</BrowserRouter>
</AuthProvider>
)
}
+40
View File
@@ -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)
}
+13 -1
View File
@@ -1,5 +1,6 @@
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 = [
{ to: '/', label: 'Dashboard', icon: LayoutDashboard },
@@ -9,6 +10,8 @@ const nav = [
]
export default function Layout() {
const { logout } = useAuth()
return (
<div className="flex h-screen">
<aside className="w-56 bg-gray-900 text-white flex flex-col">
@@ -35,6 +38,15 @@ export default function Layout() {
</NavLink>
))}
</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>
<main className="flex-1 overflow-auto">
<Outlet />
+9 -1
View File
@@ -2,14 +2,22 @@ const styles: Record<string, string> = {
pending: 'bg-yellow-100 text-yellow-800',
forwarded: 'bg-green-100 text-green-800',
failed: 'bg-red-100 text-red-800',
missing_from_mailbox: 'bg-gray-100 text-gray-700',
active: 'bg-green-100 text-green-800',
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 }) {
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'}`}>
{status}
{labels[status] ?? status}
</span>
)
}
+117 -15
View File
@@ -1,8 +1,16 @@
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> {
const res = await fetch(`${BASE}${path}`, {
headers: { 'Content-Type': 'application/json', ...init?.headers },
headers: { 'Content-Type': 'application/json', ...authHeader(), ...init?.headers },
...init,
})
if (!res.ok) {
@@ -13,26 +21,39 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
return res.json()
}
export const DEFAULT_DESTINATION_EMAIL = '[email protected]'
export interface Account {
id: number
name: string
email: string
imap_host: string
source_type: 'imap' | 'webdav'
imap_host: string | null
imap_port: number
imap_user: string
smtp_host: string
imap_user: string | null
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_user: string
bizdocs_api_key: string
bizdocs_entity_id: string
smtp_user: string | null
destination_email: string | null
bizdocs_email: string | null
bizdocs_company_id: string | null
bizdocs_api_base_url: string | null
sync_interval_minutes: number
active: boolean
created_at: string
updated_at: string
}
export type AccountCreate = Omit<Account, 'id' | 'created_at' | 'updated_at'> & {
imap_password: string
smtp_password: string
imap_password?: string
webdav_password?: string
smtp_password?: string
bizdocs_password?: string
}
export interface Message {
@@ -40,14 +61,45 @@ export interface Message {
account_id: number
account_name: string
message_uid: string
message_key: string
subject: string
sender: 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
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 {
accounts_total: number
accounts_active: number
@@ -55,18 +107,38 @@ export interface Stats {
messages_pending: number
messages_forwarded: number
messages_failed: number
messages_missing_from_mailbox?: number
last_sync_at: string | null
}
export interface ConnectionTestResult {
imap_ok: boolean
imap_error: string | null
webdav_ok: boolean
webdav_error: string | null
smtp_ok: boolean
smtp_error: string | null
bizdocs_ok: boolean
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 TestPayload {
imap_host: string
imap_port: number
@@ -90,17 +162,47 @@ export const api = {
update: (id: number, data: Partial<AccountCreate>) =>
request<Account>(`/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
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',
})
},
},
messages: {
list: (params?: { account_id?: number; status?: string; limit?: number; offset?: number }) => {
list: (params?: {
account_id?: number
status?: string
q?: string
limit?: number
offset?: number
}) => {
const q = new URLSearchParams()
if (params?.account_id) q.set('account_id', String(params.account_id))
if (params?.status) q.set('status', params.status)
if (params?.limit) q.set('limit', String(params.limit))
if (params?.offset) q.set('offset', String(params.offset))
return request<Message[]>(`/messages${q.toString() ? '?' + q : ''}`)
if (params?.q) q.set('q', params.q)
if (params?.limit != null) q.set('limit', String(params.limit))
if (params?.offset != null) q.set('offset', String(params.offset))
return request<MessageList>(`/messages${q.toString() ? '?' + q : ''}`)
},
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: {
get: () => request<Stats>('/stats'),
+332 -53
View File
@@ -1,24 +1,46 @@
import { useState } from 'react'
import { api, Account, AccountCreate } from '../lib/api'
import { api, Account, AccountCreate, DEFAULT_DESTINATION_EMAIL } from '../lib/api'
import { useAsync } from '../hooks/useApi'
import Spinner from '../components/Spinner'
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 = {
name: '',
email: '',
source_type: 'imap',
imap_host: '',
imap_port: 993,
imap_user: '',
imap_password: '',
webdav_url: '',
webdav_path: '',
webdav_user: '',
webdav_password: '',
webdav_verify_ssl: true,
delivery_mode: 'smtp',
smtp_host: '',
smtp_port: 587,
smtp_user: '',
smtp_password: '',
bizdocs_api_key: '',
bizdocs_entity_id: '',
active: true,
bizdocs_email: '',
bizdocs_password: '',
bizdocs_company_id: '',
bizdocs_api_base_url: '',
destination_email: DEFAULT_DESTINATION_EMAIL,
sync_interval_minutes: 15,
active: false,
}
function AccountModal({
@@ -33,6 +55,7 @@ function AccountModal({
const [form, setForm] = useState<AccountCreate>({ ...EMPTY_FORM, ...initial })
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const isWebdav = form.source_type === 'webdav'
const set = (k: keyof AccountCreate, v: string | number | boolean) =>
setForm((f) => ({ ...f, [k]: v }))
@@ -41,8 +64,60 @@ function AccountModal({
e.preventDefault()
setSaving(true)
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 {
await onSave(form)
await onSave(payload)
onClose()
} catch (e) {
setError(e instanceof Error ? e.message : String(e))
@@ -61,7 +136,7 @@ function AccountModal({
<label className="block text-xs font-medium text-gray-700 mb-1">{label}</label>
<input
type={type}
value={String(form[key])}
value={String(form[key] ?? '')}
placeholder={placeholder}
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"
@@ -81,40 +156,121 @@ function AccountModal({
<form onSubmit={handleSubmit} className="p-5 space-y-4">
<div className="grid grid-cols-2 gap-4">
{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>
<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>
<label className="block text-xs font-medium text-gray-700 mb-1">Origem dos documentos</label>
<select
value={form.source_type}
onChange={(e) => set('source_type', e.target.value as 'imap' | 'webdav')}
className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm"
>
<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>
</fieldset>
</fieldset>
) : (
<fieldset className="border border-gray-200 rounded-md p-3">
<legend className="text-xs font-semibold text-gray-500 px-1">IMAP</legend>
<div className="grid grid-cols-3 gap-3 mt-1">
{field('Host', 'imap_host', 'text', 'imap.gmail.com')}
{field('Porto', 'imap_port', 'number')}
{field('Utilizador', 'imap_user', 'text')}
<div className="col-span-3">
{field('Password', 'imap_password', 'password')}
</div>
</div>
</fieldset>
)}
<fieldset className="border border-gray-200 rounded-md p-3">
<legend className="text-xs font-semibold text-gray-500 px-1">SMTP</legend>
<div className="grid grid-cols-3 gap-3 mt-1">
{field('Host', 'smtp_host', 'text', 'smtp.gmail.com')}
{field('Porto', 'smtp_port', 'number')}
{field('Utilizador', 'smtp_user', 'text')}
<div className="col-span-3">
{field('Password', 'smtp_password', 'password')}
</div>
<legend className="text-xs font-semibold text-gray-500 px-1">Entrega BizDocs</legend>
<div className="mb-3">
<label className="block text-xs font-medium text-gray-700 mb-1">Modo</label>
<select
value={form.delivery_mode}
onChange={(e) => set('delivery_mode', e.target.value as 'api' | 'smtp')}
className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm"
>
<option value="smtp">Email SMTP (inbox.arquivodigital@…)</option>
<option value="api">API directa (login BizDocs)</option>
</select>
</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 className="border border-gray-200 rounded-md p-3">
<legend className="text-xs font-semibold text-gray-500 px-1">BizDocs</legend>
<div className="grid grid-cols-2 gap-3 mt-1">
{field('API Key', 'bizdocs_api_key', 'password')}
{field('Entity ID', 'bizdocs_entity_id')}
</div>
</fieldset>
{form.delivery_mode === 'smtp' && (
<p className="text-xs text-gray-500 -mt-2">
O remetente SMTP tem de estar autorizado como mailbox no portal BizDocs.
</p>
)}
<label className="flex items-center gap-2 cursor-pointer">
<input
@@ -165,7 +321,10 @@ export default function Accounts() {
account: null,
})
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 [syncingId, setSyncingId] = useState<number | null>(null)
const [testBatchSize, setTestBatchSize] = useState(DEFAULT_TEST_BATCH)
const openNew = () => setModal({ open: true, account: null })
const openEdit = (a: Account) => setModal({ open: true, account: a })
@@ -190,11 +349,16 @@ export default function Accounts() {
setTestingId(id)
try {
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[] = []
if (!r.imap_ok) parts.push(`IMAP: ${r.imap_error}`)
if (!r.smtp_ok) parts.push(`SMTP: ${r.smtp_error}`)
if (!r.bizdocs_ok) parts.push(`BizDocs: ${r.bizdocs_error}`)
if (isWebdav && !r.webdav_ok) parts.push(`WebDAV: ${r.webdav_error}`)
if (!isWebdav && !r.imap_ok) parts.push(`IMAP: ${r.imap_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) => ({
...prev,
[id]: { ok, msg: ok ? 'Ligação OK' : parts.join(' | ') },
@@ -209,12 +373,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 (
<div className="p-6">
<div className="flex items-center justify-between mb-6">
<div>
<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>
<button
onClick={openNew}
@@ -235,6 +442,27 @@ export default function Accounts() {
</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 && (
<div className="text-center py-12 text-gray-400 text-sm">
Nenhuma conta configurada. Clique em "Nova conta" para começar.
@@ -247,8 +475,9 @@ export default function Accounts() {
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">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">IMAP</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Origem</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Identificador</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Destino BizDocs</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
</tr>
@@ -257,24 +486,64 @@ export default function Accounts() {
{accounts.map((a) => (
<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 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-500 text-xs">
{a.imap_host}:{a.imap_port}
<td className="px-4 py-3 text-gray-500 text-xs truncate max-w-[200px]" title={a.destination_email || ''}>
{a.delivery_mode === 'api' ? 'API BizDocs' : a.destination_email}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
<StatusBadge status={a.active ? 'active' : 'inactive'} />
{testResults[a.id] && (
<div className="flex flex-col gap-1">
<div className="flex items-center gap-2">
<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
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>
)}
</div>
</td>
<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
title="Testar ligação"
onClick={() => handleTest(a.id)}
@@ -313,13 +582,23 @@ export default function Accounts() {
? {
name: modal.account.name,
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_user: modal.account.imap_user,
smtp_host: modal.account.smtp_host,
imap_user: modal.account.imap_user || '',
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_user: modal.account.smtp_user,
bizdocs_entity_id: modal.account.bizdocs_entity_id,
smtp_user: modal.account.smtp_user || '',
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,
}
: null
+354 -60
View File
@@ -1,29 +1,194 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { api, Message } from '../lib/api'
import { useAsync } from '../hooks/useApi'
import Spinner from '../components/Spinner'
import StatusBadge from '../components/StatusBadge'
import { RefreshCw, RotateCcw } from 'lucide-react'
import { ChevronLeft, ChevronRight, RefreshCw, RotateCcw, 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() {
const [filterStatus, setFilterStatus] = useState('')
const [searchInput, setSearchInput] = useState('')
const [searchQuery, setSearchQuery] = useState('')
const [page, setPage] = useState(0)
const [retryingId, setRetryingId] = useState<number | null>(null)
const [actionMsg, setActionMsg] = useState<{ ok: boolean; text: string } | null>(null)
const [batchRetrying, setBatchRetrying] = useState(false)
const [queueInfo, setQueueInfo] = useState<import('../lib/api').ForwardQueueStatus | null>(null)
const { data: messages, loading, error, reload } = useAsync<Message[]>(
() => api.messages.list({ status: filterStatus || undefined, limit: 100 }),
[filterStatus],
const loadQueueStatus = async () => {
try {
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) => {
setRetryingId(id)
setActionMsg(null)
try {
await api.messages.retry(id)
setActionMsg({ ok: true, text: `Mensagem #${id} reencaminhada com sucesso.` })
reload()
} catch (e) {
setActionMsg({
ok: false,
text: e instanceof Error ? e.message : `Retry falhou (#${id})`,
})
} finally {
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 (
<div className="p-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>
</div>
<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
value={filterStatus}
onChange={(e) => setFilterStatus(e.target.value)}
@@ -41,6 +234,7 @@ export default function Emails() {
<option value="pending">Pendente</option>
<option value="forwarded">Reencaminhado</option>
<option value="failed">Falhado</option>
<option value="missing_from_mailbox">Apagado da mailbox</option>
</select>
<button
onClick={reload}
@@ -51,78 +245,178 @@ export default function Emails() {
</div>
</div>
<div className="mb-4 flex items-center gap-2 max-w-xl">
<div className="relative flex-1">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
<input
type="search"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder="Pesquisar assunto, remetente, pasta, Message-ID ou #id…"
className="w-full pl-9 pr-9 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
/>
{searchInput && (
<button
type="button"
onClick={() => setSearchInput('')}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600"
title="Limpar pesquisa"
>
<X size={14} />
</button>
)}
</div>
{searchQuery && (
<span className="text-xs text-gray-500 whitespace-nowrap">
{total} resultado{total === 1 ? '' : 's'}
</span>
)}
</div>
{queueInfo && (queueInfo.pending > 0 || queueInfo.forwards_used_last_hour > 0) && (
<div className="mb-4 px-4 py-3 rounded-md text-sm border bg-sky-50 border-sky-200 text-sky-900">
<strong>Fila de reenvio:</strong> {queueInfo.pending} pendente
{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 && (
<div className="flex justify-center py-12">
<Spinner />
</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 && (
<div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-md text-sm">
{error}
</div>
)}
{messages && messages.length === 0 && (
{messages && messages.length === 0 && !loading && (
<div className="text-center py-12 text-gray-400 text-sm">
Nenhuma mensagem{filterStatus ? ` com estado "${filterStatus}"` : ''}.
Nenhuma mensagem
{searchQuery ? ` para "${searchQuery}"` : ''}
{filterStatus ? ` com estado "${filterStatus}"` : ''}.
</div>
)}
{messages && messages.length > 0 && (
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Recebido</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
</tr>
</thead>
<tbody className="divide-y divide-gray-100">
{messages.map((m) => (
<tr key={m.id} className="hover:bg-gray-50">
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
<td className="px-4 py-3 font-medium truncate max-w-xs" title={m.subject}>
{m.subject || '(sem assunto)'}
</td>
<td className="px-4 py-3 text-gray-600 text-xs truncate max-w-[180px]">{m.sender}</td>
<td className="px-4 py-3 text-gray-500 text-xs whitespace-nowrap">
{new Date(m.received_at).toLocaleString('pt-PT')}
</td>
<td className="px-4 py-3">
<div>
<StatusBadge status={m.status} />
{m.error && (
<p className="text-xs text-red-500 mt-0.5 truncate max-w-xs" title={m.error}>
{m.error}
</p>
)}
</div>
</td>
<td className="px-4 py-3 text-right">
{m.status === 'failed' && (
<button
title="Tentar novamente"
onClick={() => handleRetry(m.id)}
disabled={retryingId === m.id}
className="p-1.5 text-gray-400 hover:text-indigo-600 disabled:opacity-40"
>
{retryingId === m.id ? (
<Spinner className="h-4 w-4" />
) : (
<RotateCcw size={14} />
)}
</button>
)}
</td>
<>
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Conta</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Assunto</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Remetente</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Data email</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Pasta</th>
<th className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Estado</th>
<th className="text-right px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">Ações</th>
</tr>
))}
</tbody>
</table>
</div>
</thead>
<tbody className="divide-y divide-gray-100">
{messages.map((m: Message) => (
<tr key={m.id} className="hover:bg-gray-50">
<td className="px-4 py-3 text-gray-500 text-xs">{m.account_name}</td>
<td className="px-4 py-3 font-medium truncate max-w-xs">
<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>
)
+78
View File
@@ -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
View File
@@ -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
+11
View File
@@ -0,0 +1,11 @@
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
View File
Whitespace-only changes.
+16
View File
@@ -0,0 +1,16 @@
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
mysql_host: str = "mysql"
mysql_port: int = 3306
mysql_database: str = "forwarder"
mysql_user: str = "forwarder_app"
mysql_password: str
secret_key: str
class Config:
env_file = ".env"
settings = Settings()
+32
View File
@@ -0,0 +1,32 @@
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, declarative_base
from .config import settings
DATABASE_URL = (
f"mysql+pymysql://{settings.mysql_user}:{settings.mysql_password}"
f"@{settings.mysql_host}:{settings.mysql_port}/{settings.mysql_database}"
"?charset=utf8mb4"
)
engine = create_engine(DATABASE_URL, pool_pre_ping=True, pool_recycle=3600)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def run_migrations():
"""Apply init.sql on startup if tables are absent."""
import pathlib
sql_file = pathlib.Path(__file__).parent.parent / "migrations" / "init.sql"
statements = [s.strip() for s in sql_file.read_text().split(";") if s.strip()]
with engine.connect() as conn:
for stmt in statements:
conn.execute(text(stmt))
conn.commit()
+31
View File
@@ -0,0 +1,31 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from .database import run_migrations
from .routers import accounts, messages, stats, connection, rules
app = FastAPI(title="BizDocs Forwarder API", version="1.0.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
def startup():
run_migrations()
@app.get("/health")
def health():
return {"status": "ok"}
app.include_router(accounts.router)
app.include_router(messages.router)
app.include_router(stats.router)
app.include_router(connection.router)
app.include_router(rules.router)
+76
View File
@@ -0,0 +1,76 @@
from sqlalchemy import (
Column, Integer, SmallInteger, String, Text, Boolean,
DateTime, Enum, ForeignKey, func,
)
from sqlalchemy.orm import relationship
from .database import Base
class Account(Base):
__tablename__ = "accounts"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(255), nullable=False)
imap_host = Column(String(255), nullable=False)
imap_port = Column(SmallInteger, nullable=False, default=993)
imap_ssl = Column(Boolean, nullable=False, default=True)
email = Column(String(255), nullable=False, unique=True)
imap_user = Column(String(255), nullable=False)
imap_password = Column(Text, nullable=False)
smtp_host = Column(String(255))
smtp_port = Column(SmallInteger, default=587)
smtp_user = Column(String(255))
smtp_password = Column(Text)
folder = Column(String(255), nullable=False, default="INBOX")
bizdocs_api_key = Column(Text, nullable=False)
bizdocs_entity_id = Column(String(100))
active = Column(Boolean, nullable=False, default=True)
last_uid = Column(Integer, nullable=False, default=0)
last_checked_at = Column(DateTime)
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
rules = relationship("ForwardingRule", back_populates="account", cascade="all, delete-orphan")
messages = relationship("Message", back_populates="account", cascade="all, delete-orphan")
class ForwardingRule(Base):
__tablename__ = "forwarding_rules"
id = Column(Integer, primary_key=True, index=True)
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False)
name = Column(String(255), nullable=False)
filter_from = Column(String(500))
filter_subject = Column(String(500))
filter_has_attachment = Column(Boolean, nullable=False, default=True)
allowed_extensions = Column(String(200), nullable=False, default="pdf")
enabled = Column(Boolean, nullable=False, default=True)
created_at = Column(DateTime, server_default=func.now())
account = relationship("Account", back_populates="rules")
messages = relationship("Message", back_populates="rule")
class Message(Base):
__tablename__ = "messages"
id = Column(Integer, primary_key=True, index=True)
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False)
rule_id = Column(Integer, ForeignKey("forwarding_rules.id", ondelete="SET NULL"))
message_uid = Column(String(100), nullable=False)
subject = Column(String(500))
sender = Column(String(255))
received_at = Column(DateTime)
filename = Column(String(500))
file_size_bytes = Column(Integer)
status = Column(
Enum("pending", "forwarded", "failed"),
nullable=False, default="pending",
)
bizdocs_doc_id = Column(String(255))
error = Column(Text)
forwarded_at = Column(DateTime)
attempted_at = Column(DateTime, server_default=func.now())
account = relationship("Account", back_populates="messages")
rule = relationship("ForwardingRule", back_populates="messages")
View File
Whitespace-only changes.
+77
View File
@@ -0,0 +1,77 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, text
from sqlalchemy.orm import Session
from typing import List
from ..database import get_db
from ..models import Account
from ..schemas import AccountCreate, AccountUpdate, AccountOut, ConnectionTestResult, TestPayload
router = APIRouter(prefix="/accounts", tags=["accounts"])
@router.get("/", response_model=List[AccountOut])
def list_accounts(db: Session = Depends(get_db)):
return db.query(Account).all()
@router.post("/", response_model=AccountOut, status_code=201)
def create_account(payload: AccountCreate, db: Session = Depends(get_db)):
if db.query(Account).filter(Account.email == payload.email).first():
raise HTTPException(status_code=409, detail="Account with this email already exists")
obj = Account(**payload.model_dump())
db.add(obj)
db.commit()
db.refresh(obj)
return obj
@router.get("/{account_id}", response_model=AccountOut)
def get_account(account_id: int, db: Session = Depends(get_db)):
obj = db.get(Account, account_id)
if not obj:
raise HTTPException(status_code=404, detail="Account not found")
return obj
@router.put("/{account_id}", response_model=AccountOut)
@router.patch("/{account_id}", response_model=AccountOut)
def update_account(account_id: int, payload: AccountUpdate, db: Session = Depends(get_db)):
obj = db.get(Account, account_id)
if not obj:
raise HTTPException(status_code=404, detail="Account not found")
for field, value in payload.model_dump(exclude_unset=True).items():
setattr(obj, field, value)
db.commit()
db.refresh(obj)
return obj
@router.delete("/{account_id}", status_code=204)
def delete_account(account_id: int, db: Session = Depends(get_db)):
obj = db.get(Account, account_id)
if not obj:
raise HTTPException(status_code=404, detail="Account not found")
db.delete(obj)
db.commit()
@router.post("/{account_id}/test", response_model=ConnectionTestResult)
def test_account(account_id: int, db: Session = Depends(get_db)):
obj = db.get(Account, account_id)
if not obj:
raise HTTPException(status_code=404, detail="Account not found")
payload = TestPayload(
imap_host=obj.imap_host,
imap_port=obj.imap_port,
imap_user=obj.imap_user,
imap_password=obj.imap_password,
smtp_host=obj.smtp_host,
smtp_port=obj.smtp_port,
smtp_user=obj.smtp_user,
smtp_password=obj.smtp_password,
bizdocs_api_key=obj.bizdocs_api_key,
bizdocs_entity_id=obj.bizdocs_entity_id,
)
from .connection import _run_test
return _run_test(payload)
+77
View File
@@ -0,0 +1,77 @@
"""Connection test endpoints — IMAP, SMTP, BizDocs."""
import imaplib
import smtplib
import httpx
import logging
from fastapi import APIRouter
from ..schemas import TestPayload, ConnectionTestResult
router = APIRouter(prefix="/connection", tags=["connection"])
log = logging.getLogger(__name__)
def _test_imap(payload: TestPayload) -> tuple[bool, str | None]:
try:
if payload.imap_port in (993, 995) or True: # always try SSL first
imap = imaplib.IMAP4_SSL(payload.imap_host, payload.imap_port)
else:
imap = imaplib.IMAP4(payload.imap_host, payload.imap_port)
imap.login(payload.imap_user, payload.imap_password)
imap.logout()
return True, None
except Exception as exc:
return False, str(exc)
def _test_smtp(payload: TestPayload) -> tuple[bool, str | None]:
if not payload.smtp_host or not payload.smtp_user or not payload.smtp_password:
return True, None # SMTP not configured — skip
try:
with smtplib.SMTP(payload.smtp_host, payload.smtp_port or 587, timeout=10) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.login(payload.smtp_user, payload.smtp_password)
return True, None
except Exception as exc:
return False, str(exc)
def _test_bizdocs(payload: TestPayload) -> tuple[bool, str | None]:
if not payload.bizdocs_api_key:
return True, None # not configured — skip
try:
with httpx.Client(timeout=10) as client:
# Generic check: hit the API root or /health
resp = client.get(
"https://app.bizdocs.pt/api/health",
headers={"Authorization": f"Bearer {payload.bizdocs_api_key}"},
)
if resp.status_code in (200, 204, 401, 403):
# 401/403 means we reached the API (key may be wrong but endpoint responded)
return resp.status_code not in (401, 403), (
None if resp.status_code not in (401, 403) else f"HTTP {resp.status_code}"
)
resp.raise_for_status()
return True, None
except Exception as exc:
return False, str(exc)
def _run_test(payload: TestPayload) -> ConnectionTestResult:
imap_ok, imap_err = _test_imap(payload)
smtp_ok, smtp_err = _test_smtp(payload)
bdocs_ok, bdocs_err = _test_bizdocs(payload)
return ConnectionTestResult(
imap_ok=imap_ok,
imap_error=imap_err,
smtp_ok=smtp_ok,
smtp_error=smtp_err,
bizdocs_ok=bdocs_ok,
bizdocs_error=bdocs_err,
)
@router.post("/test", response_model=ConnectionTestResult)
def test_connection(payload: TestPayload):
return _run_test(payload)
+58
View File
@@ -0,0 +1,58 @@
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session, joinedload
from typing import List, Optional
from ..database import get_db
from ..models import Message, Account
from ..schemas import MessageOut
router = APIRouter(prefix="/messages", tags=["messages"])
@router.get("/", response_model=List[MessageOut])
def list_messages(
account_id: Optional[int] = None,
status: Optional[str] = None,
limit: int = Query(default=50, le=500),
offset: int = 0,
db: Session = Depends(get_db),
):
q = (
db.query(Message)
.options(joinedload(Message.account))
.order_by(Message.attempted_at.desc())
)
if account_id is not None:
q = q.filter(Message.account_id == account_id)
if status is not None:
q = q.filter(Message.status == status)
items = q.offset(offset).limit(limit).all()
out = []
for m in items:
d = MessageOut.model_validate(m)
d.account_name = m.account.name if m.account else None
out.append(d)
return out
@router.get("/{message_id}", response_model=MessageOut)
def get_message(message_id: int, db: Session = Depends(get_db)):
obj = db.get(Message, message_id)
if not obj:
raise HTTPException(status_code=404, detail="Message not found")
return obj
@router.post("/{message_id}/retry", status_code=202)
def retry_message(message_id: int, db: Session = Depends(get_db)):
obj = db.get(Message, message_id)
if not obj:
raise HTTPException(status_code=404, detail="Message not found")
if obj.status == "forwarded":
raise HTTPException(status_code=409, detail="Message already forwarded")
obj.status = "pending"
obj.error = None
obj.forwarded_at = None
db.commit()
return {"queued": True}
+57
View File
@@ -0,0 +1,57 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from ..database import get_db
from ..models import ForwardingRule, Account
from ..schemas import RuleCreate, RuleUpdate, RuleOut
router = APIRouter(prefix="/rules", tags=["rules"])
@router.get("/", response_model=List[RuleOut])
def list_rules(account_id: int | None = None, db: Session = Depends(get_db)):
q = db.query(ForwardingRule)
if account_id is not None:
q = q.filter(ForwardingRule.account_id == account_id)
return q.all()
@router.post("/", response_model=RuleOut, status_code=201)
def create_rule(payload: RuleCreate, db: Session = Depends(get_db)):
if not db.get(Account, payload.account_id):
raise HTTPException(status_code=404, detail="Account not found")
obj = ForwardingRule(**payload.model_dump())
db.add(obj)
db.commit()
db.refresh(obj)
return obj
@router.get("/{rule_id}", response_model=RuleOut)
def get_rule(rule_id: int, db: Session = Depends(get_db)):
obj = db.get(ForwardingRule, rule_id)
if not obj:
raise HTTPException(status_code=404, detail="Rule not found")
return obj
@router.patch("/{rule_id}", response_model=RuleOut)
def update_rule(rule_id: int, payload: RuleUpdate, db: Session = Depends(get_db)):
obj = db.get(ForwardingRule, rule_id)
if not obj:
raise HTTPException(status_code=404, detail="Rule not found")
for field, value in payload.model_dump(exclude_unset=True).items():
setattr(obj, field, value)
db.commit()
db.refresh(obj)
return obj
@router.delete("/{rule_id}", status_code=204)
def delete_rule(rule_id: int, db: Session = Depends(get_db)):
obj = db.get(ForwardingRule, rule_id)
if not obj:
raise HTTPException(status_code=404, detail="Rule not found")
db.delete(obj)
db.commit()
+34
View File
@@ -0,0 +1,34 @@
from fastapi import APIRouter, Depends
from sqlalchemy import func, select
from sqlalchemy.orm import Session
from ..database import get_db
from ..models import Account, Message
from ..schemas import StatsOut
router = APIRouter(tags=["stats"])
@router.get("/stats", response_model=StatsOut)
def get_stats(db: Session = Depends(get_db)):
accounts_total = db.query(func.count(Account.id)).scalar() or 0
accounts_active = db.query(func.count(Account.id)).filter(Account.active == 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 == "pending").scalar() or 0
messages_forwarded = db.query(func.count(Message.id)).filter(Message.status == "forwarded").scalar() or 0
messages_failed = db.query(func.count(Message.id)).filter(Message.status == "failed").scalar() or 0
last_sync = (
db.query(func.max(Account.last_checked_at)).scalar()
)
return StatsOut(
accounts_total=accounts_total,
accounts_active=accounts_active,
messages_total=messages_total,
messages_pending=messages_pending,
messages_forwarded=messages_forwarded,
messages_failed=messages_failed,
last_sync_at=last_sync,
)
+155
View File
@@ -0,0 +1,155 @@
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
# ── Account ──────────────────────────────────────────────────────────────────
class AccountCreate(BaseModel):
name: str
email: str
imap_host: str
imap_port: int = 993
imap_ssl: bool = True
imap_user: str
imap_password: str
smtp_host: Optional[str] = None
smtp_port: Optional[int] = 587
smtp_user: Optional[str] = None
smtp_password: Optional[str] = None
folder: str = "INBOX"
bizdocs_api_key: str
bizdocs_entity_id: Optional[str] = None
active: bool = True
class AccountUpdate(BaseModel):
name: Optional[str] = None
imap_host: Optional[str] = None
imap_port: Optional[int] = None
imap_ssl: Optional[bool] = None
imap_user: Optional[str] = None
imap_password: Optional[str] = None
smtp_host: Optional[str] = None
smtp_port: Optional[int] = None
smtp_user: Optional[str] = None
smtp_password: Optional[str] = None
folder: Optional[str] = None
bizdocs_api_key: Optional[str] = None
bizdocs_entity_id: Optional[str] = None
active: Optional[bool] = None
class AccountOut(BaseModel):
id: int
name: str
email: str
imap_host: str
imap_port: int
imap_ssl: bool
imap_user: str
smtp_host: Optional[str]
smtp_port: Optional[int]
smtp_user: Optional[str]
folder: str
bizdocs_entity_id: Optional[str]
active: bool
last_uid: int
last_checked_at: Optional[datetime]
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
# ── Message ───────────────────────────────────────────────────────────────────
class MessageOut(BaseModel):
id: int
account_id: int
account_name: Optional[str] = None
message_uid: str
subject: Optional[str]
sender: Optional[str]
received_at: Optional[datetime]
filename: Optional[str]
file_size_bytes: Optional[int]
status: str
bizdocs_doc_id: Optional[str]
error: Optional[str]
forwarded_at: Optional[datetime]
attempted_at: datetime
model_config = {"from_attributes": True}
# ── Stats ─────────────────────────────────────────────────────────────────────
class StatsOut(BaseModel):
accounts_total: int
accounts_active: int
messages_total: int
messages_pending: int
messages_forwarded: int
messages_failed: int
last_sync_at: Optional[datetime]
# ── Connection test ───────────────────────────────────────────────────────────
class TestPayload(BaseModel):
imap_host: str
imap_port: int
imap_user: str
imap_password: str
smtp_host: Optional[str] = None
smtp_port: Optional[int] = None
smtp_user: Optional[str] = None
smtp_password: Optional[str] = None
bizdocs_api_key: Optional[str] = None
bizdocs_entity_id: Optional[str] = None
class ConnectionTestResult(BaseModel):
imap_ok: bool
imap_error: Optional[str]
smtp_ok: bool
smtp_error: Optional[str]
bizdocs_ok: bool
bizdocs_error: Optional[str]
# ── Forwarding rules ──────────────────────────────────────────────────────────
class RuleCreate(BaseModel):
account_id: int
name: str
filter_from: Optional[str] = None
filter_subject: Optional[str] = None
filter_has_attachment: bool = True
allowed_extensions: str = "pdf"
enabled: bool = True
class RuleUpdate(BaseModel):
name: Optional[str] = None
filter_from: Optional[str] = None
filter_subject: Optional[str] = None
filter_has_attachment: Optional[bool] = None
allowed_extensions: Optional[str] = None
enabled: Optional[bool] = None
class RuleOut(BaseModel):
id: int
account_id: int
name: str
filter_from: Optional[str]
filter_subject: Optional[str]
filter_has_attachment: bool
allowed_extensions: str
enabled: bool
created_at: datetime
model_config = {"from_attributes": True}
+60
View File
@@ -0,0 +1,60 @@
-- BizDocs Forwarder — initial schema
-- Run once on fresh DB; idempotent via IF NOT EXISTS
CREATE TABLE IF NOT EXISTS accounts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
imap_host VARCHAR(255) NOT NULL,
imap_port SMALLINT NOT NULL DEFAULT 993,
imap_ssl BOOLEAN NOT NULL DEFAULT TRUE,
email VARCHAR(255) NOT NULL,
imap_user VARCHAR(255) NOT NULL,
imap_password TEXT NOT NULL,
smtp_host VARCHAR(255),
smtp_port SMALLINT DEFAULT 587,
smtp_user VARCHAR(255),
smtp_password TEXT,
folder VARCHAR(255) NOT NULL DEFAULT 'INBOX',
bizdocs_api_key TEXT NOT NULL,
bizdocs_entity_id VARCHAR(100),
active BOOLEAN NOT NULL DEFAULT TRUE,
last_uid INT NOT NULL DEFAULT 0,
last_checked_at DATETIME,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uq_accounts_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS forwarding_rules (
id INT AUTO_INCREMENT PRIMARY KEY,
account_id INT NOT NULL,
name VARCHAR(255) NOT NULL,
filter_from VARCHAR(500),
filter_subject VARCHAR(500),
filter_has_attachment BOOLEAN NOT NULL DEFAULT TRUE,
allowed_extensions VARCHAR(200) NOT NULL DEFAULT 'pdf',
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS messages (
id INT AUTO_INCREMENT PRIMARY KEY,
account_id INT NOT NULL,
rule_id INT,
message_uid VARCHAR(100) NOT NULL,
subject VARCHAR(500),
sender VARCHAR(255),
received_at DATETIME,
filename VARCHAR(500),
file_size_bytes INT,
status ENUM('pending','forwarded','failed') NOT NULL DEFAULT 'pending',
bizdocs_doc_id VARCHAR(255),
error TEXT,
forwarded_at DATETIME,
attempted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE,
FOREIGN KEY (rule_id) REFERENCES forwarding_rules(id) ON DELETE SET NULL,
INDEX idx_msg_account_status (account_id, status),
INDEX idx_msg_attempted_at (attempted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+9
View File
@@ -0,0 +1,9 @@
fastapi==0.111.0
uvicorn[standard]==0.30.1
sqlalchemy==2.0.30
pymysql==1.1.1
cryptography==42.0.7
pydantic==2.7.1
pydantic-settings==2.2.1
httpx==0.27.0
python-multipart==0.0.9
+10
View File
@@ -0,0 +1,10 @@
FROM php:8.3-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"]
+14
View File
@@ -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
+81
View File
@@ -0,0 +1,81 @@
#!/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
for i in 1 2 3 4 5; do
curl -sf --max-time 8 http://127.0.0.1:8000/api/health >/dev/null && break
log "API not ready yet (attempt $i/5), retrying in 5s..."
sleep 5
done
curl -sf --max-time 8 http://127.0.0.1:8000/api/health >/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)
+17
View File
@@ -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;
}
}
+124
View File
@@ -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,
]);
+89
View File
@@ -0,0 +1,89 @@
services:
mysql:
image: mysql:8.0
restart: unless-stopped
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root}
MYSQL_DATABASE: ${MYSQL_DATABASE:-forwarder}
MYSQL_USER: ${MYSQL_USER:-forwarder}
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-forwarder}
ports:
- "3306:3306"
volumes:
- mysql_data:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uforwarder", "-p${MYSQL_PASSWORD:-forwarder}"]
interval: 10s
timeout: 5s
retries: 5
start_period: 30s
migrate:
build: .
env_file:
- .env
depends_on:
mysql:
condition: service_healthy
command: ["alembic", "upgrade", "head"]
restart: "no"
api:
build:
context: .
args:
FORWARDER_GIT_SHA: ${FORWARDER_GIT_SHA:-unknown}
restart: unless-stopped
ports:
- "8000:8000"
env_file:
- .env
depends_on:
migrate:
condition: service_completed_successfully
command: ["uvicorn", "forwarder.api.app:app", "--host", "0.0.0.0", "--port", "8000", "--app-dir", "src"]
worker:
build:
context: .
args:
FORWARDER_GIT_SHA: ${FORWARDER_GIT_SHA:-unknown}
restart: unless-stopped
env_file:
- .env
depends_on:
migrate:
condition: service_completed_successfully
command: ["forwarder", "worker"]
web:
build:
context: ./admin-ui
dockerfile: Dockerfile
args:
GIT_SHA: ${FORWARDER_GIT_SHA:-unknown}
restart: unless-stopped
ports:
- "8080:80"
depends_on:
- api
deploy-hook:
build:
context: ./deploy
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:
mysql_data:
+58
View File
@@ -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()
+26
View File
@@ -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"}
+159
View File
@@ -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")
+64
View File
@@ -0,0 +1,64 @@
"""Add WebDAV/Nextcloud as document source
Revision ID: 004_webdav
Revises: 003_bizdocs_api
"""
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
revision: str = "004_webdav"
down_revision: Union[str, None] = "003_bizdocs_api"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
op.add_column(
"accounts",
sa.Column(
"source_type",
sa.Enum("imap", "webdav", name="sourcetype"),
nullable=False,
server_default="imap",
),
)
op.add_column("accounts", sa.Column("webdav_url", sa.String(length=512), nullable=True))
op.add_column("accounts", sa.Column("webdav_path", sa.String(length=512), nullable=True))
op.add_column("accounts", sa.Column("webdav_user", sa.String(length=255), nullable=True))
op.add_column("accounts", sa.Column("webdav_password_encrypted", sa.Text(), nullable=True))
op.add_column(
"accounts",
sa.Column(
"webdav_verify_ssl",
sa.Boolean(),
nullable=False,
server_default=sa.text("1"),
),
)
op.alter_column("accounts", "imap_host", existing_type=sa.String(length=255), nullable=True)
op.alter_column("accounts", "imap_user", existing_type=sa.String(length=255), nullable=True)
op.alter_column("accounts", "imap_password_encrypted", existing_type=sa.Text(), nullable=True)
op.execute(
"ALTER TABLE connection_tests MODIFY COLUMN test_type "
"ENUM('imap', 'smtp', 'send', 'webdav') NOT NULL"
)
def downgrade() -> None:
op.execute(
"ALTER TABLE connection_tests MODIFY COLUMN test_type "
"ENUM('imap', 'smtp', 'send') NOT NULL"
)
op.alter_column("accounts", "imap_password_encrypted", existing_type=sa.Text(), nullable=False)
op.alter_column("accounts", "imap_user", existing_type=sa.String(length=255), nullable=False)
op.alter_column("accounts", "imap_host", existing_type=sa.String(length=255), nullable=False)
op.drop_column("accounts", "webdav_verify_ssl")
op.drop_column("accounts", "webdav_password_encrypted")
op.drop_column("accounts", "webdav_user")
op.drop_column("accounts", "webdav_path")
op.drop_column("accounts", "webdav_url")
op.drop_column("accounts", "source_type")
op.execute("DROP TYPE IF EXISTS sourcetype")
@@ -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")
+132
View File
@@ -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")
+39
View File
@@ -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"]
+3
View File
@@ -0,0 +1,3 @@
"""BizDocs Forwarder — multi-account IMAP to BizDocs email forwarder."""
__version__ = "0.1.0"
+15
View File
@@ -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()
View File
Whitespace-only changes.
+56
View File
@@ -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()
+29
View File
@@ -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.
+359
View File
@@ -0,0 +1,359 @@
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,
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.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,
)
+70
View File
@@ -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,
)
+18
View File
@@ -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"),
}
+195
View File
@@ -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)
+195
View File
@@ -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
]
+69
View File
@@ -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,
)
+43
View File
@@ -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
]
+321
View File
@@ -0,0 +1,321 @@
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))
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
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
class ConnectionTestResponse(BaseModel):
success: bool
message: str
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
+5
View File
@@ -0,0 +1,5 @@
"""BizDocs mobile API client."""
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials, BizdocsSession
__all__ = ["BizdocsClient", "BizdocsCredentials", "BizdocsSession"]
+358
View File
@@ -0,0 +1,358 @@
"""BizDocs mobile API client (login + direct document upload)."""
from __future__ import annotations
import logging
import mimetypes
from dataclasses import dataclass
from typing import Any
import httpx
from forwarder.bizdocs.errors import BizdocsAuthError, BizdocsError, BizdocsUploadError
logger = logging.getLogger(__name__)
IDENTITY_ROUTER_URL = "https://bizdocsidentityrouter.azurewebsites.net"
GET_ROUTE_PATH = "/api/GetRoute"
UPLOAD_PATH = "/user/companies/document/file-s3-blob"
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
LOGIN_PATHS = (
"/login",
"/user/login",
"/auth/login",
"/api/login",
"/api/auth/login",
"/user/signInWithPassword",
)
REFRESH_PATHS = (
"/user/getAccessToken",
"/auth/refresh",
"/api/auth/refresh",
"/token/refresh",
)
COMPANIES_PATHS = (
"/user/companies",
"/companies",
"/api/companies",
"/user/getUserCompanies",
)
MOBILE_USER_AGENT = "Bizdocs-Forwarder/1.0 (compatible; Bizdocs Mobi 3.0.2)"
@dataclass(frozen=True)
class BizdocsCredentials:
email: str
password: str
company_id: str
api_base_url: str | None = None
@dataclass
class BizdocsSession:
mobile_api_url: str
access_token: str
refresh_token: str | None = None
def _pick_string(data: dict[str, Any], *keys: str) -> str | None:
for key in keys:
value = data.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _unwrap_payload(body: Any) -> dict[str, Any]:
if not isinstance(body, dict):
return {}
for wrapper in ("data", "result", "payload"):
inner = body.get(wrapper)
if isinstance(inner, dict):
return inner
return body
def _extract_mobile_api_url(body: Any) -> str | None:
data = _unwrap_payload(body)
if not isinstance(data, dict):
return None
return _pick_string(
data,
"mobileApiUrl",
"MobileApiUrl",
"mobile_api_url",
"apiUrl",
"api_url",
"url",
)
def _extract_tokens(body: Any) -> tuple[str | None, str | None]:
data = _unwrap_payload(body)
if not isinstance(data, dict):
return None, None
access = _pick_string(
data,
"accessToken",
"access_token",
"token",
"jwt",
"idToken",
"id_token",
)
refresh = _pick_string(data, "refreshToken", "refresh_token")
return access, refresh
def _extract_document_id(body: Any) -> str | None:
data = _unwrap_payload(body)
if not isinstance(data, dict):
return None
doc_id = _pick_string(data, "id", "documentId", "document_id", "docId", "doc_id")
if doc_id:
return doc_id
document = data.get("document")
if isinstance(document, dict):
return _pick_string(document, "id", "documentId", "document_id")
return None
class BizdocsClient:
def __init__(
self,
*,
identity_router_url: str = IDENTITY_ROUTER_URL,
timeout: float = 60.0,
) -> None:
self._identity_router_url = identity_router_url.rstrip("/")
self._timeout = timeout
def _client(self) -> httpx.Client:
return httpx.Client(
timeout=self._timeout,
follow_redirects=True,
headers={
"Accept": "application/json",
"User-Agent": MOBILE_USER_AGENT,
},
)
def resolve_mobile_api_url(self, email: str, override: str | None = None) -> str:
if override and override.strip():
return override.strip().rstrip("/")
url = f"{self._identity_router_url}{GET_ROUTE_PATH}"
params = {"email": email.strip()}
with self._client() as client:
response = client.get(url, params=params)
if response.status_code == 404:
raise BizdocsError(
"Identity router returned 404 for GetRoute. "
"Set bizdocs_api_base_url on the account if you know the tenant API URL."
)
if response.status_code >= 400:
raise BizdocsError(
f"Identity router failed: HTTP {response.status_code} {response.text[:200]}"
)
if not response.content:
raise BizdocsError("Identity router returned an empty response")
try:
body = response.json()
except ValueError as exc:
raise BizdocsError("Identity router returned non-JSON response") from exc
mobile_url = _extract_mobile_api_url(body)
if not mobile_url:
raise BizdocsError(
f"Identity router response missing mobileApiUrl: {body!r}"
)
return mobile_url.rstrip("/")
def login(self, credentials: BizdocsCredentials) -> BizdocsSession:
mobile_api_url = self.resolve_mobile_api_url(
credentials.email,
credentials.api_base_url,
)
last_error: str | None = None
login_bodies = (
{"email": credentials.email, "password": credentials.password},
{"Email": credentials.email, "Password": credentials.password},
{"username": credentials.email, "password": credentials.password},
)
with self._client() as client:
for path in LOGIN_PATHS:
for body in login_bodies:
url = f"{mobile_api_url}{path}"
try:
response = client.post(url, json=body)
except httpx.HTTPError as exc:
last_error = str(exc)
continue
if response.status_code in (404, 405):
last_error = f"{path}: HTTP {response.status_code}"
continue
if response.status_code >= 400:
last_error = f"{path}: HTTP {response.status_code} {response.text[:200]}"
continue
try:
payload = response.json()
except ValueError:
last_error = f"{path}: non-JSON response"
continue
access, refresh = _extract_tokens(payload)
if access:
logger.info("BizDocs login OK via %s", path)
return BizdocsSession(
mobile_api_url=mobile_api_url,
access_token=access,
refresh_token=refresh,
)
last_error = f"{path}: response missing access token: {payload!r}"
raise BizdocsAuthError(
last_error or f"BizDocs login failed for {credentials.email}"
)
def test_connection(self, credentials: BizdocsCredentials) -> tuple[bool, str]:
try:
session = self.login(credentials)
except BizdocsError as exc:
return False, str(exc)
companies_msg = ""
try:
companies = self.list_companies(session)
if companies:
ids = ", ".join(c["id"] for c in companies[:5])
companies_msg = f"; companies: {ids}"
except BizdocsError as exc:
companies_msg = f"; companies lookup: {exc}"
if credentials.company_id:
return True, f"Login OK ({session.mobile_api_url}){companies_msg}"
return True, f"Login OK ({session.mobile_api_url}){companies_msg} — set company_id"
def list_companies(self, session: BizdocsSession) -> list[dict[str, str]]:
headers = {"Authorization": f"Bearer {session.access_token}"}
with self._client() as client:
for path in COMPANIES_PATHS:
url = f"{session.mobile_api_url}{path}"
try:
response = client.get(url, headers=headers)
except httpx.HTTPError:
continue
if response.status_code >= 400:
continue
try:
body = response.json()
except ValueError:
continue
items = body
if isinstance(body, dict):
for key in ("companies", "data", "items", "results"):
if isinstance(body.get(key), list):
items = body[key]
break
if not isinstance(items, list):
continue
companies: list[dict[str, str]] = []
for item in items:
if not isinstance(item, dict):
continue
company_id = _pick_string(
item,
"id",
"companyId",
"company_id",
"enterpriseId",
"enterprise_id",
)
name = _pick_string(item, "name", "companyName", "company_name") or company_id
if company_id:
companies.append({"id": company_id, "name": name or company_id})
if companies:
return companies
raise BizdocsError("Could not list companies from BizDocs API")
def upload_document(
self,
session: BizdocsSession,
*,
company_id: str,
filename: str,
data: bytes,
content_type: str | None = None,
) -> str:
if len(data) > MAX_UPLOAD_BYTES:
raise BizdocsUploadError(
f"File {filename} exceeds BizDocs limit ({MAX_UPLOAD_BYTES // (1024 * 1024)} MB)"
)
if not content_type:
content_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
url = f"{session.mobile_api_url}{UPLOAD_PATH}"
headers = {"Authorization": f"Bearer {session.access_token}"}
param_variants = (
{"companyId": company_id},
{"company_id": company_id},
{"entityId": company_id},
{"entity_id": company_id},
)
last_error: str | None = None
with self._client() as client:
for params in param_variants:
files = {"file": (filename, data, content_type)}
try:
response = client.post(url, headers=headers, params=params, files=files)
except httpx.HTTPError as exc:
last_error = str(exc)
continue
if response.status_code in (404, 405):
last_error = f"HTTP {response.status_code}"
continue
if response.status_code >= 400:
last_error = f"HTTP {response.status_code} {response.text[:300]}"
continue
doc_id = None
if response.content:
try:
doc_id = _extract_document_id(response.json())
except ValueError:
doc_id = response.text.strip()[:255] or None
if doc_id:
return doc_id
if response.status_code in (200, 201, 204):
return filename
last_error = f"unexpected response: {response.status_code} {response.text[:200]}"
raise BizdocsUploadError(last_error or f"Upload failed for {filename}")
+13
View File
@@ -0,0 +1,13 @@
"""BizDocs API errors."""
class BizdocsError(Exception):
"""Base error for BizDocs API operations."""
class BizdocsAuthError(BizdocsError):
"""Login or token refresh failed."""
class BizdocsUploadError(BizdocsError):
"""Document upload failed."""
+51
View File
@@ -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()
+39
View File
@@ -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()
+35
View File
@@ -0,0 +1,35 @@
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")
return Fernet(key.encode() if isinstance(key, str) else key)
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 "********"
+33
View File
@@ -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",
]
+5
View File
@@ -0,0 +1,5 @@
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
+372
View File
@@ -0,0 +1,372 @@
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)
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")
+41
View File
@@ -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()
View File
Whitespace-only changes.
+109
View File
@@ -0,0 +1,109 @@
"""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 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
+210
View File
@@ -0,0 +1,210 @@
"""Invoice attachment validation — reject icons, inline embeds, and unreadable files."""
from __future__ import annotations
import os
import struct
import xml.etree.ElementTree as element_tree
# BizDocs accepts up to 10 MB; icons / tracking pixels are usually tiny.
MIN_IMAGE_BYTES = 8 * 1024
MIN_PDF_BYTES = 1024
MIN_XML_BYTES = 80
MIN_ZIP_BYTES = 22
MIN_IMAGE_WIDTH = 200
MIN_IMAGE_HEIGHT = 200
# Applied only to small image files (likely logos / UI assets).
_ICON_NAME_HINTS = (
"icon",
"logo",
"signature",
"spacer",
"pixel",
"tracking",
"facebook",
"linkedin",
"twitter",
"instagram",
"banner",
"emoji",
"avatar",
"thumb",
"badge",
"footer",
"header",
"social",
"favicon",
"cid",
"image00",
)
_SMALL_IMAGE_BYTES = 32 * 1024
def _extension_from_filename(filename: str) -> str:
_, ext = os.path.splitext(filename.lower())
return ext
def _looks_like_icon_filename(filename: str) -> bool:
base = os.path.splitext(os.path.basename(filename.lower()))[0]
if not base:
return False
for hint in _ICON_NAME_HINTS:
if hint in base:
return True
return False
def _png_dimensions(data: bytes) -> tuple[int, int] | None:
if len(data) < 24 or not data.startswith(b"\x89PNG\r\n\x1a\n"):
return None
width, height = struct.unpack(">II", data[16:24])
if width <= 0 or height <= 0:
return None
return width, height
def _jpeg_dimensions(data: bytes) -> tuple[int, int] | None:
if len(data) < 4 or not data.startswith(b"\xff\xd8"):
return None
index = 2
data_len = len(data)
while index < data_len - 1:
if data[index] != 0xFF:
index += 1
continue
marker = data[index + 1]
if marker in (
0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,
0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF,
):
if index + 9 > data_len:
return None
height = struct.unpack(">H", data[index + 5 : index + 7])[0]
width = struct.unpack(">H", data[index + 7 : index + 9])[0]
if width <= 0 or height <= 0:
return None
return width, height
if marker in (0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD8, 0xD9):
index += 2
continue
if marker == 0xDA:
break
if index + 4 > data_len:
break
segment_length = struct.unpack(">H", data[index + 2 : index + 4])[0]
if segment_length < 2:
break
index += 2 + segment_length
return None
def _image_meets_min_dimensions(data: bytes, ext: str) -> bool:
dimensions = None
if ext in (".png",):
dimensions = _png_dimensions(data)
elif ext in (".jpg", ".jpeg"):
dimensions = _jpeg_dimensions(data)
if dimensions is None:
return False
width, height = dimensions
if width < MIN_IMAGE_WIDTH or height < MIN_IMAGE_HEIGHT:
return False
return True
def _is_valid_pdf(data: bytes) -> bool:
if len(data) < MIN_PDF_BYTES:
return False
if not data.startswith(b"%PDF-"):
return False
return True
def _is_valid_xml(data: bytes) -> bool:
if len(data) < MIN_XML_BYTES:
return False
sample = data.lstrip()
if not sample.startswith(b"<"):
return False
try:
element_tree.fromstring(data)
except element_tree.ParseError:
return False
return True
def _is_valid_zip(data: bytes) -> bool:
if len(data) < MIN_ZIP_BYTES:
return False
if not data.startswith(b"PK"):
return False
return True
def _is_valid_image(data: bytes, ext: str) -> bool:
if len(data) < MIN_IMAGE_BYTES:
return False
if ext == ".png":
if not data.startswith(b"\x89PNG\r\n\x1a\n"):
return False
elif ext in (".jpg", ".jpeg"):
if not data.startswith(b"\xff\xd8"):
return False
else:
return False
if not _image_meets_min_dimensions(data, ext):
return False
return True
def is_plausible_invoice_file(
data: bytes,
*,
filename: str,
content_type: str,
) -> bool:
"""Return True when decoded bytes look like a real invoice document, not an embed/icon."""
if not data:
return False
ext = _extension_from_filename(filename)
content_type = (content_type or "").lower()
if ext in (".png", ".jpg", ".jpeg") or content_type.startswith("image/"):
if len(data) < MIN_IMAGE_BYTES:
return False
if len(data) <= _SMALL_IMAGE_BYTES and _looks_like_icon_filename(filename):
return False
if ext in (".png", ".jpg", ".jpeg"):
return _is_valid_image(data, ext)
if content_type == "image/png":
return _is_valid_image(data, ".png")
if content_type in ("image/jpeg", "image/jpg"):
return _is_valid_image(data, ".jpeg")
return False
if ext == ".pdf" or content_type == "application/pdf":
return _is_valid_pdf(data)
if ext == ".xml" or content_type in ("application/xml", "text/xml"):
return _is_valid_xml(data)
if ext == ".zip" or content_type in ("application/zip", "application/x-zip-compressed"):
return _is_valid_zip(data)
return False
+246
View File
@@ -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
+171
View File
@@ -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
+208
View File
@@ -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,
)
+6
View File
@@ -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"]
+309
View File
@@ -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
+83
View File
@@ -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
+16
View File
@@ -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}")
+247
View File
@@ -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
View File
Whitespace-only changes.
+445
View File
@@ -0,0 +1,445 @@
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, 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),
"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")),
)
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",
"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"])
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
+46
View File
@@ -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()
+208
View File
@@ -0,0 +1,208 @@
"""Deliver matched email attachments to BizDocs (API or SMTP)."""
from __future__ import annotations
import logging
import mimetypes
import os
from email.message import EmailMessage
import smtplib
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials, BizdocsSession
from forwarder.bizdocs.errors import BizdocsError
from forwarder.db.models import Account, DEFAULT_ALLOWED_EXTENSIONS, DeliveryMode
from forwarder.email.invoice_validation import is_plausible_invoice_file
from forwarder.email.parsing import InvoiceAttachment, collect_matching_attachments
from forwarder.email.smtp_client import SmtpConfig, create_smtp_client, forward_invoice_attachments
logger = logging.getLogger(__name__)
def _bizdocs_credentials(account: Account, password: str) -> BizdocsCredentials:
email = (account.bizdocs_email or account.imap_user or account.webdav_user or "").strip()
company_id = (account.bizdocs_company_id or "").strip()
if not email:
raise ValueError("BizDocs email is required for API delivery")
if not password:
raise ValueError("BizDocs password is required for API delivery")
if not company_id:
raise ValueError("BizDocs company_id is required for API delivery")
api_base = account.bizdocs_api_base_url
if api_base:
api_base = api_base.strip() or None
return BizdocsCredentials(
email=email,
password=password,
company_id=company_id,
api_base_url=api_base,
)
def open_bizdocs_session(account: Account, bizdocs_password: str) -> BizdocsSession:
client = BizdocsClient()
credentials = _bizdocs_credentials(account, bizdocs_password)
return client.login(credentials)
def _extension_allowed(filename: str, allowed_extensions: set[str], include_all: bool) -> bool:
if include_all:
return True
_, ext = os.path.splitext(filename.lower())
return ext in allowed_extensions
def _content_type_for_filename(filename: str) -> str:
guessed = mimetypes.guess_type(filename)[0]
if guessed:
return guessed
return "application/octet-stream"
def _build_synthetic_email(
*,
filename: str,
data: bytes,
content_type: str,
source_label: str,
) -> EmailMessage:
msg = EmailMessage()
msg["Subject"] = filename
msg["From"] = source_label
msg.set_content(
f"Documento importado automaticamente.\n\nOrigem: {source_label}\nFicheiro: {filename}\n"
)
maintype, _, subtype = content_type.partition("/")
if not subtype:
maintype, subtype = "application", "octet-stream"
msg.add_attachment(
data,
maintype=maintype,
subtype=subtype,
filename=filename,
disposition="attachment",
)
return msg
def deliver_invoice_file(
account: Account,
*,
filename: str,
data: bytes,
content_type: str | None = None,
source_label: str = "forwarder",
bizdocs_password: str | None = None,
smtp_config: SmtpConfig | None = None,
smtp: smtplib.SMTP | None = None,
bizdocs_session: BizdocsSession | None = None,
) -> list[str]:
"""Validate and deliver a single invoice file to BizDocs."""
if content_type is None:
content_type = _content_type_for_filename(filename)
if not is_plausible_invoice_file(data, filename=filename, content_type=content_type):
raise ValueError(f"File {filename} failed invoice validation")
if account.delivery_mode == DeliveryMode.api:
if bizdocs_session is None:
if not bizdocs_password:
raise ValueError("BizDocs password required")
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
client = BizdocsClient()
doc_id = client.upload_document(
bizdocs_session,
company_id=account.bizdocs_company_id or "",
filename=filename,
data=data,
content_type=content_type,
)
logger.info("Uploaded %s → BizDocs doc %s", filename, doc_id)
return [doc_id]
if smtp_config is None:
raise ValueError("SMTP config required for email delivery")
synthetic = _build_synthetic_email(
filename=filename,
data=data,
content_type=content_type,
source_label=source_label,
)
forward_invoice_attachments(
synthetic,
smtp_config=smtp_config,
destination_email=account.destination_email or "",
smtp=smtp,
include_all_attachments=True,
)
return []
def deliver_message_attachments(
msg: EmailMessage,
account: Account,
*,
bizdocs_password: str | None = None,
smtp_config: SmtpConfig | None = None,
smtp: smtplib.SMTP | None = None,
bizdocs_session: BizdocsSession | None = None,
) -> list[str]:
"""Upload or SMTP-forward attachments. Returns BizDocs document ids when using API."""
allowed_extensions = set(account.allowed_extensions or list(DEFAULT_ALLOWED_EXTENSIONS))
if account.delivery_mode == DeliveryMode.api:
if bizdocs_session is None:
if not bizdocs_password:
raise ValueError("BizDocs password required")
bizdocs_session = open_bizdocs_session(account, bizdocs_password)
attachments = collect_matching_attachments(
msg,
include_all_attachments=account.include_all_attachments,
allowed_extensions=allowed_extensions,
)
if not attachments:
raise ValueError("No matching attachments to upload")
client = BizdocsClient()
doc_ids: list[str] = []
for attachment in attachments:
doc_id = client.upload_document(
bizdocs_session,
company_id=account.bizdocs_company_id or "",
filename=attachment.filename,
data=attachment.data,
content_type=f"{attachment.maintype}/{attachment.subtype}",
)
doc_ids.append(doc_id)
logger.info("Uploaded %s → BizDocs doc %s", attachment.filename, doc_id)
return doc_ids
if smtp_config is None:
raise ValueError("SMTP config required for email delivery")
forward_invoice_attachments(
msg,
smtp_config=smtp_config,
destination_email=account.destination_email or "",
smtp=smtp,
include_all_attachments=account.include_all_attachments,
allowed_extensions=allowed_extensions,
)
return []
def test_bizdocs_delivery(
account: Account,
bizdocs_password: str,
) -> tuple[bool, str]:
client = BizdocsClient()
try:
credentials = _bizdocs_credentials(account, bizdocs_password)
return client.test_connection(credentials)
except (BizdocsError, ValueError) as exc:
return False, str(exc)
@@ -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
+28
View File
@@ -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)
+52
View File
@@ -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)
+217
View File
@@ -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()
+570
View File
@@ -0,0 +1,570 @@
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,
list_mailboxes,
select_folder_readonly,
should_skip_folder,
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))
for folder in folders:
if stop_all:
break
if should_skip_folder(folder):
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 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:
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:
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
+25
View File
@@ -0,0 +1,25 @@
"""WebDAV package."""
from forwarder.webdav.client import (
WebdavConfig,
WebdavFile,
WebdavNotFoundError,
build_webdav_root,
download_file,
get_webdav_message_key,
list_files,
parse_webdav_message_key,
test_connection,
)
__all__ = [
"WebdavConfig",
"WebdavFile",
"WebdavNotFoundError",
"build_webdav_root",
"download_file",
"get_webdav_message_key",
"list_files",
"parse_webdav_message_key",
"test_connection",
]
+381
View File
@@ -0,0 +1,381 @@
"""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
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 list_files(config: WebdavConfig) -> list[WebdavFile]:
root_url = build_webdav_root(config)
headers = {"Depth": "infinity", "Content-Type": "application/xml; charset=utf-8"}
with _client(config) as client:
response = client.request("PROPFIND", root_url, content=PROPFIND_BODY, headers=headers)
if response.status_code == 404:
raise WebdavNotFoundError(f"WebDAV folder not found: {root_url}")
if response.status_code == 401:
raise WebdavError("WebDAV authentication failed (401)")
if response.status_code >= 400:
raise WebdavError(f"PROPFIND failed: HTTP {response.status_code} {response.text[:200]}")
return _parse_propfind_response(root_url, response.content)
def download_file(config: WebdavConfig, relative_path: str) -> bytes:
root_url = build_webdav_root(config)
path = relative_path.lstrip("/")
file_url = f"{root_url}/{quote(path, safe='/')}"
with _client(config) as client:
response = client.get(file_url)
if response.status_code == 404:
raise WebdavNotFoundError(f"WebDAV file not found: {relative_path}")
if response.status_code == 401:
raise WebdavError("WebDAV authentication failed (401)")
if response.status_code >= 400:
raise WebdavError(
f"GET failed for {relative_path}: HTTP {response.status_code} {response.text[:200]}"
)
return response.content
def test_connection(config: WebdavConfig) -> tuple[bool, str]:
try:
root_url = build_webdav_root(config)
headers = {"Depth": "0", "Content-Type": "application/xml; charset=utf-8"}
with _client(config, timeout=15.0) as client:
response = client.request("PROPFIND", root_url, content=PROPFIND_BODY, headers=headers)
if response.status_code == 401:
return False, "WebDAV authentication failed (401)"
if response.status_code == 404:
return False, f"WebDAV folder not found: {root_url}"
if response.status_code >= 400:
return False, f"WebDAV PROPFIND failed: HTTP {response.status_code}"
files = list_files(config)
return True, f"WebDAV OK — {len(files)} ficheiro(s) em {root_url}"
except WebdavError as exc:
return False, str(exc)
except httpx.HTTPError as exc:
return False, str(exc)
View File
Whitespace-only changes.
+247
View File
@@ -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()
View File
Whitespace-only changes.
+52
View File
@@ -0,0 +1,52 @@
"""BizDocs API client unit tests."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from forwarder.bizdocs.client import BizdocsClient, BizdocsCredentials
def test_identity_router_parses_mobile_api_url():
client = BizdocsClient()
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.content = b'{"mobileApiUrl":"https://api.example.com"}'
mock_response.json.return_value = {"mobileApiUrl": "https://api.example.com"}
with patch.object(client, "_client") as mock_client_factory:
mock_http = MagicMock()
mock_http.__enter__.return_value = mock_http
mock_http.get.return_value = mock_response
mock_client_factory.return_value = mock_http
url = client.resolve_mobile_api_url("[email protected]")
assert url == "https://api.example.com"
def test_login_extracts_access_token():
client = BizdocsClient()
route_response = MagicMock(status_code=200, content=b"{}", json=lambda: {"mobileApiUrl": "https://api.example.com"})
login_response = MagicMock(
status_code=200,
content=b"{}",
json=lambda: {"accessToken": "abc123", "refreshToken": "ref"},
)
with patch.object(client, "_client") as mock_client_factory:
mock_http = MagicMock()
mock_http.__enter__.return_value = mock_http
mock_http.get.return_value = route_response
mock_http.post.return_value = login_response
mock_client_factory.return_value = mock_http
session = client.login(
BizdocsCredentials(
email="[email protected]",
password="secret",
company_id="co-1",
api_base_url="https://api.example.com",
)
)
assert session.access_token == "abc123"
assert session.mobile_api_url == "https://api.example.com"
+105
View File
@@ -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()
+144
View File
@@ -0,0 +1,144 @@
"""Invoice attachment validation tests."""
from __future__ import annotations
import struct
from email.message import EmailMessage
from forwarder.email.invoice_validation import is_plausible_invoice_file
from forwarder.email.parsing import (
DEFAULT_ALLOWED_EXTENSIONS,
collect_matching_attachments,
has_matching_attachment,
)
def _fake_png(width: int, height: int, *, padding: int = 9000) -> bytes:
signature = b"\x89PNG\r\n\x1a\n"
ihdr_data = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
ihdr = struct.pack(">I", 13) + b"IHDR" + ihdr_data + struct.pack(">I", 0)
iend = struct.pack(">I", 0) + b"IEND" + struct.pack(">I", 0xAE426082)
body = signature + ihdr + iend
if len(body) >= padding:
return body
return body + b"\x00" * (padding - len(body))
def _fake_jpeg(width: int, height: int, *, padding: int = 9000) -> bytes:
sof_payload = struct.pack(">BHH", 8, height, width) + b"\x03\x01\x11\x00"
sof = b"\xff\xc0" + struct.pack(">H", len(sof_payload) + 2) + sof_payload
body = b"\xff\xd8" + sof + b"\xff\xd9"
if len(body) >= padding:
return body
return body + b"\x00" * (padding - len(body))
def _msg_with_part(
*,
data: bytes,
filename: str,
content_type: str,
disposition: str = "attachment",
) -> EmailMessage:
msg = EmailMessage()
msg["Subject"] = "Test"
msg.set_content("body")
maintype, subtype = content_type.split("/", 1)
msg.add_attachment(
data,
maintype=maintype,
subtype=subtype,
filename=filename,
disposition=disposition,
)
return msg
def test_rejects_inline_embedded_image():
msg = _msg_with_part(
data=_fake_png(400, 400),
filename="logo.png",
content_type="image/png",
disposition="inline",
)
assert not has_matching_attachment(msg, allowed_extensions=DEFAULT_ALLOWED_EXTENSIONS)
assert collect_matching_attachments(msg) == []
def test_rejects_tiny_tracking_pixel():
msg = _msg_with_part(
data=b"\x89PNG" + b"\x00" * 100,
filename="pixel.png",
content_type="image/png",
disposition="attachment",
)
assert not has_matching_attachment(msg)
def test_rejects_small_icon_by_filename():
msg = _msg_with_part(
data=_fake_png(400, 400, padding=5000),
filename="company-logo.png",
content_type="image/png",
)
assert not is_plausible_invoice_file(
_fake_png(400, 400, padding=5000),
filename="company-logo.png",
content_type="image/png",
)
def test_accepts_large_invoice_scan_jpeg():
data = _fake_jpeg(800, 1200)
msg = _msg_with_part(
data=data,
filename="fatura_123.jpg",
content_type="image/jpeg",
)
assert has_matching_attachment(msg)
attachments = collect_matching_attachments(msg)
assert len(attachments) == 1
assert attachments[0].filename == "fatura_123.jpg"
def test_accepts_valid_pdf_attachment():
pdf = b"%PDF-1.4\n" + (b"% invoice body\n" * 80)
msg = _msg_with_part(
data=pdf,
filename="FT2024.pdf",
content_type="application/pdf",
)
assert has_matching_attachment(msg)
assert len(collect_matching_attachments(msg)) == 1
def test_rejects_truncated_pdf():
msg = _msg_with_part(
data=b"%PDF",
filename="x.pdf",
content_type="application/pdf",
)
assert not has_matching_attachment(msg)
def test_rejects_low_resolution_image():
data = _fake_png(80, 80, padding=9000)
msg = _msg_with_part(
data=data,
filename="scan.png",
content_type="image/png",
)
assert not has_matching_attachment(msg)
def test_accepts_valid_xml():
xml = (
b'<?xml version="1.0" encoding="UTF-8"?>'
b"<Invoice><Id>1</Id><Note>test document</Note></Invoice>"
)
msg = _msg_with_part(
data=xml,
filename="doc.xml",
content_type="application/xml",
)
assert has_matching_attachment(msg)
+19
View File
@@ -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
+58
View File
@@ -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)
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more