From b4000ac9bcd64fb72fc9a5afa29b832f609d0dee Mon Sep 17 00:00:00 2001 From: "victormanuel.caverogracia" <> Date: Tue, 1 Sep 2026 12:36:59 +0200 Subject: [PATCH] feat(billing): legal invoices from AgentLedger on the account page GET /api/billing/invoices lists the AgentLedger-issued Spanish invoices for the signed-in user's Stripe customer (public View/PDF links), backfilling the customer's history on demand when AgentLedger has nothing yet. New env: AGENTLEDGER_API_KEY (+ optional AGENTLEDGER_API_URL / AGENTLEDGER_TREASURY_ID). InvoicesCard renders under the plan card for accounts with a billing relationship. Claude-Session: https://claude.ai/code/session_01Chec1RKALL2v8V4GsDfPCW --- cloud/billing.py | 83 ++++++++++++++++++++ cloud/config.py | 15 ++++ dashboard/src/components/AccountPage.jsx | 4 + dashboard/src/components/InvoicesCard.jsx | 92 +++++++++++++++++++++++ 4 files changed, 194 insertions(+) create mode 100644 dashboard/src/components/InvoicesCard.jsx diff --git a/cloud/billing.py b/cloud/billing.py index 49355d4..4d6ec10 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -10,6 +10,7 @@ Design (matches the Stripe implementation planner for this use case): import asyncio from datetime import datetime, timezone +import httpx import stripe from fastapi import APIRouter, Request, HTTPException from pydantic import BaseModel @@ -252,6 +253,88 @@ async def create_portal(request: Request): return {"url": session.url} +# --------------------------------------------------------------------------- # +# Legal invoices (AgentLedger) +# --------------------------------------------------------------------------- # +# Stripe stays the payment processor; the legally valid Spanish invoice is +# issued by AgentLedger (aikount.com) and surfaced here with signed public +# links, so the customer never needs the Stripe-hosted PDF. Same flow as +# Upload-Post: read by stripe_customer_id, and when AgentLedger has nothing yet +# (just-subscribed user) ask it to import this customer's history on the spot. +_AGENTLEDGER_TIMEOUT = 8.0 +_AGENTLEDGER_BACKFILL_TIMEOUT = 20.0 +_AGENTLEDGER_BACKFILL_DEBOUNCE_S = 90 +_agentledger_backfill_at: dict[str, float] = {} # stripe_customer_id -> unix ts + + +def _agentledger_headers() -> dict: + return {"Authorization": f"Bearer {settings.agentledger_api_key}"} + + +async def _agentledger_fetch_invoices(client: httpx.AsyncClient, customer_id: str) -> list[dict]: + """Invoices for one Stripe customer. 404 = no contact yet → [].""" + r = await client.get(f"{settings.agentledger_api_url}/contacts/{customer_id}/invoices", + headers=_agentledger_headers(), timeout=_AGENTLEDGER_TIMEOUT) + if r.status_code == 404: + return [] + if r.status_code != 200: + raise HTTPException(status_code=502, detail="Could not load invoices") + raw = (r.json() or {}).get("invoices") or [] + # Project to what the UI needs; tokens stay inside the pre-built URLs. + return [{ + "doc_number": i.get("doc_number") or "", + "doc_date": i.get("doc_date") or "", + "total": i.get("total") or "0.00", + "currency": i.get("currency") or "EUR", + "status": i.get("status") or "", + "public_url": i.get("public_url") or "", + "pdf_url": i.get("pdf_url") or "", + } for i in raw] + + +async def _agentledger_backfill(client: httpx.AsyncClient, customer_id: str) -> None: + """Best-effort: import this customer's whole paid-invoice history now.""" + try: + await client.post(f"{settings.agentledger_api_url}/integrations/stripe/sync-customer", + json={"treasury_id": settings.agentledger_treasury_id, + "stripe_customer_id": customer_id}, + headers=_agentledger_headers(), timeout=_AGENTLEDGER_BACKFILL_TIMEOUT) + except httpx.HTTPError: + pass + + +@router.get("/api/billing/invoices") +async def list_invoices(request: Request): + """Legal invoices for the signed-in user: ``{"invoices": [{doc_number, + doc_date, total, currency, status, public_url, pdf_url}]}``. Free users + (no Stripe customer yet) get an empty list, not an error.""" + user = await get_current_user_required(request) + if not settings.agentledger_api_key: + raise HTTPException(status_code=503, detail="Billing backend not configured") + async with database.SessionLocal() as session: + u = await session.get(User, user.id) + customer_id = u.stripe_customer_id if u else None + if not customer_id: + return {"invoices": []} + + async with httpx.AsyncClient() as client: + try: + invoices = await _agentledger_fetch_invoices(client, customer_id) + except httpx.HTTPError: + raise HTTPException(status_code=502, detail="Invoice service unreachable") + if not invoices: + import time as _time + last = _agentledger_backfill_at.get(customer_id, 0.0) + if _time.time() - last > _AGENTLEDGER_BACKFILL_DEBOUNCE_S: + _agentledger_backfill_at[customer_id] = _time.time() + await _agentledger_backfill(client, customer_id) + try: + invoices = await _agentledger_fetch_invoices(client, customer_id) + except httpx.HTTPError: + invoices = [] + return {"invoices": invoices} + + # --------------------------------------------------------------------------- # # Webhook # --------------------------------------------------------------------------- # diff --git a/cloud/config.py b/cloud/config.py index b0c056f..b03d3c8 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -219,6 +219,21 @@ class Settings: def stripe_webhook_secret(self) -> str: return os.environ.get("STRIPE_WEBHOOK_SECRET", "") + # AgentLedger (aikount.com) — issues the legally valid Spanish invoice for + # every Stripe charge; the account page lists them via /api/billing/invoices. + @property + def agentledger_api_url(self) -> str: + return os.environ.get("AGENTLEDGER_API_URL", "https://api.aikount.com/api/v1").rstrip("/") + + @property + def agentledger_api_key(self) -> str: + return os.environ.get("AGENTLEDGER_API_KEY", "") + + @property + def agentledger_treasury_id(self) -> str: + # The Stripe Connect treasury in AgentLedger that holds OpenShorts' customers. + return os.environ.get("AGENTLEDGER_TREASURY_ID", "720d3b70-3806-4c59-8729-2495b489a771") + # Managed provider keys (server-owned, only handed to entitled users) @property def managed_gemini_key(self) -> str: diff --git a/dashboard/src/components/AccountPage.jsx b/dashboard/src/components/AccountPage.jsx index ad5c4e9..68ee0c2 100644 --- a/dashboard/src/components/AccountPage.jsx +++ b/dashboard/src/components/AccountPage.jsx @@ -7,6 +7,7 @@ import ApiKeysCard from './ApiKeysCard'; import McpConnectCard from './McpConnectCard'; import DeleteAccountCard from './DeleteAccountCard'; import SocialAnalyticsCard from './SocialAnalyticsCard'; +import InvoicesCard from './InvoicesCard'; const fmt1 = (n) => Math.round((n || 0) * 10) / 10; @@ -184,6 +185,9 @@ export default function AccountPage() { + {/* Only accounts that ever had a Stripe relationship can have invoices. */} + {me.has_billing_account && } + {topups.length > 0 && ( diff --git a/dashboard/src/components/InvoicesCard.jsx b/dashboard/src/components/InvoicesCard.jsx new file mode 100644 index 0000000..d53cd11 --- /dev/null +++ b/dashboard/src/components/InvoicesCard.jsx @@ -0,0 +1,92 @@ +import React, { useState, useEffect } from 'react'; +import { FileText, ExternalLink, Download, Loader2 } from 'lucide-react'; +import { apiJson } from '../lib/api'; + +// Legally valid invoices for the account's Stripe charges, issued by +// AgentLedger. The backend hands us pre-signed public links, so "View" and +// "Download" open directly without any extra auth from the browser. +const STATUS_CLASS = { + paid: 'badge-ok', + partially_paid: 'badge-warn', + overdue: 'badge-warn', +}; + +function formatDate(iso) { + if (!iso) return ''; + const [y, m, d] = iso.split('-'); + return y && m && d ? `${d}/${m}/${y}` : iso; +} + +function formatMoney(amount, currency) { + const n = Number(amount); + if (!Number.isFinite(n)) return `${amount} ${currency}`; + try { + return new Intl.NumberFormat('en-US', { style: 'currency', currency: (currency || 'EUR').toUpperCase() }).format(n); + } catch (_) { + return `${n.toFixed(2)} ${currency}`; + } +} + +export default function InvoicesCard() { + const [invoices, setInvoices] = useState(null); + const [error, setError] = useState(''); + + useEffect(() => { + let cancelled = false; + apiJson('/api/billing/invoices') + .then((d) => { if (!cancelled) setInvoices(Array.isArray(d.invoices) ? d.invoices : []); }) + .catch((e) => { if (!cancelled) { setError(e?.detail || 'Could not load invoices.'); setInvoices([]); } }); + return () => { cancelled = true; }; + }, []); + + return ( +
+

+ Invoices +

+

+ Legally valid invoices for every charge on this account. +

+ + {invoices === null ? ( +
+ Loading invoices… +
+ ) : error ? ( +

{error}

+ ) : invoices.length === 0 ? ( +

+ No invoices yet. They appear here after your first payment — give it a few minutes if you just subscribed. +

+ ) : ( +
    + {invoices.map((inv) => ( +
  • +
    +
    {inv.doc_number}
    +
    + {formatDate(inv.doc_date)} · {formatMoney(inv.total, inv.currency)} + {inv.status && ( + {inv.status.replace(/_/g, ' ')} + )} +
    +
    +
    + {inv.public_url && ( + + View + + )} + {inv.pdf_url && ( + + PDF + + )} +
    +
  • + ))} +
+ )} +
+ ); +}