From d8daca15bdd7c7260cace99803514b7034ab6e5d Mon Sep 17 00:00:00 2001 From: Xika Date: Tue, 30 Jun 2026 23:04:54 +0000 Subject: [PATCH] =?UTF-8?q?feat(backend):=20add=20FastAPI,=20worker,=20web?= =?UTF-8?q?=20nginx=20=E2=80=94=20full=20platform=20(BIT-26121)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- api/Dockerfile | 11 +++ api/app/__init__.py | 0 api/app/config.py | 16 ++++ api/app/database.py | 32 +++++++ api/app/main.py | 31 +++++++ api/app/models.py | 76 +++++++++++++++++ api/app/routers/__init__.py | 0 api/app/routers/accounts.py | 77 +++++++++++++++++ api/app/routers/connection.py | 77 +++++++++++++++++ api/app/routers/messages.py | 58 +++++++++++++ api/app/routers/rules.py | 57 +++++++++++++ api/app/routers/stats.py | 34 ++++++++ api/app/schemas.py | 155 ++++++++++++++++++++++++++++++++++ api/migrations/init.sql | 60 +++++++++++++ api/requirements.txt | 9 ++ docker-compose.yml | 5 +- web/Dockerfile | 17 ++++ web/nginx.conf | 23 +++++ worker/Dockerfile | 10 +++ worker/bizdocs_client.py | 32 +++++++ worker/db.py | 96 +++++++++++++++++++++ worker/imap_client.py | 112 ++++++++++++++++++++++++ worker/requirements.txt | 6 ++ worker/worker.py | 114 +++++++++++++++++++++++++ 24 files changed, 1106 insertions(+), 2 deletions(-) create mode 100644 api/Dockerfile create mode 100644 api/app/__init__.py create mode 100644 api/app/config.py create mode 100644 api/app/database.py create mode 100644 api/app/main.py create mode 100644 api/app/models.py create mode 100644 api/app/routers/__init__.py create mode 100644 api/app/routers/accounts.py create mode 100644 api/app/routers/connection.py create mode 100644 api/app/routers/messages.py create mode 100644 api/app/routers/rules.py create mode 100644 api/app/routers/stats.py create mode 100644 api/app/schemas.py create mode 100644 api/migrations/init.sql create mode 100644 api/requirements.txt create mode 100644 web/Dockerfile create mode 100644 web/nginx.conf create mode 100644 worker/Dockerfile create mode 100644 worker/bizdocs_client.py create mode 100644 worker/db.py create mode 100644 worker/imap_client.py create mode 100644 worker/requirements.txt create mode 100644 worker/worker.py diff --git a/api/Dockerfile b/api/Dockerfile new file mode 100644 index 0000000..8f75f63 --- /dev/null +++ b/api/Dockerfile @@ -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"] diff --git a/api/app/__init__.py b/api/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/app/config.py b/api/app/config.py new file mode 100644 index 0000000..13b53be --- /dev/null +++ b/api/app/config.py @@ -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() diff --git a/api/app/database.py b/api/app/database.py new file mode 100644 index 0000000..5b1b64a --- /dev/null +++ b/api/app/database.py @@ -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() diff --git a/api/app/main.py b/api/app/main.py new file mode 100644 index 0000000..b1e5e55 --- /dev/null +++ b/api/app/main.py @@ -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) diff --git a/api/app/models.py b/api/app/models.py new file mode 100644 index 0000000..84e7089 --- /dev/null +++ b/api/app/models.py @@ -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") diff --git a/api/app/routers/__init__.py b/api/app/routers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/app/routers/accounts.py b/api/app/routers/accounts.py new file mode 100644 index 0000000..e89eedc --- /dev/null +++ b/api/app/routers/accounts.py @@ -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) diff --git a/api/app/routers/connection.py b/api/app/routers/connection.py new file mode 100644 index 0000000..16c1e94 --- /dev/null +++ b/api/app/routers/connection.py @@ -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) diff --git a/api/app/routers/messages.py b/api/app/routers/messages.py new file mode 100644 index 0000000..326f7cc --- /dev/null +++ b/api/app/routers/messages.py @@ -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} diff --git a/api/app/routers/rules.py b/api/app/routers/rules.py new file mode 100644 index 0000000..80f43dd --- /dev/null +++ b/api/app/routers/rules.py @@ -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() diff --git a/api/app/routers/stats.py b/api/app/routers/stats.py new file mode 100644 index 0000000..39787f7 --- /dev/null +++ b/api/app/routers/stats.py @@ -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, + ) diff --git a/api/app/schemas.py b/api/app/schemas.py new file mode 100644 index 0000000..e39e497 --- /dev/null +++ b/api/app/schemas.py @@ -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} diff --git a/api/migrations/init.sql b/api/migrations/init.sql new file mode 100644 index 0000000..d20f6e0 --- /dev/null +++ b/api/migrations/init.sql @@ -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; diff --git a/api/requirements.txt b/api/requirements.txt new file mode 100644 index 0000000..68987ee --- /dev/null +++ b/api/requirements.txt @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml index 84a2ee7..3b08d07 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,7 @@ services: MYSQL_PASSWORD: ${MYSQL_PASSWORD} volumes: - mysql_data:/var/lib/mysql + - ./api/migrations/init.sql:/docker-entrypoint-initdb.d/init.sql:ro healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"] interval: 10s @@ -60,8 +61,8 @@ services: web: build: - context: ./web - dockerfile: Dockerfile + context: . + dockerfile: web/Dockerfile restart: unless-stopped ports: - "3000:80" diff --git a/web/Dockerfile b/web/Dockerfile new file mode 100644 index 0000000..ae8c06c --- /dev/null +++ b/web/Dockerfile @@ -0,0 +1,17 @@ +# Build stage — compile the React admin UI +FROM node:20-alpine AS builder + +WORKDIR /build +COPY admin-ui/package*.json ./ +RUN npm ci + +COPY admin-ui/ ./ +RUN npm run build + +# Runtime stage — nginx serving static assets +FROM nginx:1.27-alpine + +COPY --from=builder /build/dist /usr/share/nginx/html +COPY web/nginx.conf /etc/nginx/conf.d/default.conf + +EXPOSE 80 diff --git a/web/nginx.conf b/web/nginx.conf new file mode 100644 index 0000000..84bf8f9 --- /dev/null +++ b/web/nginx.conf @@ -0,0 +1,23 @@ +server { + listen 80; + root /usr/share/nginx/html; + index index.html; + + # Proxy API requests to the api container + location /api/ { + proxy_pass http://api:8000/; + proxy_http_version 1.1; + 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_read_timeout 60s; + } + + # SPA fallback: all other routes serve index.html + location / { + try_files $uri $uri/ /index.html; + } + + gzip on; + gzip_types text/plain text/css application/javascript application/json; +} diff --git a/worker/Dockerfile b/worker/Dockerfile new file mode 100644 index 0000000..8738b0c --- /dev/null +++ b/worker/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.12-slim + +WORKDIR /app + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +CMD ["python", "worker.py"] diff --git a/worker/bizdocs_client.py b/worker/bizdocs_client.py new file mode 100644 index 0000000..ddb9d4a --- /dev/null +++ b/worker/bizdocs_client.py @@ -0,0 +1,32 @@ +"""BizDocs upload client.""" +import logging +import httpx + +log = logging.getLogger(__name__) + + +def upload_document( + bizdocs_url: str, + api_key: str, + filename: str, + data: bytes, + entity_id: str | None = None, +) -> str: + """ + Upload *data* as *filename* to the BizDocs API. + Returns the remote document ID string. + Raises on HTTP errors. + """ + url = bizdocs_url.rstrip("/") + "/documents" + headers = {"Authorization": f"Bearer {api_key}"} + files = {"file": (filename, data)} + params = {} + if entity_id: + params["entity_id"] = entity_id + + with httpx.Client(timeout=60) as client: + resp = client.post(url, headers=headers, files=files, params=params) + + resp.raise_for_status() + body = resp.json() + return str(body.get("id") or body.get("document_id") or resp.text) diff --git a/worker/db.py b/worker/db.py new file mode 100644 index 0000000..83aa5b3 --- /dev/null +++ b/worker/db.py @@ -0,0 +1,96 @@ +import os +from sqlalchemy import create_engine, text +from sqlalchemy.orm import sessionmaker + +_url = ( + "mysql+pymysql://{user}:{pw}@{host}:{port}/{db}?charset=utf8mb4".format( + user=os.environ["MYSQL_USER"], + pw=os.environ["MYSQL_PASSWORD"], + host=os.environ.get("MYSQL_HOST", "mysql"), + port=os.environ.get("MYSQL_PORT", "3306"), + db=os.environ.get("MYSQL_DATABASE", "forwarder"), + ) +) +engine = create_engine(_url, pool_pre_ping=True, pool_recycle=3600) +Session = sessionmaker(bind=engine) + + +def get_enabled_accounts(): + with Session() as s: + rows = s.execute( + text( + "SELECT id, imap_host, imap_port, imap_ssl, email, imap_user, imap_password, " + "folder, bizdocs_api_key, bizdocs_entity_id, last_uid " + "FROM accounts WHERE active = 1" + ) + ).mappings().all() + return [dict(r) for r in rows] + + +def get_rules_for_account(account_id: int): + with Session() as s: + rows = s.execute( + text( + "SELECT id, filter_from, filter_subject, filter_has_attachment, allowed_extensions " + "FROM forwarding_rules WHERE account_id = :aid AND enabled = 1" + ), + {"aid": account_id}, + ).mappings().all() + return [dict(r) for r in rows] + + +def create_message(account_id, rule_id, message_uid, subject, sender, received_at, filename, file_size): + with Session() as s: + r = s.execute( + text( + "INSERT INTO messages " + "(account_id, rule_id, message_uid, subject, sender, received_at, " + "filename, file_size_bytes, status, attempted_at) " + "VALUES (:aid, :rid, :uid, :subj, :sndr, :dt, :fn, :sz, 'pending', NOW())" + ), + dict( + aid=account_id, rid=rule_id, uid=str(message_uid), + subj=subject, sndr=sender, dt=received_at, fn=filename, sz=file_size, + ), + ) + s.commit() + return r.lastrowid + + +def update_message(msg_id: int, status: str, bizdocs_doc_id=None, error=None): + with Session() as s: + forwarded_at = "NOW()" if status == "forwarded" else "NULL" + s.execute( + text( + f"UPDATE messages SET status = :st, bizdocs_doc_id = :doc, " + f"error = :err, forwarded_at = {forwarded_at} WHERE id = :mid" + ), + dict(st=status, doc=bizdocs_doc_id, err=error, mid=msg_id), + ) + s.commit() + + +def update_account_uid(account_id: int, last_uid: int): + with Session() as s: + s.execute( + text( + "UPDATE accounts SET last_uid = :uid, last_checked_at = NOW() WHERE id = :aid" + ), + {"uid": last_uid, "aid": account_id}, + ) + s.commit() + + +def get_pending_retries(): + """Return pending messages that were previously failed (retry flow).""" + with Session() as s: + rows = s.execute( + text( + "SELECT m.id, m.account_id, m.message_uid, m.filename, " + "a.imap_host, a.imap_port, a.imap_ssl, a.imap_user, a.imap_password, " + "a.folder, a.bizdocs_api_key, a.bizdocs_entity_id " + "FROM messages m JOIN accounts a ON a.id = m.account_id " + "WHERE m.status = 'pending' AND a.active = 1" + ) + ).mappings().all() + return [dict(r) for r in rows] diff --git a/worker/imap_client.py b/worker/imap_client.py new file mode 100644 index 0000000..fad6d98 --- /dev/null +++ b/worker/imap_client.py @@ -0,0 +1,112 @@ +"""IMAP polling — fetch unseen messages with attachments since last UID.""" +import imaplib +import email +import logging +from email.header import decode_header +from typing import Iterator + +log = logging.getLogger(__name__) + + +def _decode_str(value) -> str: + if value is None: + return "" + parts = decode_header(value) + out = [] + for raw, enc in parts: + if isinstance(raw, bytes): + out.append(raw.decode(enc or "utf-8", errors="replace")) + else: + out.append(raw) + return " ".join(out) + + +def fetch_new_messages(account: dict) -> Iterator[dict]: + """ + Yield dicts per attachment: + {uid, subject, sender, received_at, filename, data (bytes), size} + """ + host = account["imap_host"] + port = int(account["imap_port"]) + ssl = bool(account["imap_ssl"]) + user = account["imap_user"] + pw = account["imap_password"] + folder = account.get("folder", "INBOX") + last_uid = int(account["last_uid"]) + + try: + imap = imaplib.IMAP4_SSL(host, port) if ssl else imaplib.IMAP4(host, port) + except Exception as exc: + log.error("IMAP connect failed for %s: %s", user, exc) + return + + try: + imap.login(user, pw) + except Exception as exc: + log.error("IMAP login failed for %s: %s", user, exc) + imap.logout() + return + + try: + imap.select(folder, readonly=True) + except Exception as exc: + log.error("IMAP select folder %s failed for %s: %s", folder, user, exc) + imap.logout() + return + + try: + typ, data = imap.uid("search", None, f"UID {last_uid + 1}:*") + if typ != "OK" or not data or not data[0]: + return + + uid_list = data[0].split() + for uid_bytes in uid_list: + uid = int(uid_bytes) + if uid <= last_uid: + continue + + typ2, msg_data = imap.uid("fetch", uid_bytes, "(RFC822)") + if typ2 != "OK" or not msg_data or not msg_data[0]: + continue + + raw = msg_data[0][1] + msg = email.message_from_bytes(raw) + + subject = _decode_str(msg.get("Subject", "")) + sender = _decode_str(msg.get("From", "")) + date_str = msg.get("Date", "") + + from email.utils import parsedate_to_datetime + try: + received_at = parsedate_to_datetime(date_str) + except Exception: + received_at = None + + for part in msg.walk(): + if part.get_content_maintype() == "multipart": + continue + if part.get("Content-Disposition") is None: + continue + + filename = part.get_filename() + if not filename: + continue + filename = _decode_str(filename) + data_bytes = part.get_payload(decode=True) + if not data_bytes: + continue + + yield { + "uid": uid, + "subject": subject, + "sender": sender, + "received_at": received_at, + "filename": filename, + "data": data_bytes, + "size": len(data_bytes), + } + finally: + try: + imap.logout() + except Exception: + pass diff --git a/worker/requirements.txt b/worker/requirements.txt new file mode 100644 index 0000000..6c16ce7 --- /dev/null +++ b/worker/requirements.txt @@ -0,0 +1,6 @@ +sqlalchemy==2.0.30 +pymysql==1.1.1 +cryptography==42.0.7 +httpx==0.27.0 +schedule==1.2.2 +python-dotenv==1.0.1 diff --git a/worker/worker.py b/worker/worker.py new file mode 100644 index 0000000..d5b36fc --- /dev/null +++ b/worker/worker.py @@ -0,0 +1,114 @@ +"""BizDocs Forwarder worker — polls IMAP accounts and forwards attachments.""" +import logging +import time + +import schedule + +from db import ( + get_enabled_accounts, get_rules_for_account, + create_message, update_message, update_account_uid, +) +from imap_client import fetch_new_messages +from bizdocs_client import upload_document + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s %(message)s", +) +log = logging.getLogger("worker") + +POLL_INTERVAL_MINUTES = 5 + + +def _rule_matches(rule: dict, msg: dict) -> bool: + if rule["filter_has_attachment"] and not msg["filename"]: + return False + + if rule["filter_from"]: + if rule["filter_from"].lower() not in msg["sender"].lower(): + return False + + if rule["filter_subject"]: + if rule["filter_subject"].lower() not in msg["subject"].lower(): + return False + + ext = msg["filename"].rsplit(".", 1)[-1].lower() if "." in msg["filename"] else "" + allowed = [e.strip().lower() for e in rule["allowed_extensions"].split(",")] + if allowed and ext not in allowed: + return False + + return True + + +def process_account(account: dict): + account_id = account["id"] + log.info("Checking account %s (%s)", account_id, account["email"]) + + max_uid = account["last_uid"] + rules = get_rules_for_account(account_id) + + for msg in fetch_new_messages(account): + uid = msg["uid"] + max_uid = max(max_uid, uid) + + if not rules: + log.debug("No forwarding rules for account %s, skipping uid=%d", account_id, uid) + continue + + matched_rule = next((r for r in rules if _rule_matches(r, msg)), None) + if matched_rule is None: + log.debug("No matching rule for uid=%d file=%s", uid, msg["filename"]) + continue + + msg_id = create_message( + account_id=account_id, + rule_id=matched_rule["id"], + message_uid=uid, + subject=msg["subject"], + sender=msg["sender"], + received_at=msg["received_at"], + filename=msg["filename"], + file_size=msg["size"], + ) + + try: + doc_id = upload_document( + bizdocs_url="https://app.bizdocs.pt/api", + api_key=account["bizdocs_api_key"], + filename=msg["filename"], + data=msg["data"], + entity_id=account.get("bizdocs_entity_id"), + ) + update_message(msg_id, "forwarded", bizdocs_doc_id=doc_id) + log.info("Forwarded %s → bizdocs doc %s", msg["filename"], doc_id) + except Exception as exc: + update_message(msg_id, "failed", error=str(exc)) + log.error("Upload failed for uid=%d file=%s: %s", uid, msg["filename"], exc) + + if max_uid > account["last_uid"]: + update_account_uid(account_id, max_uid) + + +def run(): + accounts = get_enabled_accounts() + if not accounts: + log.info("No enabled accounts, skipping cycle") + return + for account in accounts: + try: + process_account(account) + except Exception as exc: + log.error("Unhandled error on account %s: %s", account.get("email"), exc) + + +def main(): + log.info("BizDocs Forwarder worker starting, poll interval %d min", POLL_INTERVAL_MINUTES) + run() + schedule.every(POLL_INTERVAL_MINUTES).minutes.do(run) + while True: + schedule.run_pending() + time.sleep(30) + + +if __name__ == "__main__": + main()