Spaces:
Sleeping
Add Audit Mode: evidence-backed checklist audit for finance documents
Browse filesNew POST /audit runs a per-type checklist (invoice / contract / payment_note /
general) over a document, reusing the /ask retrieval + abstention gate so it
never invents a value. A check is SUPPORTED only when retrieval does not abstain
AND the cited excerpt contains the field's discriminator keyword; otherwise the
field is flagged unsupported (a missing field drives the risk level). Returns a
summary, risk_level, per-field findings (claim + evidence + citation), and
metrics (counts + citation coverage). Reuses _owned_document for per-user
scoping + 404; /ask is unchanged.
Frontend: new Audit tab — a B2B audit dashboard (document + type selectors,
risk badge, metric cards, per-finding evidence with highlighted citations).
Backend: app/audit.py, audit schemas, POST /audit, and tests/test_audit.py
(7 tests: field detection, unsupported detection, citation coverage,
false-positive guard, 404, cross-user scoping, default type).
Hardened after an adversarial review: field discriminators prevent false
supported findings off incidental word overlaps (which would wrongly lower the
risk); the frontend clears stale results on selection change; the audit-type
control uses role=group + aria-pressed.
Verified locally: 56 backend tests pass, frontend builds. Local commit only.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- backend/app/audit.py +194 -0
- backend/app/main.py +40 -0
- backend/app/schemas.py +34 -0
- backend/tests/test_audit.py +131 -0
- frontend/src/App.jsx +4 -0
- frontend/src/api.js +2 -0
- frontend/src/components/Sidebar.jsx +2 -1
- frontend/src/components/views/Audit.jsx +201 -0
- frontend/src/styles.css +58 -0
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Evidence-backed document audit.
|
| 2 |
+
|
| 3 |
+
Runs a finance-specific checklist over a document and reports, per check, either
|
| 4 |
+
the cited value the document supports or that the field is missing. It reuses the
|
| 5 |
+
SAME retrieval + abstention gate as ``/ask`` (``answer_question``) to FIND
|
| 6 |
+
candidate evidence, then applies a field-specific discriminator before calling a
|
| 7 |
+
check "supported": the cited excerpt must actually contain one of the field's
|
| 8 |
+
keywords (e.g. a "tax"/"vat" token for the tax check, a "due date"/"payment due"
|
| 9 |
+
phrase for the due-date check). Without that second gate, the generic /ask
|
| 10 |
+
coverage rule (any two query words overlapping anywhere) would mark a field
|
| 11 |
+
"present" off incidental words like "Sales"/"Charged" — a false positive that
|
| 12 |
+
would wrongly lower the audit's risk level. So a check passes only when the
|
| 13 |
+
document genuinely supports the field, and the audit never invents a value.
|
| 14 |
+
|
| 15 |
+
This is intentionally simple and deterministic: no new model, no LLM required.
|
| 16 |
+
"""
|
| 17 |
+
import logging
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from typing import List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from .answering import _focused_span, answer_question
|
| 22 |
+
from .models import Chunk
|
| 23 |
+
from .retrieval import tokenize
|
| 24 |
+
from .schemas import AuditMetrics, AuditResponse, Citation, Finding
|
| 25 |
+
|
| 26 |
+
logger = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass(frozen=True)
|
| 30 |
+
class _Check:
|
| 31 |
+
type: str # finding type key (stable id for the UI)
|
| 32 |
+
label: str # human-readable field name (used in claims/summary)
|
| 33 |
+
query: str # question used to retrieve candidate evidence via answer_question
|
| 34 |
+
severity: str # severity to assign WHEN THE FIELD IS MISSING (low/medium/high)
|
| 35 |
+
keywords: Tuple[str, ...] # ≥1 must appear in the cited excerpt to count as present
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# Checklists per audit type. `keywords` are the field's discriminators: distinctive
|
| 39 |
+
# (often multi-word) phrases that genuinely indicate the field is present, so an
|
| 40 |
+
# incidental overlap of generic query words can't pass the check. Matching is
|
| 41 |
+
# case-insensitive substring on the cited excerpt.
|
| 42 |
+
_CHECKLISTS = {
|
| 43 |
+
"invoice": [
|
| 44 |
+
_Check("total_amount", "total amount due", "What is the total amount due?", "high",
|
| 45 |
+
("total", "amount due", "balance due", "grand total", "amount payable")),
|
| 46 |
+
_Check("due_date", "due date", "What is the payment due date?", "high",
|
| 47 |
+
("due date", "payment due", "due by", "due on", "pay by", "payable by")),
|
| 48 |
+
_Check("payment_terms", "payment terms", "What are the payment terms, e.g. net 30?", "medium",
|
| 49 |
+
("net ", "payment term", "terms net", "due within", "payable within")),
|
| 50 |
+
_Check("invoice_number", "invoice number", "What is the invoice number?", "low",
|
| 51 |
+
("invoice number", "invoice no", "invoice #", "inv-", "invoice id")),
|
| 52 |
+
_Check("late_fee", "late fee", "What is the late fee or penalty for overdue payment?", "low",
|
| 53 |
+
("late fee", "late payment", "late charge", "overdue", "penalty", "per month", "per annum")),
|
| 54 |
+
_Check("tax", "tax / VAT", "What sales tax or VAT percentage is charged?", "low",
|
| 55 |
+
("tax", "vat", "gst")),
|
| 56 |
+
],
|
| 57 |
+
"contract": [
|
| 58 |
+
_Check("payment_terms", "payment terms", "What are the payment terms?", "high",
|
| 59 |
+
("net ", "payment term", "payable within", "due within", "paid within")),
|
| 60 |
+
_Check("termination", "termination clause", "What is the termination clause or notice period?", "medium",
|
| 61 |
+
("terminat", "notice period", "days' notice", "days notice", "may cancel", "for cause")),
|
| 62 |
+
_Check("liability", "liability clause", "What is the liability, penalty, or indemnification clause?", "medium",
|
| 63 |
+
("liabilit", "indemnif", "indemnit", "damages", "limitation of")),
|
| 64 |
+
_Check("renewal", "renewal terms", "Is there an automatic renewal or renewal term?", "medium",
|
| 65 |
+
("renew", "auto-renew", "automatic renewal", "renewal term")),
|
| 66 |
+
_Check("governing_law", "governing law", "What is the governing law or jurisdiction?", "low",
|
| 67 |
+
("governing law", "jurisdiction", "governed by", "laws of", "venue")),
|
| 68 |
+
_Check("late_fee", "late fee", "What interest or late fee applies to overdue amounts?", "low",
|
| 69 |
+
("late fee", "late charge", "overdue", "per annum", "per month", "interest on")),
|
| 70 |
+
],
|
| 71 |
+
"payment_note": [
|
| 72 |
+
_Check("amount", "payment amount", "What is the payment amount or outstanding balance?", "high",
|
| 73 |
+
("amount", "balance", "outstanding", "total due", "owing")),
|
| 74 |
+
_Check("due_date", "due date", "What is the payment due date?", "high",
|
| 75 |
+
("due date", "payment due", "due by", "due on", "pay by")),
|
| 76 |
+
_Check("overdue", "overdue status", "Is the payment overdue, and by how many days?", "medium",
|
| 77 |
+
("overdue", "past due", "days late", "days overdue", "arrears")),
|
| 78 |
+
_Check("reference", "reference number", "What is the invoice or reference number?", "low",
|
| 79 |
+
("reference", "ref ", "ref:", "ref.", "invoice no", "invoice number", "inv-")),
|
| 80 |
+
],
|
| 81 |
+
"general": [
|
| 82 |
+
_Check("total_amount", "amount", "What is the total amount or balance?", "medium",
|
| 83 |
+
("total", "amount", "balance", "subtotal")),
|
| 84 |
+
_Check("date", "key date", "What is the due date or other key date?", "medium",
|
| 85 |
+
("date", "deadline", "due")),
|
| 86 |
+
_Check("payment_terms", "payment terms", "What are the payment terms?", "low",
|
| 87 |
+
("net ", "payment term", "terms")),
|
| 88 |
+
_Check("parties", "parties", "Who are the parties, vendor, or customer involved?", "low",
|
| 89 |
+
("vendor", "customer", "client", "bill to", "sold to", "supplier", "between")),
|
| 90 |
+
],
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def checklist_for(audit_type: str) -> List[_Check]:
|
| 95 |
+
return _CHECKLISTS.get(audit_type) or _CHECKLISTS["general"]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _supporting_citation(
|
| 99 |
+
keywords: Tuple[str, ...], citations: List[Citation]
|
| 100 |
+
) -> Optional[Citation]:
|
| 101 |
+
"""The first cited excerpt that actually contains one of the field's
|
| 102 |
+
discriminators, or None — i.e. the field really appears in the evidence."""
|
| 103 |
+
for c in citations:
|
| 104 |
+
low = c.excerpt.lower()
|
| 105 |
+
if any(kw.strip() and kw in low for kw in keywords):
|
| 106 |
+
return c
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def _claim_span(keywords: Tuple[str, ...], excerpt: str, fallback: str) -> str:
|
| 111 |
+
"""A verbatim window of the excerpt centered on the field's discriminator, so
|
| 112 |
+
the shown value is the field's region (not a dense overlap of generic words).
|
| 113 |
+
Nothing is generated."""
|
| 114 |
+
low = excerpt.lower()
|
| 115 |
+
hit = next((kw for kw in keywords if kw.strip() and kw in low), None)
|
| 116 |
+
span = _focused_span(set(tokenize(hit)), excerpt, window_words=14) if hit else None
|
| 117 |
+
if span and span[1].strip():
|
| 118 |
+
return span[1].strip()
|
| 119 |
+
return (fallback or excerpt).strip()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def run_audit(audit_type: str, document_name: str, chunks: List[Chunk]) -> AuditResponse:
|
| 123 |
+
"""Run the checklist for ``audit_type`` over ``chunks`` and return the audit.
|
| 124 |
+
|
| 125 |
+
For each check we retrieve candidate evidence via ``answer_question`` and then
|
| 126 |
+
require the cited excerpt to contain the field's discriminator. Only then is
|
| 127 |
+
the finding SUPPORTED (with the cited value + citation); otherwise the field
|
| 128 |
+
is flagged unsupported (no citation) and takes the check's severity — a missing
|
| 129 |
+
critical field drives the risk level.
|
| 130 |
+
"""
|
| 131 |
+
findings: List[Finding] = []
|
| 132 |
+
for chk in checklist_for(audit_type):
|
| 133 |
+
answer, abstained, _mode, citations, _meta = answer_question(chk.query, chunks, "fast")
|
| 134 |
+
cite = None if abstained else _supporting_citation(chk.keywords, citations)
|
| 135 |
+
if cite is not None:
|
| 136 |
+
findings.append(
|
| 137 |
+
Finding(
|
| 138 |
+
type=chk.type,
|
| 139 |
+
severity="low", # present and cited -> verified, lowest concern
|
| 140 |
+
claim=_claim_span(chk.keywords, cite.excerpt, answer),
|
| 141 |
+
evidence=cite.excerpt,
|
| 142 |
+
citation=cite,
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
else:
|
| 146 |
+
findings.append(
|
| 147 |
+
Finding(
|
| 148 |
+
type=chk.type,
|
| 149 |
+
severity=chk.severity, # missing field -> risk by importance
|
| 150 |
+
claim=f"No {chk.label} found in the document.",
|
| 151 |
+
evidence="",
|
| 152 |
+
citation=None,
|
| 153 |
+
)
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
supported = [f for f in findings if f.citation is not None]
|
| 157 |
+
unsupported = [f for f in findings if f.citation is None]
|
| 158 |
+
coverage = round(len(supported) / len(findings), 2) if findings else 0.0
|
| 159 |
+
risk = _risk_level(unsupported)
|
| 160 |
+
|
| 161 |
+
logger.info(
|
| 162 |
+
"Audit type=%s doc=%r: %d/%d supported, risk=%s",
|
| 163 |
+
audit_type, document_name, len(supported), len(findings), risk,
|
| 164 |
+
)
|
| 165 |
+
return AuditResponse(
|
| 166 |
+
summary=_summary(audit_type, document_name, findings, supported, unsupported, risk),
|
| 167 |
+
risk_level=risk,
|
| 168 |
+
findings=findings,
|
| 169 |
+
metrics=AuditMetrics(
|
| 170 |
+
findings_count=len(findings),
|
| 171 |
+
supported_findings=len(supported),
|
| 172 |
+
unsupported_findings=len(unsupported),
|
| 173 |
+
citation_coverage=coverage,
|
| 174 |
+
),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _risk_level(unsupported: List[Finding]) -> str:
|
| 179 |
+
"""High if a high-severity field is missing, else medium, else low."""
|
| 180 |
+
if any(f.severity == "high" for f in unsupported):
|
| 181 |
+
return "high"
|
| 182 |
+
if any(f.severity == "medium" for f in unsupported):
|
| 183 |
+
return "medium"
|
| 184 |
+
return "low"
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _summary(audit_type, name, findings, supported, unsupported, risk) -> str:
|
| 188 |
+
label = audit_type.replace("_", " ")
|
| 189 |
+
missing = ", ".join(f.type.replace("_", " ") for f in unsupported) or "none"
|
| 190 |
+
return (
|
| 191 |
+
f"Audited '{name}' as a {label}: {len(supported)} of {len(findings)} checks "
|
| 192 |
+
f"supported by cited evidence, {len(unsupported)} unsupported "
|
| 193 |
+
f"(missing: {missing}). Overall risk: {risk}."
|
| 194 |
+
)
|
|
@@ -14,6 +14,7 @@ from starlette.requests import Request
|
|
| 14 |
|
| 15 |
from . import config
|
| 16 |
from .answering import answer_question
|
|
|
|
| 17 |
from .auth import get_current_user, router as auth_router
|
| 18 |
from .database import Base, engine, get_db
|
| 19 |
from .evaluation import ensure_sample_documents, run_evaluation
|
|
@@ -23,6 +24,8 @@ from .models import QA, Chunk, Document, User
|
|
| 23 |
from .schemas import (
|
| 24 |
AskRequest,
|
| 25 |
AskResponse,
|
|
|
|
|
|
|
| 26 |
Citation,
|
| 27 |
DemoSeedResponse,
|
| 28 |
DocumentDeleted,
|
|
@@ -41,6 +44,7 @@ TAGS_METADATA = [
|
|
| 41 |
{"name": "Health", "description": "Service status and current answer mode."},
|
| 42 |
{"name": "Documents", "description": "Upload, list, inspect, and delete documents."},
|
| 43 |
{"name": "Q&A", "description": "Ask grounded questions and review past answers."},
|
|
|
|
| 44 |
{"name": "Evaluation", "description": "Anti-hallucination golden-dataset evaluation."},
|
| 45 |
{"name": "Demo", "description": "One-click seeding so the app is testable instantly."},
|
| 46 |
]
|
|
@@ -325,6 +329,42 @@ def history(
|
|
| 325 |
return result
|
| 326 |
|
| 327 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
# --------------------------------------------------------------------------- #
|
| 329 |
# Evaluation
|
| 330 |
# --------------------------------------------------------------------------- #
|
|
|
|
| 14 |
|
| 15 |
from . import config
|
| 16 |
from .answering import answer_question
|
| 17 |
+
from .audit import run_audit
|
| 18 |
from .auth import get_current_user, router as auth_router
|
| 19 |
from .database import Base, engine, get_db
|
| 20 |
from .evaluation import ensure_sample_documents, run_evaluation
|
|
|
|
| 24 |
from .schemas import (
|
| 25 |
AskRequest,
|
| 26 |
AskResponse,
|
| 27 |
+
AuditRequest,
|
| 28 |
+
AuditResponse,
|
| 29 |
Citation,
|
| 30 |
DemoSeedResponse,
|
| 31 |
DocumentDeleted,
|
|
|
|
| 44 |
{"name": "Health", "description": "Service status and current answer mode."},
|
| 45 |
{"name": "Documents", "description": "Upload, list, inspect, and delete documents."},
|
| 46 |
{"name": "Q&A", "description": "Ask grounded questions and review past answers."},
|
| 47 |
+
{"name": "Audit", "description": "Evidence-backed audit of invoices, contracts, and payment notes."},
|
| 48 |
{"name": "Evaluation", "description": "Anti-hallucination golden-dataset evaluation."},
|
| 49 |
{"name": "Demo", "description": "One-click seeding so the app is testable instantly."},
|
| 50 |
]
|
|
|
|
| 329 |
return result
|
| 330 |
|
| 331 |
|
| 332 |
+
# --------------------------------------------------------------------------- #
|
| 333 |
+
# Audit
|
| 334 |
+
# --------------------------------------------------------------------------- #
|
| 335 |
+
@app.post(
|
| 336 |
+
"/audit",
|
| 337 |
+
response_model=AuditResponse,
|
| 338 |
+
tags=["Audit"],
|
| 339 |
+
summary="Audit a document for evidence-backed findings",
|
| 340 |
+
description=(
|
| 341 |
+
"Runs a finance-specific checklist over the document (invoice, contract, "
|
| 342 |
+
"payment note, or general) and returns per-field findings. Each finding is "
|
| 343 |
+
"either SUPPORTED by a citation or flagged as unsupported (missing) — the "
|
| 344 |
+
"audit reuses the same retrieval + abstention gate as /ask, so it never "
|
| 345 |
+
"invents a value."
|
| 346 |
+
),
|
| 347 |
+
)
|
| 348 |
+
def audit(
|
| 349 |
+
req: AuditRequest,
|
| 350 |
+
db: Session = Depends(get_db),
|
| 351 |
+
user: User = Depends(get_current_user),
|
| 352 |
+
):
|
| 353 |
+
document = _owned_document(db, user, req.document_id) # 404 if missing / not owned
|
| 354 |
+
if document.status != "processed":
|
| 355 |
+
raise HTTPException(
|
| 356 |
+
status_code=400,
|
| 357 |
+
detail="Document was not processed successfully and cannot be audited.",
|
| 358 |
+
)
|
| 359 |
+
chunks = db.query(Chunk).filter(Chunk.document_id == document.id).all()
|
| 360 |
+
result = run_audit(req.audit_type, document.filename, chunks)
|
| 361 |
+
logger.info(
|
| 362 |
+
"Audit doc=%d type=%s risk=%s findings=%d",
|
| 363 |
+
document.id, req.audit_type, result.risk_level, len(result.findings),
|
| 364 |
+
)
|
| 365 |
+
return result
|
| 366 |
+
|
| 367 |
+
|
| 368 |
# --------------------------------------------------------------------------- #
|
| 369 |
# Evaluation
|
| 370 |
# --------------------------------------------------------------------------- #
|
|
@@ -43,6 +43,40 @@ class AskResponse(BaseModel):
|
|
| 43 |
metadata: dict # question_type, evidence_status, confidence, scoring, latency, etc.
|
| 44 |
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
class QAOut(BaseModel):
|
| 47 |
id: int
|
| 48 |
document_id: int
|
|
|
|
| 43 |
metadata: dict # question_type, evidence_status, confidence, scoring, latency, etc.
|
| 44 |
|
| 45 |
|
| 46 |
+
# --------------------------------------------------------------------------- #
|
| 47 |
+
# Audit (evidence-backed document audit — see app/audit.py)
|
| 48 |
+
# --------------------------------------------------------------------------- #
|
| 49 |
+
AuditType = Literal["invoice", "contract", "payment_note", "general"]
|
| 50 |
+
Severity = Literal["low", "medium", "high"]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class AuditRequest(BaseModel):
|
| 54 |
+
document_id: int
|
| 55 |
+
audit_type: AuditType = "general"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Finding(BaseModel):
|
| 59 |
+
type: str # which check produced this (e.g. "total_amount", "due_date")
|
| 60 |
+
severity: Severity
|
| 61 |
+
claim: str # the cited value when supported, or "No X found…" when not
|
| 62 |
+
evidence: str # the supporting excerpt ("" when unsupported)
|
| 63 |
+
citation: Optional[Citation] = None # present only for supported findings
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class AuditMetrics(BaseModel):
|
| 67 |
+
findings_count: int
|
| 68 |
+
supported_findings: int
|
| 69 |
+
unsupported_findings: int
|
| 70 |
+
citation_coverage: float # supported / total, rounded to 2 (0..1)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class AuditResponse(BaseModel):
|
| 74 |
+
summary: str
|
| 75 |
+
risk_level: Severity
|
| 76 |
+
findings: List[Finding]
|
| 77 |
+
metrics: AuditMetrics
|
| 78 |
+
|
| 79 |
+
|
| 80 |
class QAOut(BaseModel):
|
| 81 |
id: int
|
| 82 |
document_id: int
|
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Audit endpoint tests — an evidence-backed checklist over a document.
|
| 2 |
+
|
| 3 |
+
The audit reuses the /ask retrieval + abstention gate, so a check is "supported"
|
| 4 |
+
only when the document genuinely backs it (with a citation), and "unsupported"
|
| 5 |
+
when the field is missing. Tests run on pure TF-IDF (conftest disables embeddings),
|
| 6 |
+
so they are deterministic.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
# A complete invoice: states a total, due date, terms, and number — but NO late
|
| 10 |
+
# fee and NO tax, so those two checks must come back unsupported.
|
| 11 |
+
_INVOICE = (
|
| 12 |
+
b"Invoice Number INV-2025-0473. Issue Date March 3 2025. "
|
| 13 |
+
b"Due Date April 2 2025. Total Amount Due $2,413.98. "
|
| 14 |
+
b"Payment terms net 30 days. Bill to Acme Corporation."
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# An invoice with incidental words that overlap the tax/due-date QUERIES
|
| 18 |
+
# ("Sales", "Charged", "Due" in "Amount Due") but genuinely has NO tax and NO due
|
| 19 |
+
# date. The audit must NOT mark those fields supported off incidental overlaps.
|
| 20 |
+
_TRAP_INVOICE = (
|
| 21 |
+
b"Invoice INV-99. Sales representative John handled this order. "
|
| 22 |
+
b"Total Amount Due 5000 dollars. Charged to account 12 on file. "
|
| 23 |
+
b"Percentage discount none."
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _upload(client, name, content):
|
| 28 |
+
res = client.post(
|
| 29 |
+
"/documents/upload", files={"file": (name, content, "text/plain")}
|
| 30 |
+
)
|
| 31 |
+
assert res.status_code == 200, res.text
|
| 32 |
+
return res.json()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _by_type(findings):
|
| 36 |
+
return {f["type"]: f for f in findings}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_invoice_audit_finds_total_due_date_and_terms(client):
|
| 40 |
+
doc = _upload(client, "invoice.txt", _INVOICE)
|
| 41 |
+
res = client.post(
|
| 42 |
+
"/audit", json={"document_id": doc["id"], "audit_type": "invoice"}
|
| 43 |
+
)
|
| 44 |
+
assert res.status_code == 200, res.text
|
| 45 |
+
body = res.json()
|
| 46 |
+
findings = _by_type(body["findings"])
|
| 47 |
+
|
| 48 |
+
# The three core invoice fields are present and each carries a citation.
|
| 49 |
+
for key in ("total_amount", "due_date", "payment_terms"):
|
| 50 |
+
f = findings[key]
|
| 51 |
+
assert f["citation"] is not None, f"{key} should be supported: {f}"
|
| 52 |
+
assert f["evidence"]
|
| 53 |
+
# The extracted total is the real, verbatim value from the doc — never invented.
|
| 54 |
+
assert "2,413.98" in findings["total_amount"]["claim"]
|
| 55 |
+
assert body["risk_level"] in ("low", "medium", "high")
|
| 56 |
+
assert body["summary"]
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_audit_flags_unsupported_missing_field(client):
|
| 60 |
+
doc = _upload(client, "invoice.txt", _INVOICE)
|
| 61 |
+
body = client.post(
|
| 62 |
+
"/audit", json={"document_id": doc["id"], "audit_type": "invoice"}
|
| 63 |
+
).json()
|
| 64 |
+
findings = _by_type(body["findings"])
|
| 65 |
+
|
| 66 |
+
# The invoice states no late fee and no tax -> unsupported, no citation.
|
| 67 |
+
for key in ("late_fee", "tax"):
|
| 68 |
+
f = findings[key]
|
| 69 |
+
assert f["citation"] is None, f"{key} should be unsupported: {f}"
|
| 70 |
+
assert f["evidence"] == ""
|
| 71 |
+
assert f["claim"].startswith("No ")
|
| 72 |
+
assert body["metrics"]["unsupported_findings"] >= 1
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_audit_citation_coverage_matches_supported_ratio(client):
|
| 76 |
+
doc = _upload(client, "invoice.txt", _INVOICE)
|
| 77 |
+
body = client.post(
|
| 78 |
+
"/audit", json={"document_id": doc["id"], "audit_type": "invoice"}
|
| 79 |
+
).json()
|
| 80 |
+
m = body["metrics"]
|
| 81 |
+
|
| 82 |
+
assert m["findings_count"] == len(body["findings"])
|
| 83 |
+
assert m["supported_findings"] + m["unsupported_findings"] == m["findings_count"]
|
| 84 |
+
expected = round(m["supported_findings"] / m["findings_count"], 2)
|
| 85 |
+
assert m["citation_coverage"] == expected
|
| 86 |
+
assert 0.0 < m["citation_coverage"] <= 1.0
|
| 87 |
+
|
| 88 |
+
# Coverage is grounded: every counted "supported" finding really has a citation.
|
| 89 |
+
supported = [f for f in body["findings"] if f["citation"] is not None]
|
| 90 |
+
assert len(supported) == m["supported_findings"]
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def test_audit_default_type_is_general(client):
|
| 94 |
+
doc = _upload(client, "invoice.txt", _INVOICE)
|
| 95 |
+
# audit_type omitted -> defaults to "general"; response shape is intact.
|
| 96 |
+
body = client.post("/audit", json={"document_id": doc["id"]}).json()
|
| 97 |
+
assert body["metrics"]["findings_count"] == len(body["findings"])
|
| 98 |
+
assert body["risk_level"] in ("low", "medium", "high")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_audit_does_not_falsely_support_absent_fields(client):
|
| 102 |
+
# Incidental query-word overlaps ("Sales"/"Charged"/"Due") must NOT make an
|
| 103 |
+
# absent field look present — that would inflate coverage and lower the risk.
|
| 104 |
+
doc = _upload(client, "trap.txt", _TRAP_INVOICE)
|
| 105 |
+
body = client.post(
|
| 106 |
+
"/audit", json={"document_id": doc["id"], "audit_type": "invoice"}
|
| 107 |
+
).json()
|
| 108 |
+
findings = _by_type(body["findings"])
|
| 109 |
+
assert findings["tax"]["citation"] is None, findings["tax"]
|
| 110 |
+
assert findings["due_date"]["citation"] is None, findings["due_date"]
|
| 111 |
+
# The total IS genuinely present -> still supported (no over-correction).
|
| 112 |
+
assert findings["total_amount"]["citation"] is not None
|
| 113 |
+
# A missing high-severity field (due_date) must escalate the risk.
|
| 114 |
+
assert body["risk_level"] == "high"
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_audit_on_missing_document_returns_404(client):
|
| 118 |
+
res = client.post(
|
| 119 |
+
"/audit", json={"document_id": 9999, "audit_type": "invoice"}
|
| 120 |
+
)
|
| 121 |
+
assert res.status_code == 404
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def test_audit_cannot_access_another_users_document(client, second_client):
|
| 125 |
+
# Per-user scoping: a different user must not be able to audit (or even learn
|
| 126 |
+
# of) someone else's private document — it 404s, never 403/leaks.
|
| 127 |
+
doc = _upload(client, "private.txt", _INVOICE)
|
| 128 |
+
res = second_client.post(
|
| 129 |
+
"/audit", json={"document_id": doc["id"], "audit_type": "invoice"}
|
| 130 |
+
)
|
| 131 |
+
assert res.status_code == 404
|
|
@@ -7,10 +7,12 @@ import { ErrorState } from "./components/ui/States";
|
|
| 7 |
import Overview from "./components/views/Overview";
|
| 8 |
import Ask from "./components/views/Ask";
|
| 9 |
import Evaluation from "./components/views/Evaluation";
|
|
|
|
| 10 |
import AuthScreen from "./components/views/AuthScreen";
|
| 11 |
|
| 12 |
const HEADINGS = {
|
| 13 |
ask: { title: "Ask", sub: "Questions are answered only from retrieved evidence." },
|
|
|
|
| 14 |
evaluation: { title: "Evaluation", sub: "How well the assistant stays grounded." },
|
| 15 |
};
|
| 16 |
|
|
@@ -192,6 +194,7 @@ export default function App() {
|
|
| 192 |
<nav className="topbar-nav">
|
| 193 |
<button type="button" onClick={() => setView("overview")}>Overview</button>
|
| 194 |
<button type="button" onClick={() => setView("ask")}>Ask</button>
|
|
|
|
| 195 |
<button type="button" onClick={() => setView("evaluation")}>Evaluation</button>
|
| 196 |
</nav>
|
| 197 |
<Button variant="primary" size="sm" loading={seeding} onClick={onTryDemo}>
|
|
@@ -233,6 +236,7 @@ export default function App() {
|
|
| 233 |
onDemoConsumed={() => {}}
|
| 234 |
/>
|
| 235 |
)}
|
|
|
|
| 236 |
{view === "evaluation" && <Evaluation />}
|
| 237 |
</main>
|
| 238 |
</div>
|
|
|
|
| 7 |
import Overview from "./components/views/Overview";
|
| 8 |
import Ask from "./components/views/Ask";
|
| 9 |
import Evaluation from "./components/views/Evaluation";
|
| 10 |
+
import Audit from "./components/views/Audit";
|
| 11 |
import AuthScreen from "./components/views/AuthScreen";
|
| 12 |
|
| 13 |
const HEADINGS = {
|
| 14 |
ask: { title: "Ask", sub: "Questions are answered only from retrieved evidence." },
|
| 15 |
+
audit: { title: "Audit", sub: "Evidence-backed checks with citations you can verify." },
|
| 16 |
evaluation: { title: "Evaluation", sub: "How well the assistant stays grounded." },
|
| 17 |
};
|
| 18 |
|
|
|
|
| 194 |
<nav className="topbar-nav">
|
| 195 |
<button type="button" onClick={() => setView("overview")}>Overview</button>
|
| 196 |
<button type="button" onClick={() => setView("ask")}>Ask</button>
|
| 197 |
+
<button type="button" onClick={() => setView("audit")}>Audit</button>
|
| 198 |
<button type="button" onClick={() => setView("evaluation")}>Evaluation</button>
|
| 199 |
</nav>
|
| 200 |
<Button variant="primary" size="sm" loading={seeding} onClick={onTryDemo}>
|
|
|
|
| 236 |
onDemoConsumed={() => {}}
|
| 237 |
/>
|
| 238 |
)}
|
| 239 |
+
{view === "audit" && <Audit documents={documents} />}
|
| 240 |
{view === "evaluation" && <Evaluation />}
|
| 241 |
</main>
|
| 242 |
</div>
|
|
@@ -74,6 +74,8 @@ export const api = {
|
|
| 74 |
deleteDocument: (id) => request(`/documents/${id}`, { method: "DELETE" }),
|
| 75 |
ask: (document_id, question, mode = "fast") =>
|
| 76 |
request("/ask", { method: "POST", json: { document_id, question, mode } }),
|
|
|
|
|
|
|
| 77 |
history: (document_id) =>
|
| 78 |
request(`/history${document_id ? `?document_id=${document_id}` : ""}`),
|
| 79 |
evaluate: () => request("/evaluate", { method: "POST" }),
|
|
|
|
| 74 |
deleteDocument: (id) => request(`/documents/${id}`, { method: "DELETE" }),
|
| 75 |
ask: (document_id, question, mode = "fast") =>
|
| 76 |
request("/ask", { method: "POST", json: { document_id, question, mode } }),
|
| 77 |
+
audit: (document_id, audit_type = "general") =>
|
| 78 |
+
request("/audit", { method: "POST", json: { document_id, audit_type } }),
|
| 79 |
history: (document_id) =>
|
| 80 |
request(`/history${document_id ? `?document_id=${document_id}` : ""}`),
|
| 81 |
evaluate: () => request("/evaluate", { method: "POST" }),
|
|
@@ -1,8 +1,9 @@
|
|
| 1 |
-
import { IconAsk, IconEval, IconLogout, IconOverview, IconSpark } from "../lib/icons";
|
| 2 |
|
| 3 |
const NAV = [
|
| 4 |
{ id: "overview", label: "Overview", Icon: IconOverview },
|
| 5 |
{ id: "ask", label: "Ask", Icon: IconAsk },
|
|
|
|
| 6 |
{ id: "evaluation", label: "Evaluation", Icon: IconEval },
|
| 7 |
];
|
| 8 |
|
|
|
|
| 1 |
+
import { IconAsk, IconEval, IconLogout, IconOverview, IconShield, IconSpark } from "../lib/icons";
|
| 2 |
|
| 3 |
const NAV = [
|
| 4 |
{ id: "overview", label: "Overview", Icon: IconOverview },
|
| 5 |
{ id: "ask", label: "Ask", Icon: IconAsk },
|
| 6 |
+
{ id: "audit", label: "Audit", Icon: IconShield },
|
| 7 |
{ id: "evaluation", label: "Evaluation", Icon: IconEval },
|
| 8 |
];
|
| 9 |
|
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useEffect, useState } from "react";
|
| 2 |
+
import { api } from "../../api";
|
| 3 |
+
import Badge from "../ui/Badge";
|
| 4 |
+
import Button from "../ui/Button";
|
| 5 |
+
import Card from "../ui/Card";
|
| 6 |
+
import { Select } from "../ui/Field";
|
| 7 |
+
import { EmptyState, ErrorState, LoadingState } from "../ui/States";
|
| 8 |
+
import MetricCard from "../MetricCard";
|
| 9 |
+
import { highlightMatch } from "../../lib/highlight";
|
| 10 |
+
import { IconAlert, IconCheck } from "../../lib/icons";
|
| 11 |
+
|
| 12 |
+
const AUDIT_TYPES = [
|
| 13 |
+
{ id: "invoice", label: "Invoice" },
|
| 14 |
+
{ id: "contract", label: "Contract" },
|
| 15 |
+
{ id: "payment_note", label: "Payment note" },
|
| 16 |
+
{ id: "general", label: "General" },
|
| 17 |
+
];
|
| 18 |
+
|
| 19 |
+
const RISK_TONE = { low: "success", medium: "warn", high: "danger" };
|
| 20 |
+
const SEV_TONE = { low: "neutral", medium: "warn", high: "danger" };
|
| 21 |
+
|
| 22 |
+
const titleize = (s) =>
|
| 23 |
+
s.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
| 24 |
+
|
| 25 |
+
// Evidence-backed audit dashboard. Picks a processed document + an audit type,
|
| 26 |
+
// runs the backend checklist, and renders the result as a B2B audit report:
|
| 27 |
+
// a risk badge, coverage metrics, and a finding per check (verified value with
|
| 28 |
+
// its citation, or a flagged missing field). Nothing here is generated — every
|
| 29 |
+
// supported claim carries the document excerpt it came from.
|
| 30 |
+
export default function Audit({ documents }) {
|
| 31 |
+
const processed = documents.filter((d) => d.status === "processed");
|
| 32 |
+
const [docId, setDocId] = useState("");
|
| 33 |
+
const [auditType, setAuditType] = useState("invoice");
|
| 34 |
+
const [data, setData] = useState(null);
|
| 35 |
+
const [loading, setLoading] = useState(false);
|
| 36 |
+
const [error, setError] = useState("");
|
| 37 |
+
|
| 38 |
+
// Default to the sample invoice when present, else the first processed doc.
|
| 39 |
+
useEffect(() => {
|
| 40 |
+
if (docId || processed.length === 0) return;
|
| 41 |
+
const invoice = processed.find((d) => d.filename === "sample_invoice.txt");
|
| 42 |
+
setDocId(String((invoice || processed[0]).id));
|
| 43 |
+
}, [processed, docId]);
|
| 44 |
+
|
| 45 |
+
// Clear a stale result whenever the selection changes, so the report on screen
|
| 46 |
+
// always corresponds to the currently selected document + audit type (an audit
|
| 47 |
+
// tool must never attribute citations to the wrong document).
|
| 48 |
+
useEffect(() => {
|
| 49 |
+
setData(null);
|
| 50 |
+
setError("");
|
| 51 |
+
}, [docId, auditType]);
|
| 52 |
+
|
| 53 |
+
async function run() {
|
| 54 |
+
if (!docId) return;
|
| 55 |
+
setError("");
|
| 56 |
+
setLoading(true);
|
| 57 |
+
setData(null);
|
| 58 |
+
try {
|
| 59 |
+
setData(await api.audit(Number(docId), auditType));
|
| 60 |
+
} catch (err) {
|
| 61 |
+
setError(err.message);
|
| 62 |
+
} finally {
|
| 63 |
+
setLoading(false);
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
if (processed.length === 0) {
|
| 68 |
+
return (
|
| 69 |
+
<EmptyState title="No documents to audit">
|
| 70 |
+
Head to <strong>Overview</strong> and click <strong>Try Demo</strong> (or
|
| 71 |
+
upload a file), then come back to run an audit.
|
| 72 |
+
</EmptyState>
|
| 73 |
+
);
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
const m = data?.metrics;
|
| 77 |
+
const pct = (v) => `${Math.round(v * 100)}%`;
|
| 78 |
+
|
| 79 |
+
return (
|
| 80 |
+
<div className="stack">
|
| 81 |
+
<Card>
|
| 82 |
+
<div className="audit-controls">
|
| 83 |
+
<Select
|
| 84 |
+
label="Document"
|
| 85 |
+
value={docId}
|
| 86 |
+
onChange={(e) => setDocId(e.target.value)}
|
| 87 |
+
>
|
| 88 |
+
{processed.map((d) => (
|
| 89 |
+
<option key={d.id} value={d.id}>
|
| 90 |
+
{d.filename}
|
| 91 |
+
</option>
|
| 92 |
+
))}
|
| 93 |
+
</Select>
|
| 94 |
+
<div>
|
| 95 |
+
<span className="field-label">Audit type</span>
|
| 96 |
+
<div className="audit-types" role="group" aria-label="Audit type">
|
| 97 |
+
{AUDIT_TYPES.map((t) => (
|
| 98 |
+
<button
|
| 99 |
+
key={t.id}
|
| 100 |
+
type="button"
|
| 101 |
+
aria-pressed={auditType === t.id}
|
| 102 |
+
className={`audit-type-btn ${auditType === t.id ? "active" : ""}`}
|
| 103 |
+
onClick={() => setAuditType(t.id)}
|
| 104 |
+
>
|
| 105 |
+
{t.label}
|
| 106 |
+
</button>
|
| 107 |
+
))}
|
| 108 |
+
</div>
|
| 109 |
+
</div>
|
| 110 |
+
</div>
|
| 111 |
+
|
| 112 |
+
<p className="muted audit-tagline">
|
| 113 |
+
FinanceFlow audits invoices, contracts, and payment notes for totals,
|
| 114 |
+
due dates, payment terms, late fees, and unsupported claims — with
|
| 115 |
+
citations you can verify.
|
| 116 |
+
</p>
|
| 117 |
+
|
| 118 |
+
<div style={{ marginTop: 16 }}>
|
| 119 |
+
<Button variant="primary" onClick={run} loading={loading}>
|
| 120 |
+
{loading ? "Auditing…" : data ? "Re-run audit" : "Run audit"}
|
| 121 |
+
</Button>
|
| 122 |
+
</div>
|
| 123 |
+
<div style={{ marginTop: 12 }}>
|
| 124 |
+
<ErrorState>{error}</ErrorState>
|
| 125 |
+
</div>
|
| 126 |
+
</Card>
|
| 127 |
+
|
| 128 |
+
{loading && !data && (
|
| 129 |
+
<Card>
|
| 130 |
+
<LoadingState lines={4} label="Auditing document…" />
|
| 131 |
+
</Card>
|
| 132 |
+
)}
|
| 133 |
+
|
| 134 |
+
{data && m && (
|
| 135 |
+
<>
|
| 136 |
+
<Card>
|
| 137 |
+
<div className="audit-summary-head">
|
| 138 |
+
<h2 style={{ margin: 0, fontSize: "var(--text-lg)" }}>Audit result</h2>
|
| 139 |
+
<Badge tone={RISK_TONE[data.risk_level]} dot>
|
| 140 |
+
{data.risk_level} risk
|
| 141 |
+
</Badge>
|
| 142 |
+
</div>
|
| 143 |
+
<p className="audit-summary">{data.summary}</p>
|
| 144 |
+
<div className="metric-grid">
|
| 145 |
+
<MetricCard value={m.findings_count} label="Checks run" />
|
| 146 |
+
<MetricCard value={m.supported_findings} label="Supported" tone="good" />
|
| 147 |
+
<MetricCard
|
| 148 |
+
value={m.unsupported_findings}
|
| 149 |
+
label="Unsupported"
|
| 150 |
+
tone={m.unsupported_findings === 0 ? "good" : "bad"}
|
| 151 |
+
hint="Expected fields with no evidence."
|
| 152 |
+
/>
|
| 153 |
+
<MetricCard value={pct(m.citation_coverage)} label="Citation coverage" />
|
| 154 |
+
</div>
|
| 155 |
+
</Card>
|
| 156 |
+
|
| 157 |
+
<div>
|
| 158 |
+
<div className="section-title">
|
| 159 |
+
<h2>Findings</h2>
|
| 160 |
+
<span className="muted">{data.findings.length} checks</span>
|
| 161 |
+
</div>
|
| 162 |
+
<div className="audit-findings">
|
| 163 |
+
{data.findings.map((f, i) => {
|
| 164 |
+
const supported = f.citation != null;
|
| 165 |
+
return (
|
| 166 |
+
<div key={i} className={`finding ${supported ? "ok" : "miss"}`}>
|
| 167 |
+
<div className="finding-top">
|
| 168 |
+
<span className="finding-icon" aria-hidden>
|
| 169 |
+
{supported ? <IconCheck size={14} /> : <IconAlert size={14} />}
|
| 170 |
+
</span>
|
| 171 |
+
<span className="finding-type">{titleize(f.type)}</span>
|
| 172 |
+
{supported ? (
|
| 173 |
+
<Badge tone="success" dot>verified</Badge>
|
| 174 |
+
) : (
|
| 175 |
+
<Badge tone={SEV_TONE[f.severity]} dot>
|
| 176 |
+
{f.severity}
|
| 177 |
+
</Badge>
|
| 178 |
+
)}
|
| 179 |
+
</div>
|
| 180 |
+
<div className="finding-claim">{f.claim}</div>
|
| 181 |
+
{supported && (
|
| 182 |
+
<div className="finding-evidence">
|
| 183 |
+
<div className="finding-evidence-label">
|
| 184 |
+
Evidence · {f.citation.document_name}
|
| 185 |
+
{f.citation.page != null ? ` · page ${f.citation.page}` : ""}
|
| 186 |
+
</div>
|
| 187 |
+
<div className="finding-excerpt">
|
| 188 |
+
{highlightMatch(f.evidence, f.citation.match_text)}
|
| 189 |
+
</div>
|
| 190 |
+
</div>
|
| 191 |
+
)}
|
| 192 |
+
</div>
|
| 193 |
+
);
|
| 194 |
+
})}
|
| 195 |
+
</div>
|
| 196 |
+
</div>
|
| 197 |
+
</>
|
| 198 |
+
)}
|
| 199 |
+
</div>
|
| 200 |
+
);
|
| 201 |
+
}
|
|
@@ -907,6 +907,64 @@ code {
|
|
| 907 |
.metric-label { font-size: 12.5px; color: var(--text-dim); margin-top: 4px; }
|
| 908 |
.metric-hint { font-size: 11.5px; color: var(--text-faint); margin-top: 7px; line-height: 1.4; }
|
| 909 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 910 |
/* Eval table */
|
| 911 |
.eval-table { display: flex; flex-direction: column; gap: 10px; }
|
| 912 |
.eval-row {
|
|
|
|
| 907 |
.metric-label { font-size: 12.5px; color: var(--text-dim); margin-top: 4px; }
|
| 908 |
.metric-hint { font-size: 11.5px; color: var(--text-faint); margin-top: 7px; line-height: 1.4; }
|
| 909 |
|
| 910 |
+
/* ===================== Audit dashboard =================================== */
|
| 911 |
+
|
| 912 |
+
.audit-controls { display: grid; grid-template-columns: 1fr; gap: 16px; align-items: start; }
|
| 913 |
+
@media (min-width: 720px) {
|
| 914 |
+
.audit-controls { grid-template-columns: minmax(220px, 1fr) 1.5fr; }
|
| 915 |
+
}
|
| 916 |
+
.audit-types { display: flex; flex-wrap: wrap; gap: 8px; }
|
| 917 |
+
.audit-type-btn {
|
| 918 |
+
flex: 1 1 auto; min-width: 92px;
|
| 919 |
+
padding: 9px 12px;
|
| 920 |
+
border: 1px solid var(--border);
|
| 921 |
+
border-radius: var(--r-md);
|
| 922 |
+
background: var(--surface-1);
|
| 923 |
+
color: var(--text-dim);
|
| 924 |
+
font-size: 13px; font-weight: 600;
|
| 925 |
+
cursor: pointer;
|
| 926 |
+
transition: border-color 0.15s var(--ease), background 0.15s var(--ease), color 0.15s var(--ease);
|
| 927 |
+
}
|
| 928 |
+
.audit-type-btn:hover { border-color: var(--border-strong); color: var(--text); }
|
| 929 |
+
.audit-type-btn.active {
|
| 930 |
+
background: var(--accent-soft);
|
| 931 |
+
color: var(--accent);
|
| 932 |
+
border-color: rgba(37, 99, 235, 0.35);
|
| 933 |
+
}
|
| 934 |
+
.audit-tagline { font-size: 13px; line-height: 1.6; margin-top: 14px; max-width: 72ch; }
|
| 935 |
+
.audit-summary-head {
|
| 936 |
+
display: flex; align-items: center; justify-content: space-between;
|
| 937 |
+
gap: 12px; margin-bottom: 10px;
|
| 938 |
+
}
|
| 939 |
+
.audit-summary { color: var(--text-dim); font-size: 14px; line-height: 1.6; margin: 0 0 18px; max-width: 80ch; }
|
| 940 |
+
.audit-findings { display: grid; gap: 12px; }
|
| 941 |
+
@media (min-width: 760px) { .audit-findings { grid-template-columns: 1fr 1fr; } }
|
| 942 |
+
.finding {
|
| 943 |
+
border: 1px solid var(--border);
|
| 944 |
+
border-left: 3px solid var(--border-strong);
|
| 945 |
+
border-radius: var(--r-md);
|
| 946 |
+
background: var(--surface-1);
|
| 947 |
+
padding: 14px 16px;
|
| 948 |
+
}
|
| 949 |
+
.finding.ok { border-left-color: var(--success); }
|
| 950 |
+
.finding.miss { border-left-color: var(--danger); }
|
| 951 |
+
.finding-top { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
| 952 |
+
.finding-icon {
|
| 953 |
+
display: inline-grid; place-items: center;
|
| 954 |
+
width: 22px; height: 22px; border-radius: 6px; flex: none;
|
| 955 |
+
}
|
| 956 |
+
.finding.ok .finding-icon { color: var(--success); background: var(--success-soft); }
|
| 957 |
+
.finding.miss .finding-icon { color: var(--danger); background: var(--danger-soft); }
|
| 958 |
+
.finding-type { font-weight: 700; font-size: 13.5px; flex: 1; min-width: 0; }
|
| 959 |
+
.finding-claim { font-size: 14px; color: var(--text); line-height: 1.5; word-break: break-word; }
|
| 960 |
+
.finding.miss .finding-claim { color: var(--text-faint); font-style: italic; }
|
| 961 |
+
.finding-evidence { margin-top: 10px; padding-top: 10px; border-top: 1px dashed var(--border); }
|
| 962 |
+
.finding-evidence-label {
|
| 963 |
+
font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.05em;
|
| 964 |
+
color: var(--text-faint); margin-bottom: 4px;
|
| 965 |
+
}
|
| 966 |
+
.finding-excerpt { font-size: 12.5px; color: var(--text-dim); line-height: 1.55; }
|
| 967 |
+
|
| 968 |
/* Eval table */
|
| 969 |
.eval-table { display: flex; flex-direction: column; gap: 10px; }
|
| 970 |
.eval-row {
|