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
This commit is contained in:
victormanuel.caverogracia 2026-09-01 12:36:59 +02:00
parent 2b2a58202e
commit b4000ac9bc
4 changed files with 194 additions and 0 deletions

View file

@ -10,6 +10,7 @@ Design (matches the Stripe implementation planner for this use case):
import asyncio import asyncio
from datetime import datetime, timezone from datetime import datetime, timezone
import httpx
import stripe import stripe
from fastapi import APIRouter, Request, HTTPException from fastapi import APIRouter, Request, HTTPException
from pydantic import BaseModel from pydantic import BaseModel
@ -252,6 +253,88 @@ async def create_portal(request: Request):
return {"url": session.url} 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 # Webhook
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #

View file

@ -219,6 +219,21 @@ class Settings:
def stripe_webhook_secret(self) -> str: def stripe_webhook_secret(self) -> str:
return os.environ.get("STRIPE_WEBHOOK_SECRET", "") 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) # Managed provider keys (server-owned, only handed to entitled users)
@property @property
def managed_gemini_key(self) -> str: def managed_gemini_key(self) -> str:

View file

@ -7,6 +7,7 @@ import ApiKeysCard from './ApiKeysCard';
import McpConnectCard from './McpConnectCard'; import McpConnectCard from './McpConnectCard';
import DeleteAccountCard from './DeleteAccountCard'; import DeleteAccountCard from './DeleteAccountCard';
import SocialAnalyticsCard from './SocialAnalyticsCard'; import SocialAnalyticsCard from './SocialAnalyticsCard';
import InvoicesCard from './InvoicesCard';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10; const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
@ -184,6 +185,9 @@ export default function AccountPage() {
</div> </div>
</div> </div>
{/* Only accounts that ever had a Stripe relationship can have invoices. */}
{me.has_billing_account && <InvoicesCard />}
<SocialAnalyticsCard /> <SocialAnalyticsCard />
{topups.length > 0 && ( {topups.length > 0 && (

View file

@ -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 (
<div className="card p-6">
<h3 className="font-display lowercase text-lg text-ink mb-1 flex items-center gap-2">
<FileText size={16} className="text-brass" /> Invoices
</h3>
<p className="text-muted text-sm mb-4 lowercase">
Legally valid invoices for every charge on this account.
</p>
{invoices === null ? (
<div className="flex items-center gap-2 text-muted text-sm py-4">
<Loader2 size={16} className="animate-spin text-brass" /> Loading invoices…
</div>
) : error ? (
<p className="text-sm text-warn">{error}</p>
) : invoices.length === 0 ? (
<p className="text-sm text-muted">
No invoices yet. They appear here after your first payment — give it a few minutes if you just subscribed.
</p>
) : (
<ul className="divide-y divide-rule">
{invoices.map((inv) => (
<li key={inv.doc_number || inv.public_url} className="py-3 flex items-center justify-between gap-3 flex-wrap">
<div className="min-w-0">
<div className="text-ink font-medium font-mono text-xs">{inv.doc_number}</div>
<div className="text-muted text-xs mt-0.5">
{formatDate(inv.doc_date)} · <span className="text-ink2">{formatMoney(inv.total, inv.currency)}</span>
{inv.status && (
<span className={`ml-2 ${STATUS_CLASS[inv.status] || 'badge-warn'}`}>{inv.status.replace(/_/g, ' ')}</span>
)}
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
{inv.public_url && (
<a href={inv.public_url} target="_blank" rel="noopener noreferrer" className="btn-ghost px-3 py-1.5 text-xs">
<ExternalLink size={14} /> View
</a>
)}
{inv.pdf_url && (
<a href={inv.pdf_url} target="_blank" rel="noopener noreferrer" className="btn-ghost px-3 py-1.5 text-xs">
<Download size={14} /> PDF
</a>
)}
</div>
</li>
))}
</ul>
)}
</div>
);
}