|
|
|
@@ -4,7 +4,8 @@ SLICE-1 mounted /healthz; SLICE-2 adds the /api/auth/* identity endpoints (§6.4
|
|
|
|
|
translates HTTP <-> domain calls and owns no business logic (INV-6): every rule lives in
|
|
|
|
|
the accounts domain. create_app() opens the pool, self-migrates (INV-1, INV-7), and builds
|
|
|
|
|
the configured mailer (INV-8) at startup. SLICE-3 adds POST /api/storefronts and feeds the
|
|
|
|
|
_storefront_for seam from the storefronts domain.
|
|
|
|
|
_storefront_for seam from the storefronts domain. SLICE-5 adds the /api/products/* import
|
|
|
|
|
spine (SD-0002 §6.4): each endpoint is a gate + one products-domain call + error mapping.
|
|
|
|
|
"""
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
@@ -15,12 +16,12 @@ from pathlib import Path
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
import psycopg
|
|
|
|
|
from fastapi import Depends, FastAPI, Response
|
|
|
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
from fastapi import Depends, FastAPI, File, Query, Response, UploadFile
|
|
|
|
|
from fastapi.responses import JSONResponse, PlainTextResponse
|
|
|
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
|
from pydantic import BaseModel
|
|
|
|
|
|
|
|
|
|
from app.domains import accounts, storefronts
|
|
|
|
|
from app.domains import accounts, products, storefronts
|
|
|
|
|
from app.platform import config, db
|
|
|
|
|
from app.platform import mailer as mailer_mod
|
|
|
|
|
from app.platform.deps import SESSION_COOKIE, get_conn, get_mailer, get_session
|
|
|
|
@@ -61,6 +62,26 @@ def _storefront_for(conn: psycopg.Connection, account: accounts.Account) -> dict
|
|
|
|
|
return {"id": sf.id, "name": sf.name} if sf else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _merchant_gate(
|
|
|
|
|
conn: psycopg.Connection, sess: dict | None
|
|
|
|
|
) -> JSONResponse | tuple[accounts.Account, storefronts.Storefront]:
|
|
|
|
|
"""The shared /api/products/* gate: a signed-in account that has its storefront.
|
|
|
|
|
|
|
|
|
|
Returns the (account, storefront) pair, or the ready-to-return error response —
|
|
|
|
|
401 with no session, 404 before the storefront exists (INV-14: every products
|
|
|
|
|
call is storefront-scoped, so there is nothing to address yet).
|
|
|
|
|
"""
|
|
|
|
|
if sess is None:
|
|
|
|
|
return _error(401, "unauthenticated", "You are not signed in.")
|
|
|
|
|
account = accounts.get_account(conn, sess["account_id"])
|
|
|
|
|
if account is None:
|
|
|
|
|
return _error(401, "unauthenticated", "You are not signed in.")
|
|
|
|
|
sf = storefronts.storefront_for(conn, account.id)
|
|
|
|
|
if sf is None:
|
|
|
|
|
return _error(404, "no_storefront", "Create your storefront first.")
|
|
|
|
|
return account, sf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _ensure_app_logging() -> None:
|
|
|
|
|
"""Surface the app's own `ecomm.*` INFO logs on stderr (idempotent).
|
|
|
|
|
|
|
|
|
@@ -208,6 +229,160 @@ def create_app(database_url: str | None = None, static_dir: str | Path | None =
|
|
|
|
|
)
|
|
|
|
|
return JSONResponse(status_code=201, content={"id": sf.id, "name": sf.name})
|
|
|
|
|
|
|
|
|
|
@app.post("/api/products/imports")
|
|
|
|
|
async def import_upload(
|
|
|
|
|
file: UploadFile = File(...),
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""Upload a CSV → validated import draft (§6.4; PUC-2, PUC-5/5a on rejection)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
account, sf = gate
|
|
|
|
|
data = await file.read()
|
|
|
|
|
if len(data) > products.MAX_FILE_BYTES:
|
|
|
|
|
return _error(413, "file_too_large", "This file is larger than 10 MB.")
|
|
|
|
|
try:
|
|
|
|
|
draft = products.import_validate(conn, sf.id, account.id, file.filename or "upload.csv", data)
|
|
|
|
|
except products.FileRejected as exc:
|
|
|
|
|
return _error(400, exc.code, exc.message)
|
|
|
|
|
return JSONResponse(status_code=201, content=draft)
|
|
|
|
|
|
|
|
|
|
@app.get("/api/products/imports/drafts/{draft_id}")
|
|
|
|
|
def get_import_draft(
|
|
|
|
|
draft_id: int,
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""One draft's preview payload — summary, never the file bytes (§6.4; PUC-3)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
_account, sf = gate
|
|
|
|
|
try:
|
|
|
|
|
return products.get_draft(conn, sf.id, draft_id)
|
|
|
|
|
except products.DraftNotFound:
|
|
|
|
|
return _error(404, "not_found", "No such import preview.")
|
|
|
|
|
except products.DraftExpired:
|
|
|
|
|
return _error(410, "draft_expired", "This preview expired — upload the file again.")
|
|
|
|
|
|
|
|
|
|
@app.get("/api/products/imports/drafts/{draft_id}/records")
|
|
|
|
|
def get_import_draft_records(
|
|
|
|
|
draft_id: int,
|
|
|
|
|
kind: str | None = Query(default=None, pattern="^(add|update|unchanged|error)$"),
|
|
|
|
|
limit: int = Query(default=100, ge=1, le=500),
|
|
|
|
|
offset: int = Query(default=0, ge=0),
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""The draft's per-product preview records, paged + kind-filtered (§6.4; PUC-3)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
_account, sf = gate
|
|
|
|
|
try:
|
|
|
|
|
records = products.get_draft_records(conn, sf.id, draft_id, kind, limit, offset)
|
|
|
|
|
except products.DraftNotFound:
|
|
|
|
|
return _error(404, "not_found", "No such import preview.")
|
|
|
|
|
except products.DraftExpired:
|
|
|
|
|
return _error(410, "draft_expired", "This preview expired — upload the file again.")
|
|
|
|
|
return {"records": records}
|
|
|
|
|
|
|
|
|
|
@app.post("/api/products/imports/drafts/{draft_id}/confirm")
|
|
|
|
|
def confirm_import_draft(
|
|
|
|
|
draft_id: int,
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""Apply the previewed diff as one import run (§6.4; PUC-4, INV-10/11)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
account, sf = gate
|
|
|
|
|
try:
|
|
|
|
|
run_id = products.confirm_draft(conn, sf.id, account.id, draft_id)
|
|
|
|
|
except products.DraftNotFound:
|
|
|
|
|
return _error(404, "not_found", "No such import preview.")
|
|
|
|
|
except products.DraftExpired:
|
|
|
|
|
return _error(410, "draft_expired", "This preview expired — upload the file again.")
|
|
|
|
|
except products.PreviewStale:
|
|
|
|
|
return _error(
|
|
|
|
|
409, "preview_stale",
|
|
|
|
|
"Your catalog changed since this preview — upload the file again.",
|
|
|
|
|
)
|
|
|
|
|
except products.NothingToApply:
|
|
|
|
|
return _error(
|
|
|
|
|
409, "nothing_to_apply",
|
|
|
|
|
"Nothing to change — your catalog already matches this file.",
|
|
|
|
|
)
|
|
|
|
|
return JSONResponse(status_code=201, content={"run_id": run_id})
|
|
|
|
|
|
|
|
|
|
@app.delete("/api/products/imports/drafts/{draft_id}")
|
|
|
|
|
def discard_import_draft(
|
|
|
|
|
draft_id: int,
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""Discard the draft, no trace kept; idempotent (§6.4; PUC-3a)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
_account, sf = gate
|
|
|
|
|
products.discard_draft(conn, sf.id, draft_id)
|
|
|
|
|
return Response(status_code=204)
|
|
|
|
|
|
|
|
|
|
@app.get("/api/products/imports/runs")
|
|
|
|
|
def list_import_runs(
|
|
|
|
|
limit: int = Query(default=50, ge=1, le=200),
|
|
|
|
|
offset: int = Query(default=0, ge=0),
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""The storefront's import history, newest first (§6.4; PUC-8)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
_account, sf = gate
|
|
|
|
|
return {"runs": products.list_runs(conn, sf.id, limit, offset)}
|
|
|
|
|
|
|
|
|
|
@app.get("/api/products/imports/runs/{run_id}")
|
|
|
|
|
def get_import_run(
|
|
|
|
|
run_id: int,
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""One run's detail payload, errors included (§6.4; PUC-8)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
_account, sf = gate
|
|
|
|
|
try:
|
|
|
|
|
return products.get_run(conn, sf.id, run_id)
|
|
|
|
|
except products.RunNotFound:
|
|
|
|
|
return _error(404, "not_found", "No such import run.")
|
|
|
|
|
|
|
|
|
|
@app.get("/api/products/summary")
|
|
|
|
|
def products_summary(
|
|
|
|
|
conn: psycopg.Connection = Depends(get_conn),
|
|
|
|
|
sess: dict | None = Depends(get_session),
|
|
|
|
|
):
|
|
|
|
|
"""The products dashboard counts (§6.4)."""
|
|
|
|
|
gate = _merchant_gate(conn, sess)
|
|
|
|
|
if isinstance(gate, JSONResponse):
|
|
|
|
|
return gate
|
|
|
|
|
_account, sf = gate
|
|
|
|
|
return products.summary(conn, sf.id)
|
|
|
|
|
|
|
|
|
|
@app.get("/api/products/sample.csv")
|
|
|
|
|
def products_sample_csv():
|
|
|
|
|
"""The DOC-3 worked-example CSV. Documentation, so no auth gate (§6.4)."""
|
|
|
|
|
return PlainTextResponse(
|
|
|
|
|
products.SAMPLE_CSV_PATH.read_text(),
|
|
|
|
|
media_type="text/csv",
|
|
|
|
|
headers={"content-disposition": 'attachment; filename="ecomm-products-sample.csv"'},
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Deployed topology (launch-app SPEC §2): nginx proxies everything here, so the
|
|
|
|
|
# backend serves the built SPA. Mounted LAST so /healthz and /api/* win. In dev the
|
|
|
|
|
# dist dir doesn't exist (Vite serves the frontend) and the mount is skipped.
|
|
|
|
|