feat(scrapers): Amazon & Temu invoice downloader + BizDocs upload (BIT-26279/BIT-26280) #3
No files matched your search
@@ -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")
|
||||
@@ -7,7 +7,7 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from forwarder import __version__
|
||||
from forwarder.api.routes import accounts, connection, health, messages, stats, sync_runs
|
||||
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
|
||||
|
||||
@@ -48,6 +48,7 @@ def create_app() -> FastAPI:
|
||||
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
|
||||
|
||||
|
||||
@@ -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
|
||||
]
|
||||
@@ -254,3 +254,68 @@ class HealthResponse(BaseModel):
|
||||
|
||||
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
|
||||
@@ -4,6 +4,12 @@ from forwarder.db.models import (
|
||||
ConnectionTest,
|
||||
ForwardAttempt,
|
||||
Message,
|
||||
ScrapedDocument,
|
||||
ScrapedDocumentStatus,
|
||||
ShopAccount,
|
||||
ShopScrapeRun,
|
||||
ShopScrapeRunStatus,
|
||||
ShopType,
|
||||
SyncRun,
|
||||
User,
|
||||
UserAccount,
|
||||
@@ -15,6 +21,12 @@ __all__ = [
|
||||
"ConnectionTest",
|
||||
"ForwardAttempt",
|
||||
"Message",
|
||||
"ScrapedDocument",
|
||||
"ScrapedDocumentStatus",
|
||||
"ShopAccount",
|
||||
"ShopScrapeRun",
|
||||
"ShopScrapeRunStatus",
|
||||
"ShopType",
|
||||
"SyncRun",
|
||||
"User",
|
||||
"UserAccount",
|
||||
|
||||
@@ -236,3 +236,137 @@ class ConnectionTest(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Shop invoice scrapers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ShopType(str, enum.Enum):
|
||||
temu = "temu"
|
||||
amazon = "amazon"
|
||||
|
||||
|
||||
class ScrapedDocumentStatus(str, enum.Enum):
|
||||
pending = "pending"
|
||||
uploaded = "uploaded"
|
||||
failed = "failed"
|
||||
skipped = "skipped"
|
||||
|
||||
|
||||
class ShopScrapeRunStatus(str, enum.Enum):
|
||||
running = "running"
|
||||
completed = "completed"
|
||||
failed = "failed"
|
||||
|
||||
|
||||
class ShopAccount(Base):
|
||||
"""Credentials for a shop (Temu, Amazon…) to scrape invoices from."""
|
||||
|
||||
__tablename__ = "shop_accounts"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
shop_type: Mapped[ShopType] = mapped_column(Enum(ShopType), nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
||||
sync_interval_minutes: Mapped[int] = mapped_column(Integer, default=60, nullable=False)
|
||||
|
||||
# Shop credentials (encrypted)
|
||||
shop_email_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
shop_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
# Persisted Playwright browser state (cookies + localStorage), encrypted
|
||||
session_state_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
session_state_saved_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
|
||||
# BizDocs delivery
|
||||
bizdocs_email: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
bizdocs_password_encrypted: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
bizdocs_company_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
||||
bizdocs_api_base_url: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
|
||||
last_scraped_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
scraped_docs: Mapped[list[ScrapedDocument]] = relationship(
|
||||
back_populates="shop_account", cascade="all, delete-orphan"
|
||||
)
|
||||
scrape_runs: Mapped[list[ShopScrapeRun]] = relationship(
|
||||
back_populates="shop_account", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
|
||||
class ScrapedDocument(Base):
|
||||
"""One invoice/document scraped from a shop and uploaded to BizDocs."""
|
||||
|
||||
__tablename__ = "scraped_documents"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("shop_account_id", "order_id", name="uq_shop_account_order"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
shop_account_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("shop_accounts.id"), nullable=False, index=True
|
||||
)
|
||||
order_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
filename: Mapped[str] = mapped_column(String(512), default="", nullable=False)
|
||||
status: Mapped[ScrapedDocumentStatus] = mapped_column(
|
||||
Enum(ScrapedDocumentStatus),
|
||||
default=ScrapedDocumentStatus.pending,
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
bizdocs_doc_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
server_default=func.now(),
|
||||
onupdate=func.now(),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
shop_account: Mapped[ShopAccount] = relationship(back_populates="scraped_docs")
|
||||
|
||||
|
||||
class ShopScrapeRun(Base):
|
||||
"""Audit trail for one scraping run against a ShopAccount."""
|
||||
|
||||
__tablename__ = "shop_scrape_runs"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
shop_account_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("shop_accounts.id"), nullable=False, index=True
|
||||
)
|
||||
status: Mapped[ShopScrapeRunStatus] = mapped_column(
|
||||
Enum(ShopScrapeRunStatus),
|
||||
default=ShopScrapeRunStatus.running,
|
||||
nullable=False,
|
||||
)
|
||||
orders_found: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
invoices_uploaded: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
invoices_failed: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
invoices_skipped: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
||||
error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
started_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||
)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime(timezone=True), nullable=True
|
||||
)
|
||||
|
||||
shop_account: Mapped[ShopAccount] = relationship(back_populates="scrape_runs")
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Shop invoice scrapers (Temu, Amazon, …)."""
|
||||
|
||||
from forwarder.scrapers.base import InvoiceDocument, InvoiceScraper
|
||||
from forwarder.scrapers.registry import get_scraper
|
||||
|
||||
__all__ = ["InvoiceDocument", "InvoiceScraper", "get_scraper"]
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Amazon invoice scraper using Playwright browser automation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from forwarder.scrapers.base import InvoiceDocument, InvoiceScraper, ShopCredentials
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Amazon domains — PT/ES/DE customers may use amazon.es / amazon.de / etc.
|
||||
# Default to amazon.es which is common in Portugal; can be overridden via credentials.extra["domain"]
|
||||
DEFAULT_DOMAIN = "amazon.es"
|
||||
|
||||
# Order history page (shows VAT invoices for business accounts)
|
||||
ORDERS_PATH = "/gp/your-account/order-history"
|
||||
# VAT invoice download path pattern
|
||||
VAT_INVOICE_PATH = "/gp/shared-cs/ajax/invoice/invoice.html"
|
||||
|
||||
|
||||
class AmazonScraper(InvoiceScraper):
|
||||
"""
|
||||
Scrapes Amazon VAT invoice PDFs using Playwright.
|
||||
|
||||
Supports:
|
||||
- amazon.es (Portugal / Spain)
|
||||
- amazon.de (Germany)
|
||||
- amazon.co.uk
|
||||
- amazon.com
|
||||
- any other supported domain via credentials.extra["domain"]
|
||||
|
||||
First run: logs in with email+password. Amazon may require OTP/2FA —
|
||||
if so the login will time out. Use the Admin UI "Test Connection" flow
|
||||
to authenticate interactively and save the session state.
|
||||
|
||||
Subsequent runs: restores saved Playwright storage state (cookies).
|
||||
"""
|
||||
|
||||
@property
|
||||
def _domain(self) -> str:
|
||||
return self._credentials.extra.get("domain", DEFAULT_DOMAIN).lower()
|
||||
|
||||
@property
|
||||
def _base_url(self) -> str:
|
||||
return f"https://www.{self._domain}"
|
||||
|
||||
async def iter_invoices(
|
||||
self,
|
||||
since: datetime | None = None,
|
||||
max_orders: int = 100,
|
||||
) -> AsyncGenerator[InvoiceDocument, None]:
|
||||
try:
|
||||
from playwright.async_api import async_playwright
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"playwright is not installed. Run: pip install playwright && playwright install chromium"
|
||||
) from exc
|
||||
|
||||
async with async_playwright() as pw:
|
||||
browser = await pw.chromium.launch(headless=True)
|
||||
context_opts: dict = {}
|
||||
|
||||
if self._credentials.session_state_json:
|
||||
state = json.loads(self._credentials.session_state_json)
|
||||
context_opts["storage_state"] = state
|
||||
|
||||
context = await browser.new_context(
|
||||
**context_opts,
|
||||
user_agent=(
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/124.0.0.0 Safari/537.36"
|
||||
),
|
||||
)
|
||||
page = await context.new_page()
|
||||
|
||||
try:
|
||||
# --- Authentication ---
|
||||
if not self._credentials.session_state_json:
|
||||
await self._login(page)
|
||||
else:
|
||||
await page.goto(
|
||||
f"{self._base_url}{ORDERS_PATH}",
|
||||
wait_until="domcontentloaded",
|
||||
timeout=30_000,
|
||||
)
|
||||
if "signin" in page.url.lower() or "ap/signin" in page.url.lower():
|
||||
logger.info("Amazon: session expired, re-logging in")
|
||||
await self._login(page)
|
||||
|
||||
# --- Collect orders from order history pages ---
|
||||
orders_seen = 0
|
||||
year = datetime.now(tz=timezone.utc).year
|
||||
|
||||
for year_offset in range(3): # current year + 2 previous
|
||||
if orders_seen >= max_orders:
|
||||
break
|
||||
|
||||
check_year = year - year_offset
|
||||
order_ids = await self._list_order_ids_for_year(page, check_year, since)
|
||||
|
||||
for order_id in order_ids:
|
||||
if orders_seen >= max_orders:
|
||||
break
|
||||
orders_seen += 1
|
||||
|
||||
try:
|
||||
result = await self._download_invoice(context, page, order_id)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Amazon: failed to download invoice for order %s: %s", order_id, exc
|
||||
)
|
||||
continue
|
||||
|
||||
if result is None:
|
||||
logger.debug("Amazon: no VAT invoice for order %s", order_id)
|
||||
continue
|
||||
|
||||
pdf_bytes, order_date = result
|
||||
yield InvoiceDocument(
|
||||
order_id=order_id,
|
||||
filename=f"amazon_invoice_{order_id}.pdf",
|
||||
data=pdf_bytes,
|
||||
order_date=order_date,
|
||||
description=f"Amazon order {order_id}",
|
||||
)
|
||||
|
||||
# Persist updated session state
|
||||
updated_state = await context.storage_state()
|
||||
self._updated_session_state = json.dumps(updated_state)
|
||||
|
||||
finally:
|
||||
await context.close()
|
||||
await browser.close()
|
||||
|
||||
async def _login(self, page) -> None:
|
||||
"""Perform email+password login on Amazon."""
|
||||
logger.info("Amazon: logging in as %s on %s", self._credentials.email, self._domain)
|
||||
await page.goto(
|
||||
f"{self._base_url}/ap/signin",
|
||||
wait_until="domcontentloaded",
|
||||
timeout=30_000,
|
||||
)
|
||||
|
||||
# Email step
|
||||
await page.wait_for_selector("#ap_email", timeout=10_000)
|
||||
await page.fill("#ap_email", self._credentials.email)
|
||||
await page.click("#continue")
|
||||
|
||||
# Password step
|
||||
await page.wait_for_selector("#ap_password", timeout=10_000)
|
||||
await page.fill("#ap_password", self._credentials.password)
|
||||
await page.click("#signInSubmit")
|
||||
await page.wait_for_load_state("domcontentloaded", timeout=20_000)
|
||||
|
||||
if "signin" in page.url.lower() or "ap/signin" in page.url.lower():
|
||||
# May be OTP page
|
||||
otp_input = page.locator("#auth-mfa-otpcode")
|
||||
if await otp_input.count() > 0:
|
||||
raise RuntimeError(
|
||||
"Amazon requires OTP/2FA. "
|
||||
"Use the Admin UI to authenticate interactively and save the session state."
|
||||
)
|
||||
raise RuntimeError(
|
||||
"Amazon login failed — check credentials or CAPTCHA. "
|
||||
"Use Admin UI to authenticate interactively."
|
||||
)
|
||||
|
||||
logger.info("Amazon: login successful")
|
||||
|
||||
async def _list_order_ids_for_year(
|
||||
self,
|
||||
page,
|
||||
year: int,
|
||||
since: datetime | None,
|
||||
) -> list[str]:
|
||||
"""Return all order IDs for the given year from Amazon order history."""
|
||||
url = (
|
||||
f"{self._base_url}{ORDERS_PATH}"
|
||||
f"?opt=ab&digitalOrders=1&unifiedOrders=1&returnTo=&orderFilter=year-{year}"
|
||||
)
|
||||
await page.goto(url, wait_until="domcontentloaded", timeout=30_000)
|
||||
|
||||
order_ids: list[str] = []
|
||||
while True:
|
||||
# Extract order IDs from the page
|
||||
# Amazon marks orders with data attributes or aria-labels containing the order number
|
||||
elements = await page.query_selector_all(
|
||||
"[data-order-id], .order-id, .a-size-mini.a-color-secondary.value"
|
||||
)
|
||||
for el in elements:
|
||||
text = await el.inner_text()
|
||||
# Order IDs match pattern like: 402-1234567-8901234
|
||||
matches = re.findall(r"\d{3}-\d{7}-\d{7}", text)
|
||||
for oid in matches:
|
||||
if oid not in order_ids:
|
||||
order_ids.append(oid)
|
||||
|
||||
# Check for "next page" pagination
|
||||
next_btn = page.locator(
|
||||
'li.a-last a, .a-pagination .a-last a, [aria-label="Next page"]'
|
||||
)
|
||||
if await next_btn.count() > 0:
|
||||
await next_btn.first.click()
|
||||
await page.wait_for_load_state("domcontentloaded", timeout=15_000)
|
||||
else:
|
||||
break
|
||||
|
||||
logger.debug("Amazon: found %s order IDs for year %s", len(order_ids), year)
|
||||
return order_ids
|
||||
|
||||
async def _download_invoice(
|
||||
self,
|
||||
context,
|
||||
page,
|
||||
order_id: str,
|
||||
) -> tuple[bytes, datetime | None] | None:
|
||||
"""
|
||||
Attempt to download the VAT invoice PDF for an Amazon order.
|
||||
|
||||
Returns (pdf_bytes, order_date) or None if no invoice available.
|
||||
"""
|
||||
# Navigate to the order detail page to find the invoice link
|
||||
order_url = f"{self._base_url}/gp/your-account/order-details?orderID={order_id}"
|
||||
await page.goto(order_url, wait_until="domcontentloaded", timeout=30_000)
|
||||
|
||||
# Look for VAT invoice link
|
||||
invoice_link = page.locator(
|
||||
'a[href*="invoice"], a[href*="Invoice"], '
|
||||
'a:has-text("VAT invoice"), a:has-text("Fatura"), '
|
||||
'a:has-text("Rechnung"), a:has-text("Invoice")'
|
||||
).first
|
||||
|
||||
if await invoice_link.count() == 0:
|
||||
return None
|
||||
|
||||
invoice_href = await invoice_link.get_attribute("href")
|
||||
if not invoice_href:
|
||||
return None
|
||||
|
||||
if not invoice_href.startswith("http"):
|
||||
invoice_href = self._base_url + invoice_href
|
||||
|
||||
# Download the invoice — it may be HTML (printable receipt) or PDF
|
||||
inv_page = await context.new_page()
|
||||
try:
|
||||
# Intercept PDF download
|
||||
pdf_bytes: bytes | None = None
|
||||
|
||||
async def handle_download(download):
|
||||
nonlocal pdf_bytes
|
||||
path = await download.path()
|
||||
if path:
|
||||
with open(path, "rb") as f:
|
||||
pdf_bytes = f.read()
|
||||
|
||||
inv_page.on("download", handle_download)
|
||||
|
||||
response = await inv_page.goto(invoice_href, wait_until="domcontentloaded", timeout=20_000)
|
||||
if response and response.status == 200:
|
||||
content_type = response.headers.get("content-type", "")
|
||||
if "pdf" in content_type:
|
||||
pdf_bytes = await response.body()
|
||||
elif not pdf_bytes:
|
||||
# It's a printable HTML receipt — generate PDF via Playwright
|
||||
pdf_bytes = await inv_page.pdf(
|
||||
format="A4",
|
||||
print_background=True,
|
||||
margin={"top": "1cm", "bottom": "1cm", "left": "1cm", "right": "1cm"},
|
||||
)
|
||||
|
||||
if not pdf_bytes:
|
||||
return None
|
||||
|
||||
# Parse order date from the order detail page (already loaded)
|
||||
order_date = await self._parse_order_date(page)
|
||||
return pdf_bytes, order_date
|
||||
|
||||
finally:
|
||||
await inv_page.close()
|
||||
|
||||
@staticmethod
|
||||
async def _parse_order_date(page) -> datetime | None:
|
||||
"""Extract order placement date from an Amazon order detail page."""
|
||||
try:
|
||||
# Amazon shows "Order placed: DD Month YYYY" in the order header
|
||||
date_el = page.locator(
|
||||
".order-date-invoice-item, "
|
||||
"[data-testid='order-date'], "
|
||||
".a-color-secondary span"
|
||||
).first
|
||||
if await date_el.count() > 0:
|
||||
text = await date_el.inner_text()
|
||||
# Simple heuristic: find a 4-digit year
|
||||
match = re.search(r"\d{1,2}\s+\w+\s+(\d{4})", text)
|
||||
if match:
|
||||
try:
|
||||
return datetime.strptime(text.strip(), "%d %B %Y").replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
except ValueError:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Base class and data types for shop invoice scrapers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@dataclass
|
||||
class InvoiceDocument:
|
||||
"""An invoice retrieved from a shop."""
|
||||
|
||||
order_id: str
|
||||
filename: str
|
||||
data: bytes
|
||||
order_date: datetime | None = None
|
||||
# Human-readable label shown in logs
|
||||
description: str = ""
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.description:
|
||||
self.description = self.order_id
|
||||
|
||||
|
||||
@dataclass
|
||||
class ShopCredentials:
|
||||
email: str
|
||||
password: str
|
||||
# Persisted Playwright browser state JSON (cookies + localStorage).
|
||||
# None on first run; set by the scraper after a successful login.
|
||||
session_state_json: str | None = None
|
||||
extra: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
class InvoiceScraper(abc.ABC):
|
||||
"""
|
||||
Abstract base for per-shop invoice scrapers.
|
||||
|
||||
Each subclass targets one shop type (Temu, Amazon…). The scraper:
|
||||
1. Authenticates using `credentials` (either fresh login or saved state).
|
||||
2. Lists order IDs for which invoices exist.
|
||||
3. Downloads each invoice as raw bytes.
|
||||
4. Optionally persists an updated session state back to the caller.
|
||||
|
||||
Usage::
|
||||
|
||||
scraper = TemuScraper(credentials)
|
||||
async for doc in scraper.iter_invoices(since=last_scraped_at):
|
||||
upload_to_bizdocs(doc)
|
||||
# Persist updated session for next run:
|
||||
updated_state = scraper.get_updated_session_state()
|
||||
"""
|
||||
|
||||
def __init__(self, credentials: ShopCredentials) -> None:
|
||||
self._credentials = credentials
|
||||
self._updated_session_state: str | None = None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Abstract interface
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@abc.abstractmethod
|
||||
async def iter_invoices(
|
||||
self,
|
||||
since: datetime | None = None,
|
||||
max_orders: int = 100,
|
||||
):
|
||||
"""
|
||||
Async generator yielding InvoiceDocument instances.
|
||||
|
||||
`since`: skip orders older than this timestamp.
|
||||
`max_orders`: cap to avoid runaway scrapes on first-ever run.
|
||||
"""
|
||||
...
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Session state round-trip
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_updated_session_state(self) -> str | None:
|
||||
"""Return serialised Playwright browser state after a run, if refreshed."""
|
||||
return self._updated_session_state
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Map ShopType enum → InvoiceScraper class."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from forwarder.scrapers.base import InvoiceScraper, ShopCredentials
|
||||
|
||||
|
||||
def get_scraper(shop_type: str, credentials: ShopCredentials) -> InvoiceScraper:
|
||||
"""Instantiate the correct scraper for *shop_type*."""
|
||||
if shop_type == "temu":
|
||||
from forwarder.scrapers.temu import TemuScraper
|
||||
return TemuScraper(credentials)
|
||||
if shop_type == "amazon":
|
||||
from forwarder.scrapers.amazon import AmazonScraper
|
||||
return AmazonScraper(credentials)
|
||||
raise ValueError(f"Unknown shop type: {shop_type!r}")
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Temu invoice scraper using Playwright browser automation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from forwarder.scrapers.base import InvoiceDocument, InvoiceScraper, ShopCredentials
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TEMU_BASE = "https://www.temu.com"
|
||||
LOGIN_URL = f"{TEMU_BASE}/login.html"
|
||||
ORDERS_URL = f"{TEMU_BASE}/user-orders.html"
|
||||
# Temu internal API used by both web and the Chrome invoice extension
|
||||
ORDERS_API = f"{TEMU_BASE}/api/poppy/v1/order/order_list"
|
||||
INVOICE_API = f"{TEMU_BASE}/api/poppy/v1/invoice/download"
|
||||
|
||||
# How many pages of orders to fetch per run
|
||||
MAX_PAGES = 10
|
||||
PAGE_SIZE = 20
|
||||
|
||||
|
||||
class TemuScraper(InvoiceScraper):
|
||||
"""
|
||||
Scrapes Temu order invoices using Playwright.
|
||||
|
||||
Temu's invoice PDFs are served via their internal API once the user is
|
||||
logged in. The scraper:
|
||||
|
||||
1. Launches a headless Chromium browser.
|
||||
2. Restores a saved session state (cookies) if available, else performs
|
||||
an email+password login.
|
||||
3. Fetches order list pages via the internal JSON API.
|
||||
4. For each order with an invoice available, downloads the PDF bytes.
|
||||
5. Saves the updated browser state for next run.
|
||||
|
||||
Note: Temu may show a CAPTCHA on first login. If the session_state_json
|
||||
in ShopCredentials is empty, the first run logs a warning and the admin
|
||||
should use the Admin UI "Test Connection" flow to complete authentication
|
||||
interactively and save the session state.
|
||||
"""
|
||||
|
||||
async def iter_invoices(
|
||||
self,
|
||||
since: datetime | None = None,
|
||||
max_orders: int = 100,
|
||||
) -> AsyncGenerator[InvoiceDocument, None]:
|
||||
try:
|
||||
from playwright.async_api import async_playwright
|
||||
except ImportError as exc:
|
||||
raise RuntimeError(
|
||||
"playwright is not installed. Run: pip install playwright && playwright install chromium"
|
||||
) from exc
|
||||
|
||||
async with async_playwright() as pw:
|
||||
browser = await pw.chromium.launch(headless=True)
|
||||
context_opts: dict = {}
|
||||
|
||||
if self._credentials.session_state_json:
|
||||
state = json.loads(self._credentials.session_state_json)
|
||||
context_opts["storage_state"] = state
|
||||
|
||||
context = await browser.new_context(
|
||||
**context_opts,
|
||||
user_agent=(
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/124.0.0.0 Safari/537.36"
|
||||
),
|
||||
)
|
||||
page = await context.new_page()
|
||||
|
||||
try:
|
||||
# --- Authentication ---
|
||||
if not self._credentials.session_state_json:
|
||||
await self._login(page)
|
||||
|
||||
# Validate session by navigating to orders page
|
||||
await page.goto(ORDERS_URL, wait_until="domcontentloaded", timeout=30_000)
|
||||
if "login" in page.url.lower():
|
||||
logger.info("Temu: session expired, re-logging in")
|
||||
await self._login(page)
|
||||
|
||||
# --- Fetch orders via internal API ---
|
||||
orders_fetched = 0
|
||||
for page_num in range(MAX_PAGES):
|
||||
if orders_fetched >= max_orders:
|
||||
break
|
||||
|
||||
order_list = await self._fetch_order_page(context, page_num + 1)
|
||||
if not order_list:
|
||||
break
|
||||
|
||||
for order in order_list:
|
||||
if orders_fetched >= max_orders:
|
||||
break
|
||||
|
||||
order_id = str(order.get("order_sn") or order.get("orderId") or "")
|
||||
if not order_id:
|
||||
continue
|
||||
|
||||
# Skip old orders if `since` is set
|
||||
if since:
|
||||
order_time = self._parse_order_time(order)
|
||||
if order_time and order_time < since:
|
||||
logger.debug("Temu: order %s before since cutoff, stopping", order_id)
|
||||
return
|
||||
|
||||
orders_fetched += 1
|
||||
|
||||
try:
|
||||
pdf_bytes = await self._download_invoice(context, order_id)
|
||||
except Exception as exc:
|
||||
logger.warning("Temu: failed to download invoice for order %s: %s", order_id, exc)
|
||||
continue
|
||||
|
||||
if not pdf_bytes:
|
||||
logger.debug("Temu: no invoice for order %s", order_id)
|
||||
continue
|
||||
|
||||
order_date = self._parse_order_time(order)
|
||||
filename = f"temu_invoice_{order_id}.pdf"
|
||||
yield InvoiceDocument(
|
||||
order_id=order_id,
|
||||
filename=filename,
|
||||
data=pdf_bytes,
|
||||
order_date=order_date,
|
||||
description=f"Temu order {order_id}",
|
||||
)
|
||||
|
||||
# Persist updated session state
|
||||
updated_state = await context.storage_state()
|
||||
self._updated_session_state = json.dumps(updated_state)
|
||||
|
||||
finally:
|
||||
await context.close()
|
||||
await browser.close()
|
||||
|
||||
async def _login(self, page) -> None:
|
||||
"""Perform email+password login on Temu."""
|
||||
logger.info("Temu: logging in as %s", self._credentials.email)
|
||||
await page.goto(LOGIN_URL, wait_until="domcontentloaded", timeout=30_000)
|
||||
|
||||
# Fill email
|
||||
await page.wait_for_selector('input[type="text"], input[type="email"]', timeout=10_000)
|
||||
email_input = page.locator('input[type="email"]').first
|
||||
if await email_input.count() == 0:
|
||||
email_input = page.locator('input[type="text"]').first
|
||||
await email_input.fill(self._credentials.email)
|
||||
|
||||
# Fill password
|
||||
password_input = page.locator('input[type="password"]').first
|
||||
await password_input.fill(self._credentials.password)
|
||||
|
||||
# Submit
|
||||
await page.keyboard.press("Enter")
|
||||
await page.wait_for_load_state("domcontentloaded", timeout=20_000)
|
||||
|
||||
if "login" in page.url.lower():
|
||||
raise RuntimeError(
|
||||
"Temu login failed — page still showing login. "
|
||||
"Possible CAPTCHA. Use Admin UI to authenticate interactively."
|
||||
)
|
||||
logger.info("Temu: login successful")
|
||||
|
||||
async def _fetch_order_page(self, context, page_num: int) -> list[dict]:
|
||||
"""Fetch one page of orders from Temu's internal order list API."""
|
||||
page = await context.new_page()
|
||||
try:
|
||||
response = await page.request.get(
|
||||
ORDERS_API,
|
||||
params={
|
||||
"page": page_num,
|
||||
"page_size": PAGE_SIZE,
|
||||
"order_status": "0", # all statuses
|
||||
},
|
||||
timeout=15_000,
|
||||
)
|
||||
if response.status != 200:
|
||||
logger.warning("Temu order list API returned %s", response.status)
|
||||
return []
|
||||
|
||||
body = await response.json()
|
||||
# Temu API response: {"result": {"order_list": [...], ...}}
|
||||
result = body.get("result") or body
|
||||
if isinstance(result, dict):
|
||||
return result.get("order_list") or result.get("orders") or []
|
||||
return []
|
||||
except Exception as exc:
|
||||
logger.warning("Temu: order page %s fetch failed: %s", page_num, exc)
|
||||
return []
|
||||
finally:
|
||||
await page.close()
|
||||
|
||||
async def _download_invoice(self, context, order_id: str) -> bytes | None:
|
||||
"""Download the invoice PDF for a single Temu order."""
|
||||
page = await context.new_page()
|
||||
try:
|
||||
response = await page.request.get(
|
||||
INVOICE_API,
|
||||
params={"order_sn": order_id},
|
||||
timeout=20_000,
|
||||
)
|
||||
if response.status == 404:
|
||||
return None
|
||||
if response.status != 200:
|
||||
raise RuntimeError(f"HTTP {response.status}")
|
||||
|
||||
content_type = response.headers.get("content-type", "")
|
||||
if "pdf" in content_type or "octet-stream" in content_type:
|
||||
return await response.body()
|
||||
|
||||
# Some Temu responses return a JSON with a PDF URL
|
||||
body = await response.json()
|
||||
pdf_url = (
|
||||
body.get("result", {}).get("invoice_url")
|
||||
or body.get("invoice_url")
|
||||
or body.get("url")
|
||||
)
|
||||
if pdf_url:
|
||||
pdf_resp = await page.request.get(pdf_url, timeout=20_000)
|
||||
if pdf_resp.status == 200:
|
||||
return await pdf_resp.body()
|
||||
|
||||
return None
|
||||
finally:
|
||||
await page.close()
|
||||
|
||||
@staticmethod
|
||||
def _parse_order_time(order: dict) -> datetime | None:
|
||||
for key in ("create_time", "order_time", "created_at", "orderTime"):
|
||||
value = order.get(key)
|
||||
if isinstance(value, (int, float)) and value > 0:
|
||||
try:
|
||||
ts = value / 1000 if value > 1e10 else value
|
||||
return datetime.fromtimestamp(ts, tz=timezone.utc)
|
||||
except (OSError, OverflowError):
|
||||
continue
|
||||
if isinstance(value, str) and value:
|
||||
try:
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
@@ -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()
|
||||
@@ -6,12 +6,13 @@ from datetime import datetime, timezone
|
||||
from apscheduler.schedulers.blocking import BlockingScheduler
|
||||
from apscheduler.triggers.interval import IntervalTrigger
|
||||
|
||||
from forwarder.db.models import Account
|
||||
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__)
|
||||
|
||||
@@ -23,6 +24,10 @@ 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:
|
||||
@@ -54,6 +59,36 @@ def _sync_job(account_id: int) -> None:
|
||||
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:
|
||||
@@ -119,6 +154,48 @@ def _refresh_account_schedules(scheduler: BlockingScheduler, *, default_interval
|
||||
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
|
||||
|
||||
@@ -126,6 +203,7 @@ def run_worker(*, default_interval: int = 15) -> None:
|
||||
scheduler = BlockingScheduler()
|
||||
|
||||
_refresh_account_schedules(scheduler, default_interval=default_interval)
|
||||
_refresh_shop_schedules(scheduler)
|
||||
|
||||
scheduler.add_job(
|
||||
_forward_queue_job,
|
||||
@@ -150,6 +228,14 @@ def run_worker(*, default_interval: int = 15) -> None:
|
||||
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:
|
||||
|
||||
Reference in new issue
Block a user