#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Wire portal audit tab and documents to real audit data (#6912)
Anthony Stirling9ea848570f80
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/audit/DefaultPortalAuditScopeResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/audit/DefaultPortalAuditScopeResolver.javanew file mode 100644index 0000000000..3eb476c4df--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/audit/DefaultPortalAuditScopeResolver.java@@ -0,0 +1,15 @@+package stirling.software.proprietary.audit;++import org.springframework.stereotype.Component;++/** Self-hosted default: admins see the whole-server audit log, everyone else is denied. */+@Component+public class DefaultPortalAuditScopeResolver implements PortalAuditScopeResolver {++ @Override+ public PortalAuditScope resolve() {+ return PortalAuditScopeResolver.hasAdminAuthority()+ ? PortalAuditScope.server()+ : PortalAuditScope.denied();+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditEventRow.java b/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditEventRow.javanew file mode 100644index 0000000000..622d17c354--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditEventRow.java@@ -0,0 +1,7 @@+package stirling.software.proprietary.audit;++import java.time.Instant;++/** Immutable, cacheable projection of an {@code audit_events} row, shared across portal views. */+public record PortalAuditEventRow(+ long id, String principal, String type, String data, Instant timestamp) {}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditScope.java b/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditScope.javanew file mode 100644index 0000000000..078dc2a332--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditScope.java@@ -0,0 +1,21 @@+package stirling.software.proprietary.audit;++import java.util.List;++/** Resolved audit visibility: fullServer (admin), principals-scoped (team lead), or !allowed. */+public record PortalAuditScope(+ boolean allowed, boolean fullServer, List<String> principals, String cacheKey) {++ public static PortalAuditScope denied() {+ return new PortalAuditScope(false, false, List.of(), "denied");+ }++ // Named server()/team() to avoid colliding with the record's fullServer() accessor.+ public static PortalAuditScope server() {+ return new PortalAuditScope(true, true, List.of(), "server");+ }++ public static PortalAuditScope team(String cacheKey, List<String> principals) {+ return new PortalAuditScope(true, false, List.copyOf(principals), cacheKey);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditScopeResolver.java b/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditScopeResolver.javanew file mode 100644index 0000000000..59b68d720e--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/audit/PortalAuditScopeResolver.java@@ -0,0 +1,18 @@+package stirling.software.proprietary.audit;++import org.springframework.security.core.Authentication;+import org.springframework.security.core.context.SecurityContextHolder;++/** Resolves which slice of the audit log the caller may see. */+public interface PortalAuditScopeResolver {++ PortalAuditScope resolve();++ /** True when the current authentication carries {@code ROLE_ADMIN}. */+ static boolean hasAdminAuthority() {+ Authentication auth = SecurityContextHolder.getContext().getAuthentication();+ return auth != null+ && auth.getAuthorities().stream()+ .anyMatch(a -> "ROLE_ADMIN".equals(a.getAuthority()));+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/PortalDocumentsController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/PortalDocumentsController.javanew file mode 100644index 0000000000..14146eacb4--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/PortalDocumentsController.java@@ -0,0 +1,46 @@+package stirling.software.proprietary.controller.api;++import org.springframework.http.HttpStatus;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.GetMapping;+import org.springframework.web.bind.annotation.RequestParam;++import io.swagger.v3.oas.annotations.Operation;++import lombok.RequiredArgsConstructor;++import stirling.software.common.annotations.api.ProprietaryUiDataApi;+import stirling.software.proprietary.audit.PortalAuditScope;+import stirling.software.proprietary.audit.PortalAuditScopeResolver;+import stirling.software.proprietary.model.api.documents.PortalDocumentsResponseDto;+import stirling.software.proprietary.security.config.EnterpriseEndpoint;+import stirling.software.proprietary.service.PortalDocumentsService;++/** Serves the portal Documents review queue, derived from real audit data and scoped per caller. */+@ProprietaryUiDataApi+@RequiredArgsConstructor+@EnterpriseEndpoint+public class PortalDocumentsController {++ private final PortalDocumentsService portalDocumentsService;+ private final PortalAuditScopeResolver auditScopeResolver;++ // tier accepted for mock-seam symmetry; ignored (queue isn't tier-scoped).+ @GetMapping("/documents")+ @Operation(+ summary = "Documents review queue",+ description = "Files processed through the org, derived from the audit trail.")+ public ResponseEntity<PortalDocumentsResponseDto> getDocuments(+ @RequestParam(value = "tier", required = false) String tier) {+ PortalAuditScope scope = auditScopeResolver.resolve();+ if (!scope.allowed()) {+ return ResponseEntity.status(HttpStatus.FORBIDDEN).build();+ }+ PortalDocumentsResponseDto body =+ scope.fullServer()+ ? portalDocumentsService.serverDocuments()+ : portalDocumentsService.scopedDocuments(+ scope.cacheKey(), scope.principals());+ return ResponseEntity.ok(body);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/PortalInfraAuditController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/PortalInfraAuditController.javanew file mode 100644index 0000000000..866c295b8d--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/PortalInfraAuditController.java@@ -0,0 +1,47 @@+package stirling.software.proprietary.controller.api;++import org.springframework.http.HttpStatus;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.GetMapping;+import org.springframework.web.bind.annotation.RequestParam;++import io.swagger.v3.oas.annotations.Operation;++import lombok.RequiredArgsConstructor;++import stirling.software.common.annotations.api.ProprietaryUiDataApi;+import stirling.software.proprietary.audit.PortalAuditScope;+import stirling.software.proprietary.audit.PortalAuditScopeResolver;+import stirling.software.proprietary.model.api.audit.InfraAuditLogResponse;+import stirling.software.proprietary.security.config.EnterpriseEndpoint;+import stirling.software.proprietary.service.PortalInfraAuditService;++/** Serves the Infrastructure → Audit tab from real audit data, scoped and cached per caller. */+@ProprietaryUiDataApi+@RequiredArgsConstructor+@EnterpriseEndpoint+public class PortalInfraAuditController {++ private final PortalInfraAuditService portalInfraAuditService;+ private final PortalAuditScopeResolver auditScopeResolver;++ // tier accepted for endpoint symmetry; ignored (audit log isn't tier-scoped).+ @GetMapping("/infrastructure/audit-log")+ @Operation(+ summary = "Infrastructure audit log",+ description = "Recent audit events shaped for the portal Infrastructure → Audit tab.")+ public ResponseEntity<InfraAuditLogResponse> getInfrastructureAuditLog(+ @RequestParam(value = "tier", required = false) String tier) {+ PortalAuditScope scope = auditScopeResolver.resolve();+ if (!scope.allowed()) {+ // Return 403 (not throw) so the tab shows its access message, not a generic 500.+ return ResponseEntity.status(HttpStatus.FORBIDDEN).build();+ }+ InfraAuditLogResponse body =+ scope.fullServer()+ ? portalInfraAuditService.serverAuditLog()+ : portalInfraAuditService.scopedAuditLog(+ scope.cacheKey(), scope.principals());+ return ResponseEntity.ok(body);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditEventDto.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditEventDto.javanew file mode 100644index 0000000000..86c27e2c6e--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditEventDto.java@@ -0,0 +1,44 @@+package stirling.software.proprietary.model.api.audit;++import io.swagger.v3.oas.annotations.media.Schema;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/**+ * A single infrastructure audit-log row, shaped for the portal Infrastructure → Audit tab. Derived+ * from a {@code audit_events} row: the real {@link+ * stirling.software.proprietary.audit.AuditEventType} is mapped to a display category/action.+ */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class InfraAuditEventDto {++ @Schema(description = "Audit event id", example = "8841")+ private String id;++ @Schema(description = "Display timestamp (UTC)", example = "2026-07-07 18:59:31")+ private String timestamp;++ @Schema(description = "Category: auth | config | elevation | processing | security")+ private String category;++ @Schema(description = "Human-readable action", example = "Compress PDF")+ private String action;++ @Schema(description = "Actor principal", example = "[email protected]")+ private String actor;++ @Schema(description = "Affected target (file, endpoint, or session)")+ private String target;++ @Schema(description = "Status: success | warning | danger | info")+ private String status;++ @Schema(description = "Operation latency in milliseconds", example = "412")+ private long latencyMs;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditLogResponse.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditLogResponse.javanew file mode 100644index 0000000000..9b1b9d31c8--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditLogResponse.java@@ -0,0 +1,30 @@+package stirling.software.proprietary.model.api.audit;++import java.util.List;++import io.swagger.v3.oas.annotations.media.Schema;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/** Response for the portal Infrastructure → Audit tab: summary strip + recent event rows. */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class InfraAuditLogResponse {++ @Schema(description = "Headline counts")+ private InfraAuditSummary summary;++ @Schema(description = "Most-recent audit events, newest first")+ private List<InfraAuditEventDto> events;++ @Schema(+ description =+ "True when this is the whole-server (admin) view. Team-scoped views are false; "+ + "drives whether the admin-only, whole-server CSV export is offered.")+ private boolean fullServer;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditSummary.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditSummary.javanew file mode 100644index 0000000000..c924218e3a--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/audit/InfraAuditSummary.java@@ -0,0 +1,28 @@+package stirling.software.proprietary.model.api.audit;++import io.swagger.v3.oas.annotations.media.Schema;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/** Headline counts for the infrastructure audit-log tab, derived from the returned events. */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class InfraAuditSummary {++ @Schema(description = "Total events in the returned window", example = "40")+ private int totalEvents;++ @Schema(description = "Processing-category events", example = "24")+ private int processing;++ @Schema(description = "Elevation-category events", example = "0")+ private int elevation;++ @Schema(description = "Config-category events", example = "6")+ private int config;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocAuditEventDto.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocAuditEventDto.javanew file mode 100644index 0000000000..c3e4ac3d7e--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocAuditEventDto.java@@ -0,0 +1,24 @@+package stirling.software.proprietary.model.api.documents;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/** One event in a document's lifecycle timeline. */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class PortalDocAuditEventDto {+ private String id;++ /** ingested | extracted | flagged | reviewed | approved | archived | elevation */+ private String kind;++ /** Relative-time string, e.g. "2m ago". */+ private String time;++ private String actor;+ private String detail;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocumentsResponseDto.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocumentsResponseDto.javanew file mode 100644index 0000000000..f9b1f28009--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocumentsResponseDto.java@@ -0,0 +1,18 @@+package stirling.software.proprietary.model.api.documents;++import java.util.List;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/** Response for the portal Documents review queue. */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class PortalDocumentsResponseDto {+ private PortalDocumentsSummaryDto summary;+ private List<PortalReviewDocumentDto> documents;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocumentsSummaryDto.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocumentsSummaryDto.javanew file mode 100644index 0000000000..1222afdc03--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalDocumentsSummaryDto.java@@ -0,0 +1,18 @@+package stirling.software.proprietary.model.api.documents;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/** KPI strip for the documents queue. */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class PortalDocumentsSummaryDto {+ private int totalInQueue;+ private int processed;+ private int errors;+ private int processedToday;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalExtractionDto.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalExtractionDto.javanew file mode 100644index 0000000000..e332530dbc--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalExtractionDto.java@@ -0,0 +1,17 @@+package stirling.software.proprietary.model.api.documents;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/** A single extracted field. Empty for audit-derived documents (no extraction data yet). */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class PortalExtractionDto {+ private String field;+ private String value;+ private double confidence;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalReviewDocumentDto.java b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalReviewDocumentDto.javanew file mode 100644index 0000000000..658b1c991d--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/model/api/documents/PortalReviewDocumentDto.java@@ -0,0 +1,48 @@+package stirling.software.proprietary.model.api.documents;++import java.util.List;++import lombok.AllArgsConstructor;+import lombok.Builder;+import lombok.Data;+import lombok.NoArgsConstructor;++/**+ * A document in the review queue, derived from the audit trail of a processed file. Extraction+ * fields ({@code confidence}, {@code extractions}) are absent/empty - that data doesn't exist yet.+ */+@Data+@Builder+@NoArgsConstructor+@AllArgsConstructor+public class PortalReviewDocumentDto {+ private String id;+ private String name;+ private String type;++ /** Where it was processed: "API" or "Editor". */+ private String product;++ /** The operation / pipeline, e.g. "Compress PDF" (or "Editor"). */+ private String action;++ /** The user who ran it. */+ private String user;++ /** processed | error */+ private String status;++ private String source;++ /** Overall confidence 0..1, or null when there's no extraction data. */+ private Double confidence;++ private int fieldsExtracted;++ /** Relative-time string, e.g. "4m ago". */+ private String time;++ private boolean sensitive;+ private List<PortalExtractionDto> extractions;+ private List<PortalDocAuditEventDto> audit;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.javaindex 501826a084..eef27703f2 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/CacheConfig.java@@ -24,6 +24,9 @@ public class CacheConfig {this.applicationProperties = applicationProperties;}+ /** Short-TTL cache of recent audit rows, shared by every audit-derived portal view. */+ private static final String PORTAL_AUDIT_EVENTS_CACHE = "portalAuditEvents";+@Beanpublic CacheManager cacheManager() {int keyRetentionDays = applicationProperties.getSecurity().getJwt().getKeyRetentionDays();@@ -33,6 +36,14 @@ public class CacheConfig {.maximumSize(1000) // Make configurable?.expireAfterWrite(Duration.ofDays(keyRetentionDays)).recordStats());+ // 30s TTL keeps audit views near-live without re-scanning the DB; one entry per scope.+ cacheManager.registerCustomCache(+ PORTAL_AUDIT_EVENTS_CACHE,+ Caffeine.newBuilder()+ .maximumSize(256)+ .expireAfterWrite(Duration.ofSeconds(30))+ .recordStats()+ .build());return cacheManager;}}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalAuditReadService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalAuditReadService.javanew file mode 100644index 0000000000..1678cd095f--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalAuditReadService.java@@ -0,0 +1,60 @@+package stirling.software.proprietary.service;++import java.util.List;++import org.springframework.cache.annotation.Cacheable;+import org.springframework.data.domain.PageRequest;+import org.springframework.data.domain.Sort;+import org.springframework.stereotype.Service;++import lombok.RequiredArgsConstructor;++import stirling.software.proprietary.audit.PortalAuditEventRow;+import stirling.software.proprietary.model.security.PersistentAuditEvent;+import stirling.software.proprietary.repository.PersistentAuditEventRepository;++/** One cached read of recent {@code audit_events} per scope, shared by all audit-derived views. */+@Service+@RequiredArgsConstructor+public class PortalAuditReadService {++ /** Cache name - registered with a short TTL in CacheConfig. */+ public static final String CACHE_NAME = "portalAuditEvents";++ /** Newest rows to scan; each surface filters this down to what it shows. */+ private static final int SCAN_LIMIT = 400;++ private final PersistentAuditEventRepository auditRepository;++ /** Recent whole-server events (admins). */+ @Cacheable(value = CACHE_NAME, key = "'server'")+ public List<PortalAuditEventRow> serverEvents() {+ return toRows(auditRepository.findAll(recentPage()).getContent());+ }++ /** Recent events by the given principals (team scope). Empty principals yield an empty list. */+ @Cacheable(value = CACHE_NAME, key = "#cacheKey")+ public List<PortalAuditEventRow> scopedEvents(String cacheKey, List<String> principals) {+ if (principals.isEmpty()) {+ return List.of();+ }+ return toRows(auditRepository.findByPrincipalIn(principals, recentPage()).getContent());+ }++ private static PageRequest recentPage() {+ return PageRequest.of(0, SCAN_LIMIT, Sort.by(Sort.Direction.DESC, "timestamp"));+ }++ private static List<PortalAuditEventRow> toRows(List<PersistentAuditEvent> events) {+ return events.stream()+ .map(+ e ->+ new PortalAuditEventRow(+ e.getId() == null ? 0L : e.getId(),+ e.getPrincipal(),+ e.getType(),+ e.getData(),+ e.getTimestamp()))+ .toList();+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalDocumentsService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalDocumentsService.javanew file mode 100644index 0000000000..8784d5c5b6--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalDocumentsService.java@@ -0,0 +1,268 @@+package stirling.software.proprietary.service;++import java.time.Duration;+import java.time.Instant;+import java.util.ArrayList;+import java.util.List;+import java.util.Locale;+import java.util.Map;++import org.springframework.stereotype.Service;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.audit.AuditEventType;+import stirling.software.proprietary.audit.PortalAuditEventRow;+import stirling.software.proprietary.model.api.documents.PortalDocAuditEventDto;+import stirling.software.proprietary.model.api.documents.PortalDocumentsResponseDto;+import stirling.software.proprietary.model.api.documents.PortalDocumentsSummaryDto;+import stirling.software.proprietary.model.api.documents.PortalReviewDocumentDto;++import tools.jackson.core.JacksonException;+import tools.jackson.databind.ObjectMapper;++/** Builds the Documents feed from audit_events: one row per file; extraction fields stay null. */+@Slf4j+@Service+@RequiredArgsConstructor+public class PortalDocumentsService {++ private static final int RETURN_LIMIT = 40;++ private final PortalAuditReadService auditReadService;+ private final ObjectMapper objectMapper;++ /** Whole-server view (admins). */+ public PortalDocumentsResponseDto serverDocuments() {+ return build(auditReadService.serverEvents());+ }++ /** Team-scoped view: only files touched by {@code principals}. */+ public PortalDocumentsResponseDto scopedDocuments(String cacheKey, List<String> principals) {+ return build(auditReadService.scopedEvents(cacheKey, principals));+ }++ private PortalDocumentsResponseDto build(List<PortalAuditEventRow> events) {+ // Events arrive newest-first; each file in a processing event is one activity row.+ Instant dayAgo = Instant.now().minus(Duration.ofDays(1));+ List<PortalReviewDocumentDto> documents = new ArrayList<>();+ int processedToday = 0;+ for (PortalAuditEventRow event : events) {+ if (documents.size() >= RETURN_LIMIT) {+ break;+ }+ if (!isFileBearing(event.type())) {+ continue;+ }+ Map<String, Object> data = parseData(event);+ Object files = data.get("files");+ if (!(files instanceof List<?> fileList)) {+ continue;+ }+ String path = asString(data.get("path"));+ String source = sourceLabel(asString(data.get("__origin")));+ String product = "API integration".equals(source) ? "API" : "Editor";+ String action = prettyTool(path);+ boolean failed = isFailure(data);+ Instant ts = event.timestamp();+ long eventId = event.id();+ int idx = 0;+ for (Object f : fileList) {+ if (documents.size() >= RETURN_LIMIT) {+ break;+ }+ if (!(f instanceof Map<?, ?> fileMap)) {+ continue;+ }+ String name = asString(fileMap.get("name"));+ if (name == null || name.isBlank()) {+ continue;+ }+ documents.add(+ toDocument(+ eventId + "-" + idx++,+ name,+ asString(fileMap.get("type")),+ product,+ action,+ event.principal(),+ failed,+ source,+ ts));+ if (!failed && ts != null && ts.isAfter(dayAgo)) {+ processedToday++;+ }+ }+ }++ int processed =+ (int) documents.stream().filter(d -> "processed".equals(d.getStatus())).count();+ int errors = documents.size() - processed;++ PortalDocumentsSummaryDto summary =+ PortalDocumentsSummaryDto.builder()+ .totalInQueue(documents.size())+ .processed(processed)+ .errors(errors)+ .processedToday(processedToday)+ .build();++ return PortalDocumentsResponseDto.builder().summary(summary).documents(documents).build();+ }++ /** Build one activity row from a single file inside one processing event. */+ private PortalReviewDocumentDto toDocument(+ String rowId,+ String name,+ String contentType,+ String product,+ String action,+ String user,+ boolean failed,+ String source,+ Instant timestamp) {+ PortalDocAuditEventDto op =+ PortalDocAuditEventDto.builder()+ .id(rowId + "-op")+ .kind(failed ? "flagged" : "extracted")+ .time(relativeTime(timestamp))+ .actor(user)+ .detail(failed ? action + " failed" : action + " via " + source)+ .build();++ return PortalReviewDocumentDto.builder()+ .id("doc-" + rowId)+ .name(name)+ .type(docType(contentType, name))+ .product(product)+ .action(action)+ .user(user)+ .status(failed ? "error" : "processed")+ .source(source)+ .confidence(null)+ .fieldsExtracted(0)+ .time(relativeTime(timestamp))+ // Audit events don't reveal content sensitivity, so never guess it.+ .sensitive(false)+ .extractions(List.of())+ .audit(List.of(op))+ .build();+ }++ private static boolean isFileBearing(String type) {+ return AuditEventType.PDF_PROCESS.name().equals(type)+ || AuditEventType.FILE_OPERATION.name().equals(type);+ }++ private static boolean isFailure(Map<String, Object> data) {+ Object status = data.get("status");+ if (status instanceof String s && "failure".equalsIgnoreCase(s)) {+ return true;+ }+ Object code = data.get("statusCode");+ return code instanceof Number n && n.intValue() >= 400;+ }++ private static String sourceLabel(String origin) {+ if ("API".equals(origin)) {+ return "API integration";+ }+ if ("SYSTEM".equals(origin)) {+ return "System";+ }+ return "Web upload";+ }++ private static String docType(String contentType, String name) {+ String ct = contentType == null ? "" : contentType.toLowerCase(Locale.ROOT);+ if (ct.contains("pdf") || name.toLowerCase(Locale.ROOT).endsWith(".pdf")) {+ return "PDF";+ }+ if (ct.startsWith("image/") || name.matches("(?i).*\\.(png|jpe?g|gif|webp|tiff?)$")) {+ return "Image";+ }+ if (ct.contains("word") || name.matches("(?i).*\\.docx?$")) {+ return "Word";+ }+ return "Document";+ }++ private static String prettyTool(String path) {+ if (path == null || path.isBlank()) {+ return "Processed";+ }+ String[] parts = path.split("/");+ // Convert endpoints are /convert/{from}/{to}; label them as a conversion.+ for (int i = 0; i + 2 < parts.length; i++) {+ if ("convert".equals(parts[i]) && !parts[i + 1].isEmpty() && !parts[i + 2].isEmpty()) {+ return "Convert " + prettyWords(parts[i + 1]) + " to " + prettyWords(parts[i + 2]);+ }+ }+ String last = parts.length > 0 ? parts[parts.length - 1] : path;+ String pretty = prettyWords(last);+ return pretty.isEmpty() ? "Processed" : pretty;+ }++ /** Title-case a hyphenated path segment, upper-casing known acronyms. */+ private static String prettyWords(String segment) {+ StringBuilder sb = new StringBuilder();+ for (String word : segment.split("-")) {+ if (word.isEmpty()) {+ continue;+ }+ if (sb.length() > 0) {+ sb.append(' ');+ }+ String lower = word.toLowerCase(Locale.ROOT);+ sb.append(+ switch (lower) {+ case "pdf" -> "PDF";+ case "pdfs" -> "PDFs";+ case "ocr" -> "OCR";+ case "img" -> "Image";+ case "csv" -> "CSV";+ default -> Character.toUpperCase(word.charAt(0)) + word.substring(1);+ });+ }+ return sb.toString();+ }++ private static String relativeTime(Instant ts) {+ if (ts == null) {+ return "";+ }+ long seconds = Duration.between(ts, Instant.now()).getSeconds();+ if (seconds < 60) {+ return "just now";+ }+ long minutes = seconds / 60;+ if (minutes < 60) {+ return minutes + "m ago";+ }+ long hours = minutes / 60;+ if (hours < 24) {+ return hours + "h ago";+ }+ return (hours / 24) + "d ago";+ }++ private Map<String, Object> parseData(PortalAuditEventRow event) {+ if (event.data() == null || event.data().isEmpty()) {+ return Map.of();+ }+ try {+ @SuppressWarnings("unchecked")+ Map<String, Object> parsed = objectMapper.readValue(event.data(), Map.class);+ // A literal "null" payload parses to null; treat it as empty, not an NPE.+ return parsed == null ? Map.of() : parsed;+ } catch (JacksonException e) {+ log.warn("Failed to parse audit event {} data as JSON", event.id());+ return Map.of();+ }+ }++ private static String asString(Object o) {+ return o == null ? null : String.valueOf(o);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalInfraAuditService.java b/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalInfraAuditService.javanew file mode 100644index 0000000000..73d45800a8--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/service/PortalInfraAuditService.java@@ -0,0 +1,251 @@+package stirling.software.proprietary.service;++import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.List;+import java.util.Locale;+import java.util.Map;++import org.springframework.stereotype.Service;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.audit.AuditEventType;+import stirling.software.proprietary.audit.PortalAuditEventRow;+import stirling.software.proprietary.model.api.audit.InfraAuditEventDto;+import stirling.software.proprietary.model.api.audit.InfraAuditLogResponse;+import stirling.software.proprietary.model.api.audit.InfraAuditSummary;++import tools.jackson.core.JacksonException;+import tools.jackson.databind.ObjectMapper;++/** Maps cached audit_events to the Infrastructure → Audit tab, dropping read-noise types. */+@Slf4j+@Service+@RequiredArgsConstructor+public class PortalInfraAuditService {++ /** Rows returned to the tab after filtering. */+ private static final int RETURN_LIMIT = 40;++ private static final DateTimeFormatter TS_FORMAT =+ DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC);++ private final PortalAuditReadService auditReadService;+ private final ObjectMapper objectMapper;++ /** Whole-server view (admins). */+ public InfraAuditLogResponse serverAuditLog() {+ return buildFromEvents(auditReadService.serverEvents(), true);+ }++ /** Team-scoped view: only events by the given principals; empty yields an empty log. */+ public InfraAuditLogResponse scopedAuditLog(String cacheKey, List<String> principals) {+ return buildFromEvents(auditReadService.scopedEvents(cacheKey, principals), false);+ }++ private InfraAuditLogResponse buildFromEvents(+ List<PortalAuditEventRow> recent, boolean fullServer) {+ List<InfraAuditEventDto> events =+ recent.stream()+ .filter(e -> isInfraRelevant(e.type()))+ .map(this::toDto)+ .limit(RETURN_LIMIT)+ .toList();++ int processing =+ (int) events.stream().filter(e -> "processing".equals(e.getCategory())).count();+ int elevation =+ (int) events.stream().filter(e -> "elevation".equals(e.getCategory())).count();+ int config = (int) events.stream().filter(e -> "config".equals(e.getCategory())).count();++ InfraAuditSummary summary =+ InfraAuditSummary.builder()+ .totalEvents(events.size())+ .processing(processing)+ .elevation(elevation)+ .config(config)+ .build();++ return InfraAuditLogResponse.builder()+ .summary(summary)+ .events(events)+ .fullServer(fullServer)+ .build();+ }++ /** UI_DATA and HTTP_REQUEST are read/polling noise - excluded from the infrastructure view. */+ private static boolean isInfraRelevant(String type) {+ return !AuditEventType.UI_DATA.name().equals(type)+ && !AuditEventType.HTTP_REQUEST.name().equals(type);+ }++ private InfraAuditEventDto toDto(PortalAuditEventRow event) {+ Map<String, Object> data = parseData(event);+ String path = asString(data.get("path"));+ String category = categoryFor(event.type(), path);++ return InfraAuditEventDto.builder()+ .id(String.valueOf(event.id()))+ .timestamp(event.timestamp() == null ? "" : TS_FORMAT.format(event.timestamp()))+ .category(category)+ .action(actionFor(event.type(), path))+ .actor(event.principal())+ .target(targetFor(category, path, data))+ .status(statusFor(event.type(), category, data))+ .latencyMs(asLong(data.get("latencyMs")))+ .build();+ }++ private Map<String, Object> parseData(PortalAuditEventRow event) {+ if (event.data() == null || event.data().isEmpty()) {+ return Map.of();+ }+ try {+ @SuppressWarnings("unchecked")+ Map<String, Object> parsed = objectMapper.readValue(event.data(), Map.class);+ // A literal "null" payload parses to null; treat it as empty, not an NPE.+ return parsed == null ? Map.of() : parsed;+ } catch (JacksonException e) {+ log.warn("Failed to parse audit event {} data as JSON", event.id());+ return Map.of();+ }+ }++ private static String categoryFor(String type, String path) {+ AuditEventType t = AuditEventType.fromString(type);+ if (t == null) {+ return "processing";+ }+ return switch (t) {+ case USER_LOGIN, USER_LOGOUT, USER_FAILED_LOGIN -> "auth";+ case SETTINGS_CHANGED, USER_PROFILE_UPDATE -> "config";+ case PDF_PROCESS, FILE_OPERATION -> isSecurityPath(path) ? "security" : "processing";+ // UI_DATA / HTTP_REQUEST are filtered out before mapping.+ default -> "processing";+ };+ }++ private static boolean isSecurityPath(String path) {+ if (path == null) {+ return false;+ }+ String p = path.toLowerCase(Locale.ROOT);+ return p.contains("/security/")+ || p.contains("password")+ || p.contains("watermark")+ || p.contains("sign")+ || p.contains("cert")+ || p.contains("redact");+ }++ private static String actionFor(String type, String path) {+ AuditEventType t = AuditEventType.fromString(type);+ if (t == null) {+ return prettyTool(path);+ }+ return switch (t) {+ case USER_LOGIN -> "User signed in";+ case USER_LOGOUT -> "User signed out";+ case USER_FAILED_LOGIN -> "Failed sign-in attempt";+ case USER_PROFILE_UPDATE -> "Profile settings updated";+ case SETTINGS_CHANGED -> "Admin settings changed";+ case PDF_PROCESS, FILE_OPERATION -> prettyTool(path);+ default -> prettyTool(path);+ };+ }++ /** Acronyms/tokens that get special casing when title-casing a tool path. */+ private static final Map<String, String> WORD_FIXUPS =+ Map.of(+ "pdf", "PDF",+ "pdfs", "PDFs",+ "ocr", "OCR",+ "img", "Image",+ "csv", "CSV",+ "html", "HTML",+ "url", "URL",+ "xml", "XML");++ /** "/api/v1/misc/compress-pdf" → "Compress PDF"; "merge-pdfs" → "Merge PDFs". */+ private static String prettyTool(String path) {+ if (path == null || path.isBlank()) {+ return "PDF operation";+ }+ String[] parts = path.split("/");+ String last = parts.length > 0 ? parts[parts.length - 1] : path;+ StringBuilder sb = new StringBuilder();+ for (String word : last.split("-")) {+ if (word.isEmpty()) {+ continue;+ }+ if (sb.length() > 0) {+ sb.append(' ');+ }+ String lower = word.toLowerCase(Locale.ROOT);+ sb.append(+ WORD_FIXUPS.getOrDefault(+ lower, Character.toUpperCase(word.charAt(0)) + word.substring(1)));+ }+ return sb.isEmpty() ? "PDF operation" : sb.toString();+ }++ private static String targetFor(String category, String path, Map<String, Object> data) {+ if ("auth".equals(category)) {+ // Auth events don't act on a resource; the session is the closest thing.+ return "Web session";+ }+ if ("config".equals(category)) {+ return path != null && !path.isBlank() ? path : "System settings";+ }+ // processing / security: prefer the first affected file name.+ String file = firstFileName(data);+ if (file != null) {+ return file;+ }+ return path != null && !path.isBlank() ? prettyTool(path) : "Document";+ }++ private static String statusFor(String type, String category, Map<String, Object> data) {+ if (AuditEventType.USER_FAILED_LOGIN.name().equals(type)) {+ return "danger";+ }+ String status = asString(data.get("status"));+ Integer code = asInteger(data.get("statusCode"));+ if ("failure".equalsIgnoreCase(status) || (code != null && code >= 500)) {+ return "danger";+ }+ if (code != null && code >= 400) {+ return "warning";+ }+ if ("config".equals(category)) {+ return "info";+ }+ return "success";+ }++ @SuppressWarnings("unchecked")+ private static String firstFileName(Map<String, Object> data) {+ Object files = data.get("files");+ if (files instanceof List<?> list+ && !list.isEmpty()+ && list.get(0) instanceof Map<?, ?> f) {+ Object name = ((Map<String, Object>) f).get("name");+ return name != null ? String.valueOf(name) : null;+ }+ return null;+ }++ private static String asString(Object o) {+ return o == null ? null : String.valueOf(o);+ }++ private static long asLong(Object o) {+ return o instanceof Number n ? n.longValue() : 0L;+ }++ private static Integer asInteger(Object o) {+ return o instanceof Number n ? n.intValue() : null;+ }+}diff --git a/app/saas/src/main/java/stirling/software/saas/security/SaasPortalAuditScopeResolver.java b/app/saas/src/main/java/stirling/software/saas/security/SaasPortalAuditScopeResolver.javanew file mode 100644index 0000000000..00c7c42757--- /dev/null+++ b/app/saas/src/main/java/stirling/software/saas/security/SaasPortalAuditScopeResolver.java@@ -0,0 +1,45 @@+package stirling.software.saas.security;++import java.util.List;+import java.util.Objects;++import org.springframework.context.annotation.Primary;+import org.springframework.context.annotation.Profile;+import org.springframework.stereotype.Component;++import lombok.RequiredArgsConstructor;++import stirling.software.proprietary.audit.PortalAuditScope;+import stirling.software.proprietary.audit.PortalAuditScopeResolver;+import stirling.software.saas.repository.TeamMembershipRepository;++/** SaaS audit visibility: admins see the server; team LEADERs see their team (by member email). */+@Component+@Primary+@Profile("saas")+@RequiredArgsConstructor+public class SaasPortalAuditScopeResolver implements PortalAuditScopeResolver {++ private final TeamSecurityExpressions teamSecurity;+ private final TeamMembershipRepository membershipRepository;++ @Override+ public PortalAuditScope resolve() {+ if (PortalAuditScopeResolver.hasAdminAuthority()) {+ return PortalAuditScope.server();+ }+ if (!teamSecurity.isCurrentUserTeamLeader()) {+ return PortalAuditScope.denied();+ }+ Long teamId = teamSecurity.currentUserTeamId();+ if (teamId == null) {+ return PortalAuditScope.denied();+ }+ List<String> memberEmails =+ membershipRepository.findByTeamId(teamId).stream()+ .map(m -> m.getUser() == null ? null : m.getUser().getEmail())+ .filter(Objects::nonNull)+ .toList();+ return PortalAuditScope.team("team:" + teamId, memberEmails);+ }+}diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 5a27ded6ee..6c301dac25 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -6576,7 +6576,9 @@ beforeHelper = "header against your signing secret before trusting a payload. SDbeforeSignature = "Verify the"[portal.documents]-subtitle = "Review and approve documents moving through your pipelines."+exportCsv = "Export CSV"+search = "Search by filename, ID..."+subtitle = "Every document your org has processed, with its full processing record. Content access is request-gated."title = "Documents"[portal.documents.audit]@@ -6614,42 +6616,38 @@ value = "Value"[portal.documents.filters]all = "All"-archived = "Archived"ariaLabel = "Filter documents by status"-needsReview = "Needs review"+flagged = "Flagged"+inReview = "In review"processed = "Processed"[portal.documents.overview]-confidence = "Confidence"-fieldsExtracted = "Fields extracted"-received = "Received"-source = "Source"+action = "Pipeline / Action"+product = "Product"+received = "Time"status = "Status"type = "Type"+user = "User"[portal.documents.queue.empty]description = "As sources feed documents into your pipelines they'll appear here for review."title = "No documents in the queue"-[portal.documents.summary]-avgConfidence = "Avg confidence"-inQueue = "In queue"-needsReview = "Needs review"-processedToday = "Processed today"-[portal.documents.table]+auto = "Auto"+editorAction = "Editor"empty = "No documents match this filter."+rowActions = "Row actions"sensitiveLabel = "Sensitive"sensitiveTitle = "Sensitive — access required"[portal.documents.table.columns]-confidence = "Confidence"-fields = "Fields"-name = "Name"-source = "Source"+action = "Pipeline / Action"+document = "Document"+product = "Product"status = "Status"time = "Time"-type = "Type"+user = "User"[portal.editorAdmin]subtitle = "Deploy the Stirling PDF Editor, pair self-hosted instances to your org, and operate the running fleet — targets, health, credentials, and offline activation in one place."@@ -6894,13 +6892,32 @@ actor = "Actor"event = "Event"latency = "Latency"status = "Status"-target = "Target"+target = "Resource"timestamp = "Timestamp"[portal.infrastructure.audit.empty]description = "Workspace activity will appear here as it happens."title = "No audit events"+[portal.infrastructure.audit.export]+cancel = "Cancel"+error = "Export failed. Please try again."+exportButton = "Export"+exporting = "Exporting…"+fieldsLegend = "Columns"+format = "Format"+open = "Export"+subtitle = "Download audit events as CSV or JSON. Choose which columns to include."+title = "Export audit log"++[portal.infrastructure.audit.export.fields]+date = "Date"+documentName = "Document name"+ipAddress = "IP address"+outcome = "Outcome"+tool = "Tool"+username = "Username"+[portal.infrastructure.audit.filters]all = "All"auth = "Auth"@@ -6909,6 +6926,10 @@ elevation = "Elevation"processing = "Processing"security = "Security"+[portal.infrastructure.audit.forbidden]+description = "The audit log is available to team leads and admins. Ask your team lead or an admin for access."+title = "You don't have access"+[portal.infrastructure.audit.metrics]config = "Config"elevation = "Elevation"diff --git a/frontend/editor/src/portal/api/documents.ts b/frontend/editor/src/portal/api/documents.tsindex 3e8e4e1170..25e34f731d 100644--- a/frontend/editor/src/portal/api/documents.ts+++ b/frontend/editor/src/portal/api/documents.ts@@ -9,18 +9,22 @@ export type {DocumentsResponse,DocumentsSummary,Extraction,+ ProductType,ReviewDocument,} from "@portal/mocks/documents";export {+ classificationTone,DOC_AUDIT_LABEL,DOC_AUDIT_TONE,DOCUMENT_STATUS_LABEL,DOCUMENT_STATUS_TONE,+ PRODUCT_CHIP_TONE,} from "@portal/mocks/documents";-/** GET /v1/documents?tier=… — summary strip + the review queue for the tier. */+/** GET the audit-derived Documents feed; SaaS or local, scoped server-side. `tier` ignored. */export async function fetchDocuments(tier: Tier): Promise<DocumentsResponse> {- return apiClient.local.json<DocumentsResponse>(- `/v1/documents?tier=${encodeURIComponent(tier)}`,- );+ const path = `/api/v1/proprietary/ui-data/documents?tier=${encodeURIComponent(tier)}`;+ return apiClient.saas.isConfigured()+ ? apiClient.saas.json<DocumentsResponse>(path)+ : apiClient.local.json<DocumentsResponse>(path);}diff --git a/frontend/editor/src/portal/api/http.ts b/frontend/editor/src/portal/api/http.tsindex 2dfa914890..17bc55a530 100644--- a/frontend/editor/src/portal/api/http.ts+++ b/frontend/editor/src/portal/api/http.ts@@ -168,6 +168,24 @@ async function localJson<T>(return unwrap<T>(res);}+/** Same-origin GET returning a binary Blob (e.g. a CSV/JSON export download). */+async function localBlob(+ path: string,+ options: HttpRequestOptions = {},+): Promise<Blob> {+ const res = await fetch(path, {+ method: options.method ?? "GET",+ headers: { ...localAuthHeader(), ...options.headers },+ signal: options.signal,+ });+ if (res.status === 401) {+ clearStoredToken();+ window.dispatchEvent(new CustomEvent("jwt-available"));+ }+ if (!res.ok) throw new HttpError(res.status, res.statusText, null);+ return res.blob();+}+// ────────────────────────────────────────────────────────────────────────────// saas — hosted SaaS Java, admin's Supabase JWT// ────────────────────────────────────────────────────────────────────────────@@ -197,6 +215,25 @@ async function saasJson<T>(return unwrap<T>(res);}+/** SaaS GET returning a binary Blob, with the Supabase JWT attached. */+async function saasBlob(+ path: string,+ options: HttpRequestOptions = {},+): Promise<Blob> {+ const base = saasBaseUrl();+ // Same-origin SaaS resolves to "" (falsy); only null means unconfigured.+ if (base === null) throw new SaasUnconfiguredError();+ const token = await getPortalSaasToken();+ if (!token) throw new SaasNotLinkedError();+ const res = await fetch(`${base}${path}`, {+ method: options.method ?? "GET",+ headers: { Authorization: `Bearer ${token}`, ...options.headers },+ signal: options.signal,+ });+ if (!res.ok) throw new HttpError(res.status, res.statusText, null);+ return res.blob();+}+// ────────────────────────────────────────────────────────────────────────────// Exported API client// ────────────────────────────────────────────────────────────────────────────@@ -205,10 +242,12 @@ export const apiClient = {/** Local backend (this instance). Spring admin bearer auto-attached. */local: {json: localJson,+ blob: localBlob,},/** Hosted SaaS Java. Admin's Supabase JWT auto-attached. */saas: {json: saasJson,+ blob: saasBlob,/** True when a SaaS base URL is resolvable. Doesn't check session liveness. */isConfigured: (): boolean => saasBaseUrl() !== null,},diff --git a/frontend/editor/src/portal/api/infrastructure.ts b/frontend/editor/src/portal/api/infrastructure.tsindex 9d3023abd6..ec844330fe 100644--- a/frontend/editor/src/portal/api/infrastructure.ts+++ b/frontend/editor/src/portal/api/infrastructure.ts@@ -90,9 +90,23 @@ export async function fetchStorage(tier: Tier): Promise<StorageConfig> {);}-/** GET /v1/infrastructure/audit-log?tier=… */+/** GET the audit log; SaaS or local, backend-scoped (admin → server, SaaS lead → team). */export async function fetchAuditLog(tier: Tier): Promise<AuditLogResponse> {- return apiClient.local.json<AuditLogResponse>(- `/v1/infrastructure/audit-log${q(tier)}`,- );+ const path = `/api/v1/proprietary/ui-data/infrastructure/audit-log${q(tier)}`;+ return apiClient.saas.isConfigured()+ ? apiClient.saas.json<AuditLogResponse>(path)+ : apiClient.local.json<AuditLogResponse>(path);+}++/** Download the audit log as a CSV/JSON blob (admin-only, whole-server); SaaS or local. */+export async function exportAuditLog(+ format: "csv" | "json",+ fields: string,+): Promise<Blob> {+ const path = `/api/v1/proprietary/ui-data/audit-export?format=${format}&fields=${encodeURIComponent(+ fields,+ )}`;+ return apiClient.saas.isConfigured()+ ? apiClient.saas.blob(path)+ : apiClient.local.blob(path);}diff --git a/frontend/editor/src/portal/components/documents/DocumentExtractions.stories.tsx b/frontend/editor/src/portal/components/documents/DocumentExtractions.stories.tsxindex a729289915..d96ef55a1f 100644--- a/frontend/editor/src/portal/components/documents/DocumentExtractions.stories.tsx+++ b/frontend/editor/src/portal/components/documents/DocumentExtractions.stories.tsx@@ -6,9 +6,6 @@ import "@portal/views/Documents.css";const ALL = documentsFor("enterprise");const NON_SENSITIVE = ALL.find((d) => !d.sensitive)!;const SENSITIVE = ALL.find((d) => d.sensitive)!;-const NO_AMOUNT = ALL.find((d) =>- d.extractions.some((e) => e.confidence === 0),-)!;const meta: Meta<typeof DocumentExtractions> = {title: "Portal/Documents/DocumentExtractions",@@ -26,14 +23,9 @@ const meta: Meta<typeof DocumentExtractions> = {export default meta;type Story = StoryObj<typeof DocumentExtractions>;-/** Per-field table with mixed confidence tones. */+/** No extraction data exists yet - the table shows its empty state. */export const Default: Story = {};-/** A field that failed to extract sits at 0% confidence. */-export const LowConfidence: Story = {- args: { doc: NO_AMOUNT },-};-/** Sensitive doc with no active grant — content stays masked. */export const Masked: Story = {args: { doc: SENSITIVE, unlocked: false },diff --git a/frontend/editor/src/portal/components/documents/DocumentOverview.tsx b/frontend/editor/src/portal/components/documents/DocumentOverview.tsxindex 3994bd7098..91fa0ce6b8 100644--- a/frontend/editor/src/portal/components/documents/DocumentOverview.tsx+++ b/frontend/editor/src/portal/components/documents/DocumentOverview.tsx@@ -4,9 +4,8 @@ import {DOCUMENT_STATUS_LABEL,type ReviewDocument,} from "@portal/api/documents";-import { confidencePct } from "@portal/components/documents/format";-/** Key fields for the selected document — status, source, confidence. */+/** Key fields for the selected document - product, action, user, status. */export function DocumentOverview({ doc }: { doc: ReviewDocument }) {const { t } = useTranslation();return (@@ -17,20 +16,22 @@ export function DocumentOverview({ doc }: { doc: ReviewDocument }) {value={DOCUMENT_STATUS_LABEL[doc.status]}/><StatTile- label={t("portal.documents.overview.type")}- value={doc.type}+ label={t("portal.documents.overview.product")}+ value={doc.product}/><StatTile- label={t("portal.documents.overview.confidence")}- value={confidencePct(doc.confidence)}+ label={t("portal.documents.overview.action")}+ value={+ doc.product === "Editor" || !doc.action ? "Editor" : doc.action+ }/><StatTile- label={t("portal.documents.overview.fieldsExtracted")}- value={doc.fieldsExtracted}+ label={t("portal.documents.overview.user")}+ value={doc.user || "-"}/><StatTile- label={t("portal.documents.overview.source")}- value={doc.source}+ label={t("portal.documents.overview.type")}+ value={doc.type}/><StatTilelabel={t("portal.documents.overview.received")}diff --git a/frontend/editor/src/portal/components/documents/DocumentsSummaryStrip.stories.tsx b/frontend/editor/src/portal/components/documents/DocumentsSummaryStrip.stories.tsxdeleted file mode 100644index 1bab1092be..0000000000--- a/frontend/editor/src/portal/components/documents/DocumentsSummaryStrip.stories.tsx+++ /dev/null@@ -1,26 +0,0 @@-import type { Meta, StoryObj } from "@storybook/react-vite";-import { summaryFor } from "@portal/mocks/documents";-import { DocumentsSummaryStrip } from "@portal/components/documents/DocumentsSummaryStrip";-import "@portal/views/Documents.css";--const meta: Meta<typeof DocumentsSummaryStrip> = {- title: "Portal/Documents/DocumentsSummaryStrip",- component: DocumentsSummaryStrip,- parameters: { layout: "padded" },- args: { summary: summaryFor("enterprise"), loading: false },- decorators: [- (S) => (- <div style={{ maxWidth: "78rem" }}>- <S />- </div>- ),- ],-};-export default meta;-type Story = StoryObj<typeof DocumentsSummaryStrip>;--export const Default: Story = {};--export const Loading: Story = {- args: { summary: null, loading: true },-};diff --git a/frontend/editor/src/portal/components/documents/DocumentsSummaryStrip.tsx b/frontend/editor/src/portal/components/documents/DocumentsSummaryStrip.tsxdeleted file mode 100644index eb116e7393..0000000000--- a/frontend/editor/src/portal/components/documents/DocumentsSummaryStrip.tsx+++ /dev/null@@ -1,48 +0,0 @@-import { useTranslation } from "react-i18next";-import { MetricCard, MetricStrip, Skeleton } from "@app/ui";-import type { DocumentsSummary } from "@portal/api/documents";-import { confidencePct } from "@portal/components/documents/format";--interface DocumentsSummaryStripProps {- summary: DocumentsSummary | null;- loading: boolean;-}--/** KPI strip across the top of the review queue. */-export function DocumentsSummaryStrip({- summary,- loading,-}: DocumentsSummaryStripProps) {- const { t } = useTranslation();- if (loading && !summary) {- return (- <MetricStrip>- {Array.from({ length: 4 }).map((_, i) => (- <Skeleton key={i} height="5.5rem" />- ))}- </MetricStrip>- );- }- if (!summary) return null;-- return (- <MetricStrip>- <MetricCard- label={t("portal.documents.summary.inQueue")}- value={summary.totalInQueue.toLocaleString()}- />- <MetricCard- label={t("portal.documents.summary.needsReview")}- value={summary.needsReview.toLocaleString()}- />- <MetricCard- label={t("portal.documents.summary.avgConfidence")}- value={confidencePct(summary.avgConfidence)}- />- <MetricCard- label={t("portal.documents.summary.processedToday")}- value={summary.processedToday.toLocaleString()}- />- </MetricStrip>- );-}diff --git a/frontend/editor/src/portal/components/documents/ReviewQueue.stories.tsx b/frontend/editor/src/portal/components/documents/ReviewQueue.stories.tsxindex 2d1d37d88e..ced1628253 100644--- a/frontend/editor/src/portal/components/documents/ReviewQueue.stories.tsx+++ b/frontend/editor/src/portal/components/documents/ReviewQueue.stories.tsx@@ -1,5 +1,5 @@import type { Meta, StoryObj } from "@storybook/react-vite";-import { http, HttpResponse, delay } from "msw";+import { documentsFor } from "@portal/mocks/documents";import { ReviewQueue } from "@portal/components/documents/ReviewQueue";import "@portal/views/Documents.css";@@ -7,9 +7,10 @@ const meta: Meta<typeof ReviewQueue> = {title: "Portal/Documents/ReviewQueue",component: ReviewQueue,parameters: { layout: "padded" },+ args: { documents: documentsFor("enterprise"), loading: false },decorators: [(S) => (- <div style={{ maxWidth: "78rem" }}>+ <div style={{ maxWidth: "80rem" }}><S /></div>),@@ -18,38 +19,12 @@ const meta: Meta<typeof ReviewQueue> = {export default meta;type Story = StoryObj<typeof ReviewQueue>;-/** Live queue served by the default MSW handler (drives off the toolbar tier). */export const Default: Story = {};export const Loading: Story = {- parameters: {- msw: {- handlers: [- http.get("/v1/documents", async () => {- await delay("infinite");- return HttpResponse.json({ summary: {}, documents: [] });- }),- ],- },- },+ args: { documents: [], loading: true },};export const Empty: Story = {- parameters: {- msw: {- handlers: [- http.get("/v1/documents", () =>- HttpResponse.json({- summary: {- totalInQueue: 0,- needsReview: 0,- avgConfidence: 0,- processedToday: 0,- },- documents: [],- }),- ),- ],- },- },+ args: { documents: [], loading: false },};diff --git a/frontend/editor/src/portal/components/documents/ReviewQueue.tsx b/frontend/editor/src/portal/components/documents/ReviewQueue.tsxindex 6eab89e9eb..b4423fbe5c 100644--- a/frontend/editor/src/portal/components/documents/ReviewQueue.tsx+++ b/frontend/editor/src/portal/components/documents/ReviewQueue.tsx@@ -1,57 +1,68 @@import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";-import { EmptyState, Skeleton, Tabs, type TabItem } from "@app/ui";-import { useTier } from "@portal/contexts/TierContext";-import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";-import {- fetchDocuments,- type DocumentStatus,- type DocumentsResponse,- type ReviewDocument,-} from "@portal/api/documents";-import { DocumentsSummaryStrip } from "@portal/components/documents/DocumentsSummaryStrip";+import { EmptyState, Input, Skeleton, Tabs, type TabItem } from "@app/ui";+import type { DocumentStatus, ReviewDocument } from "@portal/api/documents";import { ReviewQueueTable } from "@portal/components/documents/ReviewQueueTable";import { DocumentDrawer } from "@portal/components/documents/DocumentDrawer";-type QueueFilter = "all" | "needs-review" | "processed" | "archived";+type QueueFilter = "all" | "flagged" | "processed" | "in-review";/** Which document statuses each filter pill admits. */const FILTER_STATUSES: Record<QueueFilter, DocumentStatus[] | null> = {all: null,- // "Needs review" surfaces both routed-for-review and flagged docs — the two- // states that demand a human decision.- "needs-review": ["needs-review", "flagged"],+ flagged: ["flagged"],processed: ["processed"],- archived: ["archived"],+ "in-review": ["in-review"],};-function countFor(docs: ReviewDocument[], filter: QueueFilter): number {- const statuses = FILTER_STATUSES[filter];- if (statuses === null) return docs.length;- return docs.filter((d) => statuses.includes(d.status)).length;+interface ReviewQueueProps {+ documents: ReviewDocument[];+ loading: boolean;+}++function SearchIcon() {+ return (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden>+ <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2" />+ <path+ d="m20 20-3.5-3.5"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ />+ </svg>+ );}/**- * The review/approval queue: KPI strip, status filter pills, the document- * stream table, and a detail drawer. The primary Documents surface.+ * The processing list: status filter pills, a filename search, the document+ * table, and a detail drawer. The primary Documents surface.*/-export function ReviewQueue() {+export function ReviewQueue({ documents, loading }: ReviewQueueProps) {const { t } = useTranslation();- const { tier } = useTier();- const state = useAsync<DocumentsResponse>(() => fetchDocuments(tier), [tier]);- const { data, loading } = state;- const { isLoading, isEmpty } = useSectionFlags(state);-const [filter, setFilter] = useState<QueueFilter>("all");+ const [query, setQuery] = useState("");const [selectedId, setSelectedId] = useState<string | null>(null);- const documents = useMemo(() => data?.documents ?? [], [data]);+ const searched = useMemo(() => {+ const q = query.trim().toLowerCase();+ if (!q) return documents;+ return documents.filter(+ (d) => d.name.toLowerCase().includes(q) || d.id.toLowerCase().includes(q),+ );+ }, [documents, query]);const rows = useMemo(() => {const statuses = FILTER_STATUSES[filter];- if (statuses === null) return documents;- return documents.filter((d) => statuses.includes(d.status));- }, [documents, filter]);+ if (statuses === null) return searched;+ return searched.filter((d) => statuses.includes(d.status));+ }, [searched, filter]);++ const countFor = (f: QueueFilter): number => {+ const statuses = FILTER_STATUSES[f];+ if (statuses === null) return documents.length;+ return documents.filter((d) => statuses.includes(d.status)).length;+ };const selected = documents.find((d) => d.id === selectedId) ?? null;@@ -59,39 +70,48 @@ export function ReviewQueue() {{key: "all",label: t("portal.documents.filters.all"),- count: countFor(documents, "all"),+ count: countFor("all"),},{- key: "needs-review",- label: t("portal.documents.filters.needsReview"),- count: countFor(documents, "needs-review"),+ key: "flagged",+ label: t("portal.documents.filters.flagged"),+ count: countFor("flagged"),},{key: "processed",label: t("portal.documents.filters.processed"),- count: countFor(documents, "processed"),+ count: countFor("processed"),},{- key: "archived",- label: t("portal.documents.filters.archived"),- count: countFor(documents, "archived"),+ key: "in-review",+ label: t("portal.documents.filters.inReview"),+ count: countFor("in-review"),},];+ const isLoading = loading && documents.length === 0;+ const isEmpty = !loading && documents.length === 0;+return (<div className="portal-documents__queue">- <DocumentsSummaryStrip- summary={data?.summary ?? null}- loading={loading}- />-- <Tabs<QueueFilter>- items={filterItems}- activeKey={filter}- onChange={setFilter}- variant="pill"- ariaLabel={t("portal.documents.filters.ariaLabel")}- />+ <div className="portal-documents__toolbar">+ <Tabs<QueueFilter>+ items={filterItems}+ activeKey={filter}+ onChange={setFilter}+ variant="pill"+ ariaLabel={t("portal.documents.filters.ariaLabel")}+ />+ <Input+ className="portal-documents__search"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder={t("portal.documents.search")}+ aria-label={t("portal.documents.search")}+ leadingIcon={<SearchIcon />}+ inputSize="sm"+ />+ </div>{isLoading && (<div className="portal-documents__table-skeleton" aria-hidden>diff --git a/frontend/editor/src/portal/components/documents/ReviewQueueTable.stories.tsx b/frontend/editor/src/portal/components/documents/ReviewQueueTable.stories.tsxindex bf0f6bb640..1ebdd430aa 100644--- a/frontend/editor/src/portal/components/documents/ReviewQueueTable.stories.tsx+++ b/frontend/editor/src/portal/components/documents/ReviewQueueTable.stories.tsx@@ -12,7 +12,7 @@ const meta: Meta<typeof ReviewQueueTable> = {args: { documents: DOCS, onRowClick: () => {} },decorators: [(S) => (- <div style={{ maxWidth: "78rem" }}>+ <div style={{ maxWidth: "80rem" }}><S /></div>),@@ -23,12 +23,10 @@ type Story = StoryObj<typeof ReviewQueueTable>;export const Default: Story = {};-/** Only the rows demanding a decision. */+/** Only the rows that need a human decision. */export const NeedsReview: Story = {args: {- documents: DOCS.filter(- (d) => d.status === "needs-review" || d.status === "flagged",- ),+ documents: DOCS.filter((d) => d.status === "flagged"),},};diff --git a/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsx b/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsxindex 88835344e8..cda3d20ca2 100644--- a/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsx+++ b/frontend/editor/src/portal/components/documents/ReviewQueueTable.tsx@@ -1,22 +1,50 @@import { useMemo } from "react";import { useTranslation } from "react-i18next";-import { ProgressBar, StatusBadge, Table, type TableColumn } from "@app/ui";+import { Button, Chip, StatusBadge, Table, type TableColumn } from "@app/ui";import {+ classificationTone,DOCUMENT_STATUS_LABEL,DOCUMENT_STATUS_TONE,+ PRODUCT_CHIP_TONE,type ReviewDocument,} from "@portal/api/documents";-import {- confidencePct,- confidenceTone,-} from "@portal/components/documents/format";interface ReviewQueueTableProps {documents: ReviewDocument[];onRowClick: (doc: ReviewDocument) => void;}-/** The document stream — one row per document awaiting a review decision. */+function BoltIcon() {+ return (+ <svg+ width="10"+ height="10"+ viewBox="0 0 24 24"+ fill="currentColor"+ aria-hidden+ >+ <path d="M13 2 4 14h6l-1 8 9-12h-6l1-8z" />+ </svg>+ );+}++function KebabIcon() {+ return (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="currentColor"+ aria-hidden+ >+ <circle cx="12" cy="5" r="1.6" />+ <circle cx="12" cy="12" r="1.6" />+ <circle cx="12" cy="19" r="1.6" />+ </svg>+ );+}++/** The document stream - one row per document your org has processed. */export function ReviewQueueTable({documents,onRowClick,@@ -25,79 +53,106 @@ export function ReviewQueueTable({const columns = useMemo<TableColumn<ReviewDocument>[]>(() => [{- key: "name",- header: t("portal.documents.table.columns.name"),+ key: "document",+ header: t("portal.documents.table.columns.document"),render: (d) => (- <div className="portal-documents__name-cell">- <span className="portal-documents__name">{d.name}</span>- {d.sensitive && (- <span- className="portal-documents__lock"- title={t("portal.documents.table.sensitiveTitle")}- aria-label={t("portal.documents.table.sensitiveLabel")}- >- 🔒- </span>- )}+ <div className="portal-documents__doc-cell">+ <div className="portal-documents__doc-head">+ <span className="portal-documents__name">{d.name}</span>+ {d.classification && (+ <Chip accent={classificationTone(d)} size="sm">+ {d.classification}+ </Chip>+ )}+ {d.auto && (+ <Chip accent="success" size="sm" leadingIcon={<BoltIcon />}>+ {t("portal.documents.table.auto")}+ </Chip>+ )}+ {d.sensitive && (+ <span+ className="portal-documents__lock"+ title={t("portal.documents.table.sensitiveTitle")}+ aria-label={t("portal.documents.table.sensitiveLabel")}+ >+ 🔒+ </span>+ )}+ </div>+ {d.note && <span className="portal-documents__note">{d.note}</span>}</div>),},{- key: "type",- header: t("portal.documents.table.columns.type"),- render: (d) => d.type,- },- {- key: "status",- header: t("portal.documents.table.columns.status"),+ key: "product",+ header: t("portal.documents.table.columns.product"),+ width: "7rem",render: (d) => (- <StatusBadge tone={DOCUMENT_STATUS_TONE[d.status]} size="sm">- {DOCUMENT_STATUS_LABEL[d.status]}- </StatusBadge>+ <Chip accent={PRODUCT_CHIP_TONE[d.product]} size="sm" showDot={false}>+ {d.product}+ </Chip>),},{- key: "source",- header: t("portal.documents.table.columns.source"),- render: (d) => (- <span className="portal-documents__muted">{d.source}</span>- ),+ key: "action",+ header: t("portal.documents.table.columns.action"),+ width: "12rem",+ render: (d) =>+ d.product === "Editor" || !d.action ? (+ <span className="portal-documents__editor-action">+ {t("portal.documents.table.editorAction")}+ </span>+ ) : (+ <span className="portal-documents__action">{d.action}</span>+ ),},{- key: "confidence",- header: t("portal.documents.table.columns.confidence"),- width: "9rem",+ key: "user",+ header: t("portal.documents.table.columns.user"),+ width: "8rem",render: (d) => (- <div className="portal-documents__confidence">- <ProgressBar value={d.confidence} height={6} />- <span- className={`portal-documents__confidence-pct portal-documents__confidence-pct--${confidenceTone(- d.confidence,- )}`}- >- {confidencePct(d.confidence)}- </span>- </div>+ <span className="portal-documents__muted">{d.user || "-"}</span>),},{- key: "fields",- header: t("portal.documents.table.columns.fields"),- align: "right",+ key: "status",+ header: t("portal.documents.table.columns.status"),+ width: "10rem",render: (d) => (- <span className="portal-documents__mono">{d.fieldsExtracted}</span>+ <StatusBadge tone={DOCUMENT_STATUS_TONE[d.status]} size="sm">+ {DOCUMENT_STATUS_LABEL[d.status]}+ {d.status === "in-review" && d.reviewer ? ` · ${d.reviewer}` : ""}+ </StatusBadge>),},{key: "time",header: t("portal.documents.table.columns.time"),- align: "right",+ width: "7rem",render: (d) => (<span className="portal-documents__muted">{d.time}</span>),},+ {+ key: "actions",+ header: "",+ width: "3rem",+ render: (d) => (+ <Button+ variant="quiet"+ size="sm"+ shape="circle"+ leftSection={<KebabIcon />}+ aria-label={t("portal.documents.table.rowActions")}+ onClick={(e) => {+ e.stopPropagation();+ onRowClick(d);+ }}+ />+ ),+ },],- [t],+ [t, onRowClick],);return (diff --git a/frontend/editor/src/portal/components/documents/format.ts b/frontend/editor/src/portal/components/documents/format.tsindex e2d4899818..879a23ef75 100644--- a/frontend/editor/src/portal/components/documents/format.ts+++ b/frontend/editor/src/portal/components/documents/format.ts@@ -1,16 +1,17 @@import type { StatusTone } from "@app/ui";-/** Format a 0–1 confidence fraction as a whole-percent string. */-export function confidencePct(n: number): string {+/**+ * Format a 0–1 confidence fraction as a whole-percent string. `null`/`undefined`+ * (no extraction data) renders as an em-free dash.+ */+export function confidencePct(n: number | null | undefined): string {+ if (n == null) return "-";return `${Math.round(n * 100)}%`;}-/**- * Tone for a confidence value. The bands match the review thresholds: below- * 60% is unreliable (danger), 60–85% warrants a glance (warning), above is- * trusted (success).- */-export function confidenceTone(n: number): StatusTone {+/** Tone for a confidence value: <60% danger, 60-85% warning, above success, none neutral. */+export function confidenceTone(n: number | null | undefined): StatusTone {+ if (n == null) return "neutral";if (n < 0.6) return "danger";if (n < 0.85) return "warning";return "success";diff --git a/frontend/editor/src/portal/components/infrastructure/AuditExportModal.stories.tsx b/frontend/editor/src/portal/components/infrastructure/AuditExportModal.stories.tsxnew file mode 100644index 0000000000..dc12295a32--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/AuditExportModal.stories.tsx@@ -0,0 +1,37 @@+import type { Meta, StoryObj } from "@storybook/react-vite";+import { http, HttpResponse } from "msw";+import { AuditExportModal } from "@portal/components/infrastructure/AuditExportModal";+import "@portal/views/Infrastructure.css";++/**+ * Export modal for the Infrastructure → Audit tab. Rendered always-open here.+ * Downloads via the editor's real `/audit-export` endpoint (mocked by MSW), so+ * clicking "Export" pulls a sample CSV/JSON.+ */+const meta: Meta<typeof AuditExportModal> = {+ title: "Portal/Infrastructure/AuditExportModal",+ component: AuditExportModal,+ parameters: { layout: "fullscreen" },+ args: { open: true, onClose: () => {} },+};+export default meta;+type Story = StoryObj<typeof AuditExportModal>;++export const Open: Story = {};++/**+ * The export request fails - click "Export" to see the inline error message.+ * (Overrides the sample-export handler with a 500.)+ */+export const ExportFails: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get(+ "*/api/v1/proprietary/ui-data/audit-export",+ () => new HttpResponse(null, { status: 500 }),+ ),+ ],+ },+ },+};diff --git a/frontend/editor/src/portal/components/infrastructure/AuditExportModal.tsx b/frontend/editor/src/portal/components/infrastructure/AuditExportModal.tsxnew file mode 100644index 0000000000..5b147ed90f--- /dev/null+++ b/frontend/editor/src/portal/components/infrastructure/AuditExportModal.tsx@@ -0,0 +1,139 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { Button, Checkbox, Modal, RadioGroup } from "@app/ui";+import { exportAuditLog } from "@portal/api/infrastructure";++interface AuditExportModalProps {+ open: boolean;+ onClose: () => void;+}++type ExportFormat = "csv" | "json";++/** Columns offered for export - mirrors the editor's audit export section. */+const FIELD_KEYS = [+ "date",+ "username",+ "ipaddress",+ "tool",+ "documentName",+ "outcome",+] as const;+type FieldKey = (typeof FIELD_KEYS)[number];++const DEFAULT_FIELDS: Record<FieldKey, boolean> = {+ date: true,+ username: true,+ ipaddress: false,+ tool: true,+ documentName: true,+ outcome: true,+};++/** Export the audit log to CSV/JSON via the admin-only, whole-server endpoint. */+export function AuditExportModal({ open, onClose }: AuditExportModalProps) {+ const { t } = useTranslation();+ const [format, setFormat] = useState<ExportFormat>("csv");+ const [fields, setFields] =+ useState<Record<FieldKey, boolean>>(DEFAULT_FIELDS);+ const [exporting, setExporting] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const anyField = FIELD_KEYS.some((k) => fields[k]);++ async function handleExport() {+ setError(null);+ setExporting(true);+ try {+ const fieldsParam = FIELD_KEYS.filter((k) => fields[k]).join(",");+ const blob = await exportAuditLog(format, fieldsParam);+ const url = window.URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = `audit-export-${new Date().toISOString()}.${format}`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ window.URL.revokeObjectURL(url);+ onClose();+ } catch {+ setError(t("portal.infrastructure.audit.export.error"));+ } finally {+ setExporting(false);+ }+ }++ const fieldLabel: Record<FieldKey, string> = {+ date: t("portal.infrastructure.audit.export.fields.date"),+ username: t("portal.infrastructure.audit.export.fields.username"),+ ipaddress: t("portal.infrastructure.audit.export.fields.ipAddress"),+ tool: t("portal.infrastructure.audit.export.fields.tool"),+ documentName: t("portal.infrastructure.audit.export.fields.documentName"),+ outcome: t("portal.infrastructure.audit.export.fields.outcome"),+ };++ return (+ <Modal+ open={open}+ onClose={onClose}+ title={t("portal.infrastructure.audit.export.title")}+ subtitle={t("portal.infrastructure.audit.export.subtitle")}+ footer={+ <div className="portal-infra__export-actions">+ <Button variant="tertiary" onClick={onClose} disabled={exporting}>+ {t("portal.infrastructure.audit.export.cancel")}+ </Button>+ <Button+ variant="primary"+ onClick={handleExport}+ disabled={exporting || !anyField}+ >+ {exporting+ ? t("portal.infrastructure.audit.export.exporting")+ : t("portal.infrastructure.audit.export.exportButton")}+ </Button>+ </div>+ }+ >+ <div className="portal-infra__export">+ <div className="portal-infra__export-group">+ <span className="portal-infra__export-label">+ {t("portal.infrastructure.audit.export.format")}+ </span>+ <RadioGroup<ExportFormat>+ name="audit-export-format"+ value={format}+ onChange={setFormat}+ direction="horizontal"+ options={[+ { value: "csv", label: "CSV" },+ { value: "json", label: "JSON" },+ ]}+ />+ </div>++ <div className="portal-infra__export-group">+ <span className="portal-infra__export-label">+ {t("portal.infrastructure.audit.export.fieldsLegend")}+ </span>+ <div className="portal-infra__export-fields">+ {FIELD_KEYS.map((k) => (+ <Checkbox+ key={k}+ label={fieldLabel[k]}+ checked={fields[k]}+ onChange={(e) => {+ // Capture synchronously; React nulls currentTarget before the state update.+ const checked = e.target.checked;+ setFields((prev) => ({ ...prev, [k]: checked }));+ }}+ />+ ))}+ </div>+ </div>++ {error && <p className="portal-infra__export-error">{error}</p>}+ </div>+ </Modal>+ );+}diff --git a/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsx b/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsxindex d4aefcd197..3bb2d6dc3c 100644--- a/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsx+++ b/frontend/editor/src/portal/components/infrastructure/AuditTab.stories.tsx@@ -24,10 +24,13 @@ export const Loading: Story = {parameters: {msw: {handlers: [- http.get("/v1/infrastructure/audit-log", async () => {- await delay("infinite");- return HttpResponse.json({ summary: {}, events: [] });- }),+ http.get(+ "*/api/v1/proprietary/ui-data/infrastructure/audit-log",+ async () => {+ await delay("infinite");+ return HttpResponse.json({ summary: {}, events: [] });+ },+ ),],},},@@ -37,10 +40,84 @@ export const Empty: Story = {parameters: {msw: {handlers: [- http.get("/v1/infrastructure/audit-log", () =>+ http.get("*/api/v1/proprietary/ui-data/infrastructure/audit-log", () =>HttpResponse.json({summary: { totalEvents: 0, processing: 0, elevation: 0, config: 0 },events: [],+ fullServer: true,+ }),+ ),+ ],+ },+ },+};++// A team member who isn't a lead (or any caller the backend scopes out) gets a+// 403 - the tab shows the access message, not the "no events" empty state.+export const NonLeadForbidden: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("*/api/v1/proprietary/ui-data/infrastructure/audit-log", () =>+ HttpResponse.json({ detail: "Not permitted" }, { status: 403 }),+ ),+ ],+ },+ },+};++// A team leader sees only their own team's events - a narrower slice than the+// admin whole-server view (the Default story). fullServer:false, so no Export.+export const TeamLeadScoped: Story = {+ parameters: {+ msw: {+ handlers: [+ http.get("*/api/v1/proprietary/ui-data/infrastructure/audit-log", () =>+ HttpResponse.json({+ summary: { totalEvents: 4, processing: 2, elevation: 0, config: 1 },+ events: [+ {+ id: "9102",+ timestamp: "2026-07-07 18:12:03",+ category: "processing",+ action: "Compress PDF",+ actor: "[email protected]",+ target: "acme-invoice-8841.pdf",+ status: "success",+ latencyMs: 842,+ },+ {+ id: "9101",+ timestamp: "2026-07-07 17:44:20",+ category: "auth",+ action: "User signed in",+ actor: "[email protected]",+ target: "Web session",+ status: "success",+ latencyMs: 128,+ },+ {+ id: "9100",+ timestamp: "2026-07-07 17:05:58",+ category: "config",+ action: "Profile settings updated",+ actor: "[email protected]",+ target: "/api/v1/user/change-settings",+ status: "info",+ latencyMs: 175,+ },+ {+ id: "9099",+ timestamp: "2026-07-07 16:31:11",+ category: "processing",+ action: "Merge PDFs",+ actor: "[email protected]",+ target: "onboarding-packet.pdf",+ status: "success",+ latencyMs: 2199,+ },+ ],+ fullServer: false,}),),],diff --git a/frontend/editor/src/portal/components/infrastructure/AuditTab.tsx b/frontend/editor/src/portal/components/infrastructure/AuditTab.tsxindex 6420950458..0b0d806c59 100644--- a/frontend/editor/src/portal/components/infrastructure/AuditTab.tsx+++ b/frontend/editor/src/portal/components/infrastructure/AuditTab.tsx@@ -1,6 +1,7 @@import { useMemo, useState } from "react";import { useTranslation } from "react-i18next";import {+ Button,Card,EmptyState,MetricCard,@@ -12,19 +13,21 @@ import {} from "@app/ui";import { useTier } from "@portal/contexts/TierContext";import { useAsync, useSectionFlags } from "@portal/hooks/useAsync";+import { HttpError } from "@portal/api/http";import {fetchAuditLog,type AuditCategory,type AuditEvent,type AuditLogResponse,} from "@portal/api/infrastructure";+import { AuditExportModal } from "@portal/components/infrastructure/AuditExportModal";import { SectionHeader } from "@portal/components/infrastructure/SectionHeader";import { TableSkeleton } from "@portal/components/infrastructure/TableSkeleton";import {AUDIT_CAT_LABEL,AUDIT_CAT_TONE,+ AUDIT_STATUS_LABEL,AUDIT_TONE,- titleCase,} from "@portal/components/infrastructure/infraFormat";type AuditFilter = "all" | AuditCategory;@@ -33,6 +36,7 @@ export function AuditTab() {const { t } = useTranslation();const { tier } = useTier();const [filter, setFilter] = useState<AuditFilter>("all");+ const [exportOpen, setExportOpen] = useState(false);const auditFilters: TabItem<AuditFilter>[] = [{ key: "all", label: t("portal.infrastructure.audit.filters.all") },@@ -85,7 +89,7 @@ export function AuditTab() {header: t("portal.infrastructure.audit.columns.status"),render: (e) => (<StatusBadge tone={AUDIT_TONE[e.status]} size="sm">- {titleCase(e.status)}+ {AUDIT_STATUS_LABEL[e.status]}</StatusBadge>),},@@ -104,8 +108,10 @@ export function AuditTab() {];const state = useAsync<AuditLogResponse>(() => fetchAuditLog(tier), [tier]);- const { data } = state;+ const { data, error } = state;const { isLoading, isEmpty } = useSectionFlags(state);+ // Backend returns 403 for scoped-out callers; show an access message, not an empty state.+ const forbidden = error instanceof HttpError && error.status === 403;const rows = useMemo(() => {if (!data) return [];@@ -115,9 +121,22 @@ export function AuditTab() {return (<div className="portal-infra__stack">- <SectionHeader- title={t("portal.infrastructure.audit.heading")}- sub={t("portal.infrastructure.audit.subheading")}+ <div className="portal-infra__audit-head">+ <SectionHeader+ title={t("portal.infrastructure.audit.heading")}+ sub={t("portal.infrastructure.audit.subheading")}+ />+ {/* Export is admin-only + whole-server, so only shown in the full-server view. */}+ {data?.fullServer && (+ <Button variant="secondary" onClick={() => setExportOpen(true)}>+ {t("portal.infrastructure.audit.export.open")}+ </Button>+ )}+ </div>++ <AuditExportModal+ open={exportOpen}+ onClose={() => setExportOpen(false)}/>{data && (@@ -141,17 +160,26 @@ export function AuditTab() {</section>)}- <Tabs<AuditFilter>- items={auditFilters}- activeKey={filter}- onChange={setFilter}- variant="pill"- ariaLabel={t("portal.infrastructure.audit.filterAriaLabel")}- />+ {!forbidden && (+ <Tabs<AuditFilter>+ items={auditFilters}+ activeKey={filter}+ onChange={setFilter}+ variant="pill"+ ariaLabel={t("portal.infrastructure.audit.filterAriaLabel")}+ />+ )}<Card padding="none">{isLoading && <TableSkeleton rows={6} cols={6} />}- {isEmpty && (+ {!isLoading && forbidden && (+ <EmptyState+ size="compact"+ title={t("portal.infrastructure.audit.forbidden.title")}+ description={t("portal.infrastructure.audit.forbidden.description")}+ />+ )}+ {!isLoading && !forbidden && isEmpty && (<EmptyStatesize="compact"title={t("portal.infrastructure.audit.empty.title")}diff --git a/frontend/editor/src/portal/components/infrastructure/infraFormat.ts b/frontend/editor/src/portal/components/infrastructure/infraFormat.tsindex 2cf7c2e028..df3f993360 100644--- a/frontend/editor/src/portal/components/infrastructure/infraFormat.ts+++ b/frontend/editor/src/portal/components/infrastructure/infraFormat.ts@@ -100,6 +100,14 @@ export const AUDIT_TONE: Record<AuditStatus, StatusTone> = {info: "info",};+// Human labels for the status badge: danger/warning are tones, not outcomes (read "Error").+export const AUDIT_STATUS_LABEL: Record<AuditStatus, string> = {+ success: "Success",+ warning: "Warning",+ danger: "Error",+ info: "Info",+};+export const AUDIT_CAT_LABEL: Record<AuditCategory, string> = {auth: "Auth",config: "Config",diff --git a/frontend/editor/src/portal/mocks/documents.ts b/frontend/editor/src/portal/mocks/documents.tsindex 218c812527..b4b7fe2325 100644--- a/frontend/editor/src/portal/mocks/documents.ts+++ b/frontend/editor/src/portal/mocks/documents.ts@@ -1,35 +1,31 @@/**- * Document review-queue fixtures and the types api/documents.ts shares with them.+ * Documents fixtures and the types api/documents.ts shares with them.*- * A "document" here is a single item flowing through the org's pipelines and- * waiting on a review/approval decision. Each carries its extracted fields, an- * audit timeline, and a `sensitive` flag that gates whether its content is- * shown directly or behind a zero-standing-access elevation request.- *- * api/documents.ts imports the types; the MSW handlers serve the fixture data- * over the intercepted apiClient.local.json() calls. Components never reach into this- * module directly. Once a real backend exists the handlers stop being- * registered and these fixtures can be deleted (or kept as test seeds).+ * A "document" is a file your org has processed, shown with its processing+ * record: which product ran it (API vs Editor), the pipeline/action, the user,+ * a classification chip (when auto-classified), the outcome, and when. Content+ * access is request-gated (the `sensitive` flag drives the drawer's elevation).+ * The real backend fills what it can from audit_events; the MSW handlers serve+ * these fixtures for the demo. Confidence scores aren't supported yet, so they+ * stay null and never surface in the table.*/import type { Tier } from "@portal/contexts/TierContext";-import type { StatusTone } from "@app/ui";+import type { ChipAccent, StatusTone } from "@app/ui";/* ──────────────────────────────────────────────────────────────────────── *//* Domain types *//* ──────────────────────────────────────────────────────────────────────── */-export type DocumentStatus =- | "processed"- | "flagged"- | "needs-review"- | "archived";+export type DocumentStatus = "processed" | "flagged" | "in-review" | "error";++/** Which Stirling product ran the operation. */+export type ProductType = "API" | "Editor";/** A single field pulled out of the document by extraction. */export interface Extraction {field: string;value: string;- /** Per-field confidence 0..1. */confidence: number;}@@ -46,7 +42,6 @@ export type DocAuditKind =export interface DocAuditEvent {id: string;kind: DocAuditKind;- /** Relative-time string, e.g. "2m ago". */time: string;actor: string;detail: string;@@ -55,33 +50,39 @@ export interface DocAuditEvent {export interface ReviewDocument {id: string;name: string;- /** Document type label, e.g. "Invoice", "Contract". */+ /** File-type label, e.g. "PDF". */type: string;+ /** Auto-classification label (e.g. "Contract"), or null when not classified. */+ classification: string | null;+ /** True when the classification was assigned automatically. */+ auto: boolean;+ /** Short descriptive sub-line (editor action or flag reason), or null. */+ note: string | null;+ /** Where it was processed. */+ product: ProductType;+ /** Pipeline/action, e.g. "contract". Null (or Editor product) renders "Editor". */+ action: string | null;+ /** The user who ran it. */+ user: string;status: DocumentStatus;+ /** Reviewer name for in-review docs, e.g. "Sarah K.". */+ reviewer: string | null;/** Originating source name. */source: string;- /** Overall extraction confidence 0..1. */- confidence: number;- /** Count of extracted fields (matches extractions.length). */+ /** Overall confidence 0..1, or null (unsupported - never shown in the table). */+ confidence: number | null;fieldsExtracted: number;- /** Relative-time string, e.g. "4m ago". */+ /** Relative-time string, e.g. "2 min ago". */time: string;- /**- * When true, content sits behind a zero-standing-access wall. The viewer- * sees a "Request access" affordance instead of the extractions until a- * timed elevation is granted.- */sensitive: boolean;extractions: Extraction[];audit: DocAuditEvent[];}export interface DocumentsSummary {- /** Total documents currently in the queue. */totalInQueue: number;- needsReview: number;- /** Mean extraction confidence across the queue, 0..1. */- avgConfidence: number;+ processed: number;+ errors: number;processedToday: number;}@@ -92,28 +93,39 @@ export interface DocumentsResponse {/* ──────────────────────────────────────────────────────────────────────── *//* Presentation metadata (label + chip tone) */-/* Lives client-side — product copy, not data. Re-exported via api/. *//* ──────────────────────────────────────────────────────────────────────── */export const DOCUMENT_STATUS_LABEL: Record<DocumentStatus, string> = {processed: "Processed",- flagged: "Flagged",- "needs-review": "Needs review",- archived: "Archived",+ flagged: "Needs Review",+ "in-review": "In Review",+ error: "Error",};export const DOCUMENT_STATUS_TONE: Record<DocumentStatus, StatusTone> = {processed: "success",- flagged: "danger",- "needs-review": "warning",- archived: "neutral",+ flagged: "warning",+ "in-review": "purple",+ error: "danger",};+export const PRODUCT_CHIP_TONE: Record<ProductType, ChipAccent> = {+ API: "brand",+ Editor: "success",+};++/** Classification chip accent: danger when unclassified, warning when it needs a look. */+export function classificationTone(doc: ReviewDocument): ChipAccent {+ if (doc.classification === "Unclassified") return "danger";+ if (doc.status === "processed") return "success";+ return "warning";+}+export const DOC_AUDIT_LABEL: Record<DocAuditKind, string> = {ingested: "Ingested",- extracted: "Extracted",- flagged: "Flagged",- reviewed: "Reviewed",+ extracted: "Processed",+ flagged: "Needs Review",+ reviewed: "In Review",approved: "Approved",archived: "Archived",elevation: "Elevation",@@ -121,436 +133,312 @@ export const DOC_AUDIT_LABEL: Record<DocAuditKind, string> = {export const DOC_AUDIT_TONE: Record<DocAuditKind, StatusTone> = {ingested: "info",- extracted: "info",- flagged: "danger",- reviewed: "warning",+ extracted: "success",+ flagged: "warning",+ reviewed: "purple",approved: "success",archived: "neutral",elevation: "purple",};/* ──────────────────────────────────────────────────────────────────────── */-/* Fixture builders */+/* Fixture builder *//* ──────────────────────────────────────────────────────────────────────── */-/**- * Pro-tier queue. A spread of statuses, types, sources, and confidences plus- * deliberate edge cases: a 100%-confidence clean processed doc, a flagged- * low-confidence outlier, and a doc with zero extracted fields.- */-const PRO_DOCS: ReviewDocument[] = [- {- id: "doc-inv-8841",- name: "ACME-INV-8841.pdf",- type: "Invoice",- status: "needs-review",- source: "[email protected]",- confidence: 0.82,- fieldsExtracted: 6,- time: "3m ago",- sensitive: false,- extractions: [- { field: "Vendor", value: "Globex Supplies Ltd", confidence: 0.98 },- { field: "Invoice no.", value: "INV-8841", confidence: 0.99 },- { field: "Invoice date", value: "2026-06-12", confidence: 0.94 },- { field: "Due date", value: "2026-07-12", confidence: 0.88 },- { field: "Total", value: "$12,480.00", confidence: 0.71 },- { field: "PO number", value: "PO-2231 (unverified)", confidence: 0.42 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "4m ago",- actor: "[email protected]",- detail: "Received via email inbox",- },- {- id: "a2",- kind: "extracted",- time: "4m ago",- actor: "Invoice Extractor",- detail: "6 fields extracted · 82% mean confidence",- },- {- id: "a3",- kind: "flagged",- time: "3m ago",- actor: "Invoice Extractor",- detail: "PO number below 50% confidence — routed to review",- },- ],- },- {- id: "doc-receipt-3320",- name: "expense-receipt-3320.jpg",- type: "Receipt",+type DocSeed = {+ id: string;+ name: string;+ product: ProductType;+ user: string;+ status: DocumentStatus;+ time: string;+ classification?: string;+ auto?: boolean;+ note?: string;+ action?: string;+ reviewer?: string;+ sensitive?: boolean;+ type?: string;+};++function mk(s: DocSeed): ReviewDocument {+ const source = s.product === "API" ? "API integration" : "Web upload";+ const resultKind: DocAuditKind =+ s.status === "flagged"+ ? "flagged"+ : s.status === "in-review"+ ? "reviewed"+ : "extracted";+ const audit: DocAuditEvent[] = [+ {+ id: `${s.id}-a1`,+ kind: "ingested",+ time: s.time,+ actor: s.user || "system",+ detail: `Received via ${source}`,+ },+ {+ id: `${s.id}-a2`,+ kind: resultKind,+ time: s.time,+ actor: s.user || "system",+ detail: s.note ?? (s.action ? `Ran ${s.action}` : "Processed"),+ },+ ];+ return {+ id: s.id,+ name: s.name,+ type: s.type ?? "PDF",+ classification: s.classification ?? null,+ auto: s.auto ?? false,+ note: s.note ?? null,+ product: s.product,+ action: s.action ?? null,+ user: s.user,+ status: s.status,+ reviewer: s.reviewer ?? null,+ source,+ confidence: null,+ fieldsExtracted: 0,+ time: s.time,+ sensitive: s.sensitive ?? false,+ extractions: [],+ audit,+ };+}++// Ordered newest-first; 15 processed, 4 needs-review, 1 in-review → "All 20".+const DOCS: ReviewDocument[] = [+ mk({+ id: "d1",+ name: "acme_services_agreement.pdf",+ classification: "Contract",+ auto: true,+ product: "API",+ action: "contract",+ user: "matt",status: "processed",- source: "Stirling Desktop — Reviewer pool",- confidence: 1.0,- fieldsExtracted: 4,- time: "11m ago",- sensitive: false,- extractions: [- { field: "Merchant", value: "Blue Bottle Coffee", confidence: 1.0 },- { field: "Date", value: "2026-06-15", confidence: 1.0 },- { field: "Amount", value: "$8.50", confidence: 1.0 },- { field: "Category", value: "Meals", confidence: 1.0 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "12m ago",- actor: "[email protected]",- detail: "Uploaded from desktop app",- },- {- id: "a2",- kind: "extracted",- time: "12m ago",- actor: "Invoice Extractor",- detail: "4 fields extracted · 100% mean confidence",- },- {- id: "a3",- kind: "approved",- time: "11m ago",- actor: "Invoice Extractor",- detail: "Auto-approved — all fields above threshold",- },- ],- },- {- id: "doc-contract-7712",- name: "MSA-Globex-2026.pdf",- type: "Contract",- status: "needs-review",- source: "SharePoint — Legal",- confidence: 0.76,- fieldsExtracted: 5,- // Sensitive: legal contract behind zero-standing-access. Content is hidden- // until a timed elevation is granted.- sensitive: true,- time: "27m ago",- extractions: [- { field: "Counterparty", value: "Globex Corporation", confidence: 0.95 },- { field: "Effective date", value: "2026-07-01", confidence: 0.9 },- { field: "Term", value: "36 months", confidence: 0.84 },- { field: "Auto-renewal", value: "Yes — 12 months", confidence: 0.61 },- { field: "Governing law", value: "Delaware", confidence: 0.49 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "31m ago",- actor: "SharePoint — Legal",- detail: "Synced from Contracts / Inbound",- },- {- id: "a2",- kind: "extracted",- time: "30m ago",- actor: "Contract Router",- detail: "5 fields extracted · 76% mean confidence",- },- {- id: "a3",- kind: "flagged",- time: "27m ago",- actor: "Contract Router",- detail: "Governing-law clause ambiguous — routed to legal review",- },- ],- },- {- id: "doc-claim-1190",- name: "claim-1190-intake.pdf",- type: "Claim",+ time: "2 min ago",+ }),+ mk({+ id: "d2",+ name: "quarterly_report_draft.pdf",+ note: "Merge + watermark removal",+ product: "Editor",+ user: "sarah.k",+ status: "processed",+ time: "3 min ago",+ }),+ mk({+ id: "d3",+ name: "flagged_contract.pdf",+ classification: "Contract",+ note: "Low confidence PII detection",+ product: "API",+ action: "contract",+ user: "matt",+ status: "flagged",+ time: "4 min ago",+ }),+ mk({+ id: "d4",+ name: "loan_disclosure_preview.pdf",+ classification: "Closing Disclosure",+ auto: true,+ product: "API",+ action: "closing disclosure",+ user: "",+ status: "processed",+ time: "5 min ago",+ }),+ mk({+ id: "d5",+ name: "patient_intake_form.pdf",+ classification: "Patient Intake",+ auto: true,+ product: "API",+ action: "patient intake",+ user: "matt",+ status: "processed",+ time: "6 min ago",+ }),+ mk({+ id: "d6",+ name: "invoice_batch_march.pdf",+ note: "Split into 12 pages + OCR",+ product: "Editor",+ user: "mike.r",+ status: "processed",+ time: "8 min ago",+ }),+ mk({+ id: "d7",+ name: "unknown_format.pdf",+ classification: "Unclassified",+ note: "Unrecognized format, needs manual classification",+ product: "API",+ action: "documents",+ user: "matt",status: "flagged",- source: "S3 — claims-intake",- confidence: 0.38,- fieldsExtracted: 3,- // Edge case: low-confidence outlier that failed to parse a scanned form.- sensitive: false,- time: "44m ago",- extractions: [- { field: "Claimant", value: "(illegible)", confidence: 0.21 },- { field: "Policy no.", value: "POL-44120", confidence: 0.66 },- { field: "Claim amount", value: "(not found)", confidence: 0.0 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "46m ago",- actor: "S3 — claims-intake",- detail: "Picked up from intake bucket",- },- {- id: "a2",- kind: "extracted",- time: "45m ago",- actor: "KYC Processor",- detail: "3 fields extracted · 38% mean confidence",- },- {- id: "a3",- kind: "flagged",- time: "44m ago",- actor: "KYC Processor",- detail: "Scan quality too low — manual re-key required",- },- ],- },- {- id: "doc-w9-0042",- name: "vendor-W9-globex.pdf",- type: "Tax form",+ time: "9 min ago",+ }),+ mk({+ id: "d8",+ name: "employee_w2_martinez.pdf",+ classification: "Tax Document",+ auto: true,+ product: "API",+ action: "tax document",+ user: "matt",status: "processed",- source: "Acme Production",- confidence: 0.93,- fieldsExtracted: 5,+ time: "11 min ago",+ }),+ mk({+ id: "d9",+ name: "nda_countersigned.pdf",+ classification: "Contract",+ auto: true,+ product: "API",+ action: "contract",+ user: "",+ status: "processed",+ time: "13 min ago",+ }),+ mk({+ id: "d10",+ name: "ambiguous_signature.pdf",+ classification: "Contract",+ note: "Signature verification failed",+ product: "API",+ action: "contract",+ user: "matt",+ status: "in-review",+ reviewer: "Sarah K.",+ time: "15 min ago",+ }),+ mk({+ id: "d11",+ name: "vendor_invoice_globex.pdf",+ classification: "Invoice",+ auto: true,+ product: "API",+ action: "invoice",+ user: "matt",+ status: "processed",+ time: "18 min ago",+ }),+ mk({+ id: "d12",+ name: "merged_appendix.pdf",+ note: "Merge + compress",+ product: "Editor",+ user: "sarah.k",+ status: "processed",+ time: "22 min ago",+ }),+ mk({+ id: "d13",+ name: "medical_record_scan.pdf",+ classification: "Patient Intake",+ auto: true,+ product: "API",+ action: "patient intake",+ user: "lisa.m",+ status: "processed",+ time: "25 min ago",sensitive: true,- time: "1h ago",- extractions: [- { field: "Legal name", value: "Globex Supplies Ltd", confidence: 0.97 },- { field: "TIN", value: "••-•••4821", confidence: 0.91 },- { field: "Entity type", value: "LLC", confidence: 0.95 },- {- field: "Address",- value: "44 Industrial Way, Springfield",- confidence: 0.9,- },- { field: "Signature", value: "Present", confidence: 0.92 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "1h ago",- actor: "Acme Production",- detail: "Uploaded via POST /v1/extract",- },- {- id: "a2",- kind: "extracted",- time: "1h ago",- actor: "KYC Processor",- detail: "5 fields extracted · 93% mean confidence",- },- {- id: "a3",- kind: "approved",- time: "58m ago",- actor: "[email protected]",- detail: "Reviewed and approved",- },- ],- },- {- id: "doc-po-6610",- name: "purchase-order-6610.pdf",- type: "Purchase order",- status: "archived",- source: "Nightly archive reprocess",- confidence: 0.88,- fieldsExtracted: 4,- sensitive: false,- time: "8h ago",- extractions: [- { field: "Supplier", value: "Initech", confidence: 0.92 },- { field: "PO number", value: "PO-6610", confidence: 0.99 },- { field: "Line items", value: "7", confidence: 0.85 },- { field: "Total", value: "$3,210.00", confidence: 0.78 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "8h ago",- actor: "Nightly archive reprocess",- detail: "Reprocessed from archive bucket",- },- {- id: "a2",- kind: "extracted",- time: "8h ago",- actor: "Invoice Extractor",- detail: "4 fields extracted · 88% mean confidence",- },- {- id: "a3",- kind: "archived",- time: "8h ago",- actor: "system",- detail: "Retention policy — archived after approval",- },- ],- },-];--/**- * Enterprise-only additions — deeper queue with more sensitive items so the- * zero-standing-access elevation flow has something to gate, plus richer- * audit trails.- */-const ENTERPRISE_EXTRA: ReviewDocument[] = [- {- id: "doc-kyc-5523",- name: "onboarding-passport-5523.pdf",- type: "KYC document",- status: "needs-review",- source: "S3 — claims-intake",- confidence: 0.79,- fieldsExtracted: 6,+ }),+ mk({+ id: "d14",+ name: "redacted_statement.pdf",+ note: "Redact PII + flatten",+ product: "Editor",+ user: "mike.r",+ status: "processed",+ time: "30 min ago",sensitive: true,- time: "9m ago",- extractions: [- { field: "Full name", value: "Maria L. Vance", confidence: 0.96 },- { field: "Document type", value: "Passport", confidence: 0.99 },- { field: "Document no.", value: "••••••742", confidence: 0.83 },- { field: "Date of birth", value: "1989-03-14", confidence: 0.88 },- { field: "Nationality", value: "United Kingdom", confidence: 0.94 },- { field: "Expiry", value: "2029-11-02", confidence: 0.55 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "10m ago",- actor: "S3 — claims-intake",- detail: "Picked up from intake bucket",- },- {- id: "a2",- kind: "extracted",- time: "10m ago",- actor: "KYC Processor",- detail: "6 fields extracted · 79% mean confidence",- },- {- id: "a3",- kind: "flagged",- time: "9m ago",- actor: "Compliance Sweep",- detail: "PII present — four-eyes review required before release",- },- ],- },- {- id: "doc-dpa-2207",- name: "DPA-globex-amendment.pdf",- type: "Contract",+ }),+ mk({+ id: "d15",+ name: "w4_form_chen.pdf",+ classification: "Tax Document",+ auto: true,+ product: "API",+ action: "tax document",+ user: "matt",+ status: "processed",+ time: "35 min ago",+ }),+ mk({+ id: "d16",+ name: "offer_letter_draft.pdf",+ classification: "Contract",+ note: "Missing signature block",+ product: "API",+ action: "contract",+ user: "john.d",status: "flagged",- source: "SharePoint — Legal",- confidence: 0.84,- fieldsExtracted: 5,- sensitive: true,- time: "1h ago",- extractions: [- { field: "Counterparty", value: "Globex Corporation", confidence: 0.95 },- { field: "Data categories", value: "PII, financial", confidence: 0.81 },- { field: "Sub-processors", value: "3 listed", confidence: 0.77 },- { field: "SCC version", value: "2021/914", confidence: 0.9 },- { field: "Breach window", value: "72 hours", confidence: 0.76 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "1h ago",- actor: "SharePoint — Legal",- detail: "Synced from Contracts / Inbound",- },- {- id: "a2",- kind: "extracted",- time: "1h ago",- actor: "Contract Router",- detail: "5 fields extracted · 84% mean confidence",- },- {- id: "a3",- kind: "flagged",- time: "1h ago",- actor: "Compliance Sweep",- detail: "Sub-processor list changed — escalated to DPO",- },- ],- },- {- id: "doc-coi-9001",- name: "certificate-of-insurance-9001.pdf",- type: "Compliance",+ time: "40 min ago",+ }),+ mk({+ id: "d17",+ name: "compressed_brochure.pdf",+ note: "Compress + convert to PDF",+ product: "Editor",+ user: "sarah.k",+ status: "processed",+ time: "48 min ago",+ }),+ mk({+ id: "d18",+ name: "blurry_receipt.pdf",+ classification: "Unclassified",+ note: "Image too low-res to classify",+ product: "API",+ action: "documents",+ user: "matt",+ status: "flagged",+ time: "52 min ago",+ }),+ mk({+ id: "d19",+ name: "signed_nda_partner.pdf",+ classification: "Contract",+ auto: true,+ product: "API",+ action: "contract",+ user: "",status: "processed",- source: "Compliance Sweep",- confidence: 0.96,- fieldsExtracted: 5,- sensitive: false,- time: "2h ago",- extractions: [- { field: "Insured", value: "Acme Corp", confidence: 0.98 },- { field: "Carrier", value: "Liberty Mutual", confidence: 0.97 },- { field: "Policy no.", value: "CGL-77120", confidence: 0.95 },- { field: "Coverage", value: "$2,000,000", confidence: 0.96 },- { field: "Expiry", value: "2027-01-31", confidence: 0.94 },- ],- audit: [- {- id: "a1",- kind: "ingested",- time: "2h ago",- actor: "Compliance Sweep",- detail: "Pulled for COI compliance check",- },- {- id: "a2",- kind: "extracted",- time: "2h ago",- actor: "Compliance Sweep",- detail: "5 fields extracted · 96% mean confidence",- },- {- id: "a3",- kind: "approved",- time: "2h ago",- actor: "[email protected]",- detail: "Coverage verified — approved",- },- ],- },+ time: "1 h ago",+ }),+ mk({+ id: "d20",+ name: "bank_statement_june.pdf",+ classification: "Closing Disclosure",+ auto: true,+ product: "API",+ action: "closing disclosure",+ user: "lisa.m",+ status: "processed",+ time: "1 h ago",+ sensitive: true,+ }),];-/** Documents for a given tier. Free is a slim queue; enterprise is the deepest. */+/** Documents for a given tier. Free is a slim queue; pro/enterprise get all. */export function documentsFor(tier: Tier): ReviewDocument[] {- if (tier === "free") {- // Free keeps a simple, non-sensitive queue — no elevation flow to exercise.- return PRO_DOCS.filter((d) => !d.sensitive).slice(0, 3);- }- if (tier === "enterprise") return [...ENTERPRISE_EXTRA, ...PRO_DOCS];- return PRO_DOCS;+ if (tier === "free") return DOCS.filter((d) => !d.sensitive).slice(0, 6);+ return DOCS;}-/** Summary strip derived from the tier's queue so the KPIs always reconcile. */export function summaryFor(tier: Tier): DocumentsSummary {const docs = documentsFor(tier);- const needsReview = docs.filter((d) => d.status === "needs-review").length;- const avgConfidence =- docs.length === 0- ? 0- : docs.reduce((sum, d) => sum + d.confidence, 0) / docs.length;- // "Processed today" approximates same-day throughput from the visible queue;- // a real backend would count against an actual calendar boundary.- const processedToday = docs.filter(- (d) => d.status === "processed" || d.status === "archived",- ).length;+ const processed = docs.filter((d) => d.status === "processed").length;return {totalInQueue: docs.length,- needsReview,- avgConfidence,- processedToday,+ processed,+ errors: docs.filter((d) => d.status === "error").length,+ processedToday: processed,};}diff --git a/frontend/editor/src/portal/mocks/handlers/documents.ts b/frontend/editor/src/portal/mocks/handlers/documents.tsindex 0f072aa1bd..dca9a0a6af 100644--- a/frontend/editor/src/portal/mocks/handlers/documents.ts+++ b/frontend/editor/src/portal/mocks/handlers/documents.ts@@ -3,7 +3,9 @@ import type { Tier } from "@portal/contexts/TierContext";import { buildDocumentsResponse } from "@portal/mocks/documents";export const documentsHandlers = [- http.get("/v1/documents", async ({ request }) => {+ // Wildcard prefix so it intercepts both apiClient.local (same-origin) and+ // apiClient.saas (absolute VITE_SAAS_API_URL) calls.+ http.get("*/api/v1/proprietary/ui-data/documents", async ({ request }) => {await delay(120);const url = new URL(request.url);const tier = (url.searchParams.get("tier") ?? "pro") as Tier;diff --git a/frontend/editor/src/portal/mocks/handlers/infrastructure.ts b/frontend/editor/src/portal/mocks/handlers/infrastructure.tsindex 3b3029cb2a..f885a39a1f 100644--- a/frontend/editor/src/portal/mocks/handlers/infrastructure.ts+++ b/frontend/editor/src/portal/mocks/handlers/infrastructure.ts@@ -45,8 +45,65 @@ export const infrastructureHandlers = [return HttpResponse.json(storageFor(tierFrom(request)));}),- http.get("/v1/infrastructure/audit-log", async ({ request }) => {- await delay(120);- return HttpResponse.json(auditLogFor(tierFrom(request)));+ // Mirrors the real backend route. Wildcard prefix so it intercepts both the+ // self-hosted apiClient.local call (same-origin) and the SaaS apiClient.saas+ // call (absolute VITE_SAAS_API_URL).+ http.get(+ "*/api/v1/proprietary/ui-data/infrastructure/audit-log",+ async ({ request }) => {+ await delay(120);+ return HttpResponse.json(auditLogFor(tierFrom(request)));+ },+ ),++ // Sample audit export so the export modal downloads something with mocks on.+ http.get("*/api/v1/proprietary/ui-data/audit-export", async ({ request }) => {+ await delay(200);+ const format = new URL(request.url).searchParams.get("format") ?? "csv";+ const rows = [+ {+ date: "2026-07-07 18:59:31",+ username: "[email protected]",+ ipaddress: "10.0.3.21",+ tool: "compress-pdf",+ documentName: "purchase-order-6610.pdf",+ outcome: "success",+ },+ {+ date: "2026-07-07 18:40:50",+ username: "[email protected]",+ ipaddress: "10.0.0.161",+ tool: "login",+ documentName: "",+ outcome: "success",+ },+ {+ date: "2026-07-07 15:25:06",+ username: "[email protected]",+ ipaddress: "10.0.1.4",+ tool: "add-password",+ documentName: "scan-batch-0142.pdf",+ outcome: "failure",+ },+ ];+ if (format === "json") {+ return HttpResponse.json(rows);+ }+ const header = "date,username,ipaddress,tool,documentName,outcome";+ const body = rows+ .map((r) =>+ [+ r.date,+ r.username,+ r.ipaddress,+ r.tool,+ r.documentName,+ r.outcome,+ ].join(","),+ )+ .join("\n");+ return new HttpResponse(`${header}\n${body}\n`, {+ headers: { "Content-Type": "text/csv" },+ });}),];diff --git a/frontend/editor/src/portal/mocks/infrastructure.ts b/frontend/editor/src/portal/mocks/infrastructure.tsindex 47c0c664ab..5b33e324fb 100644--- a/frontend/editor/src/portal/mocks/infrastructure.ts+++ b/frontend/editor/src/portal/mocks/infrastructure.ts@@ -655,126 +655,190 @@ export interface AuditEvent {latencyMs: number;}+// Mirrors what the real backend (PortalInfraAuditService) returns: audit_events+// mapped from real AuditEventType values to the tab's categories. Only real+// types appear - there is no audited "elevation" event, so that category is+// absent (its summary metric reads 0), matching the backend.const AUDIT_EVENTS_ALL: AuditEvent[] = [{- id: "a-1",- timestamp: "10:42:18",+ id: "8841",+ timestamp: "2026-07-07 18:59:31",category: "processing",- action: "Pipeline run completed",- actor: "ci-bot",- target: "COI Compliance",+ action: "Compress PDF",+ actor: "[email protected]",+ target: "acme-invoice-8841.pdf",status: "success",- latencyMs: 412,+ latencyMs: 842,},{- id: "a-2",- timestamp: "10:38:02",+ id: "8840",+ timestamp: "2026-07-07 18:40:50",category: "auth",- action: "API key authenticated",- actor: "sk_live_a3f8…",- target: "us-east-1 gateway",+ action: "User signed in",+ actor: "[email protected]",+ target: "Web session",status: "success",- latencyMs: 9,+ latencyMs: 128,},{- id: "a-3",- timestamp: "10:31:55",- category: "elevation",- action: "Admin role assumed",- actor: "maria.chen",- target: "Security settings",- status: "warning",- latencyMs: 21,+ id: "8839",+ timestamp: "2026-07-07 18:22:07",+ category: "security",+ action: "Add password",+ actor: "[email protected]",+ target: "MSA-Globex-2026.pdf",+ status: "success",+ latencyMs: 1203,},{- id: "a-4",- timestamp: "10:24:40",+ id: "8838",+ timestamp: "2026-07-07 17:58:44",category: "config",- action: "Retention policy changed",- actor: "devon.park",- target: "30d → 90d",+ action: "Admin settings changed",+ actor: "[email protected]",+ target: "/api/v1/admin/settings/update",status: "info",- latencyMs: 14,+ latencyMs: 210,},{- id: "a-5",- timestamp: "10:19:07",- category: "security",- action: "IP allowlist updated",- actor: "maria.chen",- target: "203.0.113.7/32",- status: "info",- latencyMs: 11,+ id: "8837",+ timestamp: "2026-07-07 17:31:12",+ category: "processing",+ action: "Merge PDFs",+ actor: "[email protected]",+ target: "onboarding-packet.pdf",+ status: "success",+ latencyMs: 2199,},{- id: "a-6",- timestamp: "10:12:33",+ id: "8836",+ timestamp: "2026-07-07 17:04:55",category: "auth",- action: "Failed key authentication",- actor: "sk_live_d901…",- target: "us-west-2 gateway",+ action: "Failed sign-in attempt",+ actor: "[email protected]",+ target: "Web session",status: "danger",- latencyMs: 6,+ latencyMs: 96,},{- id: "a-7",- timestamp: "10:04:51",+ id: "8835",+ timestamp: "2026-07-07 16:47:29",category: "processing",- action: "Redaction job queued",- actor: "ci-bot",- target: "Prior Auth batch",+ action: "OCR PDF",+ actor: "[email protected]",+ target: "scan-batch-0142.pdf",status: "success",- latencyMs: 188,+ latencyMs: 8421,},{- id: "a-8",- timestamp: "09:58:12",- category: "elevation",- action: "Key rotation requested",- actor: "devon.park",- target: "Ops · admin (legacy)",- status: "warning",- latencyMs: 33,+ id: "8834",+ timestamp: "2026-07-07 16:20:03",+ category: "security",+ action: "Add watermark",+ actor: "[email protected]",+ target: "policy-handbook.pdf",+ status: "success",+ latencyMs: 640,},{- id: "a-9",- timestamp: "09:51:44",- category: "security",- action: "Access policy set to HYOK",- actor: "maria.chen",- target: "Document encryption",+ id: "8833",+ timestamp: "2026-07-07 15:58:41",+ category: "config",+ action: "Profile settings updated",+ actor: "[email protected]",+ target: "/api/v1/user/change-settings",status: "info",- latencyMs: 27,+ latencyMs: 175,},{- id: "a-10",- timestamp: "09:43:20",- category: "config",- action: "Region added",- actor: "ci-bot",- target: "eu-west-1",+ id: "8832",+ timestamp: "2026-07-07 15:29:18",+ category: "processing",+ action: "Split pages",+ actor: "[email protected]",+ target: "statement-june.pdf",+ status: "success",+ latencyMs: 410,+ },+ {+ id: "8831",+ timestamp: "2026-07-07 15:02:37",+ category: "processing",+ action: "Compress PDF",+ actor: "[email protected]",+ target: "purchase-order-6610.pdf",+ status: "danger",+ latencyMs: 1203,+ },+ {+ id: "8830",+ timestamp: "2026-07-07 14:41:50",+ category: "security",+ action: "Remove password",+ actor: "[email protected]",+ target: "certificate-9001.pdf",status: "success",- latencyMs: 240,+ latencyMs: 980,},{- id: "a-11",- timestamp: "09:36:08",+ id: "8829",+ timestamp: "2026-07-07 14:15:22",category: "processing",- action: "Schema drift flagged",- actor: "extract-engine",- target: "Invoice v3",+ action: "PDF to Image",+ actor: "[email protected]",+ target: "contract-amendment.pdf",status: "warning",- latencyMs: 95,+ latencyMs: 1560,},{- id: "a-12",- timestamp: "09:28:55",+ id: "8828",+ timestamp: "2026-07-07 13:52:09",category: "auth",- action: "SSO session started",- actor: "devon.park",- target: "Okta · acme.com",+ action: "User signed out",+ actor: "[email protected]",+ target: "Web session",+ status: "success",+ latencyMs: 42,+ },+ {+ id: "8827",+ timestamp: "2026-07-07 13:30:44",+ category: "config",+ action: "Admin settings changed",+ actor: "[email protected]",+ target: "/api/v1/admin/team/update",+ status: "info",+ latencyMs: 320,+ },+ {+ id: "8826",+ timestamp: "2026-07-07 13:03:58",+ category: "processing",+ action: "Extract images",+ actor: "[email protected]",+ target: "expense-report-q2.pdf",+ status: "success",+ latencyMs: 2200,+ },+ {+ id: "8825",+ timestamp: "2026-07-07 12:38:11",+ category: "auth",+ action: "User signed in",+ actor: "[email protected]",+ target: "Web session",+ status: "success",+ latencyMs: 110,+ },+ {+ id: "8824",+ timestamp: "2026-07-07 12:11:47",+ category: "security",+ action: "Add watermark",+ actor: "[email protected]",+ target: "MSA-Globex-2026.pdf",status: "success",- latencyMs: 18,+ latencyMs: 705,},];@@ -788,6 +852,8 @@ export interface AuditSummary {export interface AuditLogResponse {summary: AuditSummary;events: AuditEvent[];+ /** True for the whole-server (admin) view; gates the admin-only CSV export. */+ fullServer: boolean;}/* ──────────────────────────────────────────────────────────────────────── */@@ -1039,20 +1105,19 @@ export function modelsResponseFor(tier: Tier): ModelsResponse {export function auditLogFor(tier: Tier): AuditLogResponse {const events =tier === "free"- ? AUDIT_EVENTS_ALL.slice(0, 5)+ ? AUDIT_EVENTS_ALL.slice(0, 6): tier === "pro"- ? AUDIT_EVENTS_ALL.slice(0, 9)+ ? AUDIT_EVENTS_ALL.slice(0, 12): AUDIT_EVENTS_ALL;- // Headline counts reflect a full 24h window, not just the visible slice —- // the table shows the most recent events, the metrics show the day's totals.- const scale = tier === "free" ? 1 : tier === "pro" ? 21 : 86;+ // Summary is derived from the returned events, exactly like the backend+ // (PortalInfraAuditService) computes it - so mocks and real data reconcile.const summary: AuditSummary = {- totalEvents: events.length * scale,- processing:- events.filter((e) => e.category === "processing").length * scale,- elevation: events.filter((e) => e.category === "elevation").length * scale,- config: events.filter((e) => e.category === "config").length * scale,+ totalEvents: events.length,+ processing: events.filter((e) => e.category === "processing").length,+ elevation: events.filter((e) => e.category === "elevation").length,+ config: events.filter((e) => e.category === "config").length,};- return { summary, events };+ // The mock represents the admin (whole-server) view, so export is offered.+ return { summary, events, fullServer: true };}diff --git a/frontend/editor/src/portal/views/Documents.css b/frontend/editor/src/portal/views/Documents.cssindex a655289567..13cbf33c3c 100644--- a/frontend/editor/src/portal/views/Documents.css+++ b/frontend/editor/src/portal/views/Documents.css@@ -9,6 +9,13 @@/* Header */.portal-documents__head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++.portal-documents__head-text {display: flex;flex-direction: column;gap: 0.25rem;@@ -36,25 +43,50 @@gap: 1.25rem;}+/* Toolbar: filter pills left, filename search right */+.portal-documents__toolbar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ flex-wrap: wrap;+}++.portal-documents__search {+ width: 18rem;+ max-width: 100%;+}+.portal-documents__table-skeleton {display: flex;flex-direction: column;gap: 0.5rem;}-/* Table cells */-.portal-documents__name-cell {+/* Document cell: name + chips + descriptive sub-line */+.portal-documents__doc-cell {+ display: flex;+ flex-direction: column;+ gap: 0.25rem;+ min-width: 0;+}++.portal-documents__doc-head {display: flex;align-items: center;- gap: 0.4375rem;+ gap: 0.5rem;+ flex-wrap: wrap;min-width: 0;}.portal-documents__name {font-weight: 600;color: var(--color-text-1);- overflow: hidden;- text-overflow: ellipsis;+}++.portal-documents__note {+ font-size: 0.8125rem;+ color: var(--color-text-4);}.portal-documents__lock {@@ -68,32 +100,15 @@color: var(--color-text-4);}-.portal-documents__mono {- font-family: var(--font-mono);+.portal-documents__action {font-size: 0.8125rem;color: var(--color-text-2);}-.portal-documents__confidence {- display: flex;- align-items: center;- gap: 0.5rem;-}--.portal-documents__confidence-pct {- font-family: var(--font-mono);- font-size: 0.75rem;- white-space: nowrap;-}--.portal-documents__confidence-pct--success {- color: var(--color-green-dark);-}-.portal-documents__confidence-pct--warning {- color: var(--color-amber-dark);-}-.portal-documents__confidence-pct--danger {- color: var(--color-red);+.portal-documents__editor-action {+ font-size: 0.8125rem;+ font-style: italic;+ color: var(--color-text-4);}/* Drawer body */diff --git a/frontend/editor/src/portal/views/Documents.tsx b/frontend/editor/src/portal/views/Documents.tsxindex e73b4960a1..b94102bd4f 100644--- a/frontend/editor/src/portal/views/Documents.tsx+++ b/frontend/editor/src/portal/views/Documents.tsx@@ -1,26 +1,107 @@import { useTranslation } from "react-i18next";+import { Button } from "@app/ui";+import { useTier } from "@portal/contexts/TierContext";+import { useAsync } from "@portal/hooks/useAsync";+import {+ fetchDocuments,+ DOCUMENT_STATUS_LABEL,+ type DocumentsResponse,+ type ReviewDocument,+} from "@portal/api/documents";import { ReviewQueue } from "@portal/components/documents/ReviewQueue";import "@portal/views/Documents.css";+function DownloadIcon() {+ return (+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden>+ <path+ d="M12 3v12m0 0 4-4m-4 4-4-4M5 21h14"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ </svg>+ );+}++function csvCell(value: string): string {+ return `"${value.replace(/"/g, '""')}"`;+}++/** Flatten the visible columns to CSV, matching the on-screen table. */+function toCsv(docs: ReviewDocument[]): string {+ const header = [+ "Document",+ "Product",+ "Pipeline / Action",+ "User",+ "Status",+ "Time",+ ];+ const lines = [header.map(csvCell).join(",")];+ for (const d of docs) {+ const action = d.product === "Editor" || !d.action ? "Editor" : d.action;+ const status =+ DOCUMENT_STATUS_LABEL[d.status] ++ (d.status === "in-review" && d.reviewer ? ` · ${d.reviewer}` : "");+ lines.push(+ [d.name, d.product, action, d.user || "", status, d.time]+ .map((v) => csvCell(String(v)))+ .join(","),+ );+ }+ return lines.join("\n");+}+/**- * Documents surface — the review/approval queue: documents flowing through the- * org's pipelines awaiting a decision, with filters, a detail drawer, and- * zero-standing-access elevation for sensitive files.+ * Documents surface - the processing record for every file the org has run,+ * with status filters, a filename search, a CSV export, and a detail drawer+ * (content is request-gated behind zero-standing-access for sensitive files).*/export function Documents() {const { t } = useTranslation();+ const { tier } = useTier();+ const state = useAsync<DocumentsResponse>(() => fetchDocuments(tier), [tier]);+ const documents = state.data?.documents ?? [];++ function exportCsv() {+ const blob = new Blob([toCsv(documents)], {+ type: "text/csv;charset=utf-8",+ });+ const url = URL.createObjectURL(blob);+ const link = document.createElement("a");+ link.href = url;+ link.download = "documents.csv";+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ URL.revokeObjectURL(url);+ }+return (<div className="portal-documents"><header className="portal-documents__head">- <h1 className="portal-documents__title">- {t("portal.documents.title")}- </h1>- <p className="portal-documents__sub">- {t("portal.documents.subtitle")}- </p>+ <div className="portal-documents__head-text">+ <h1 className="portal-documents__title">+ {t("portal.documents.title")}+ </h1>+ <p className="portal-documents__sub">+ {t("portal.documents.subtitle")}+ </p>+ </div>+ <Button+ variant="secondary"+ size="sm"+ leftSection={<DownloadIcon />}+ onClick={exportCsv}+ disabled={documents.length === 0}+ >+ {t("portal.documents.exportCsv")}+ </Button></header>- <ReviewQueue />+ <ReviewQueue documents={documents} loading={state.loading} /></div>);}diff --git a/frontend/editor/src/portal/views/Infrastructure.css b/frontend/editor/src/portal/views/Infrastructure.cssindex fd893694d3..f0a2f55da9 100644--- a/frontend/editor/src/portal/views/Infrastructure.css+++ b/frontend/editor/src/portal/views/Infrastructure.css@@ -71,6 +71,51 @@color: var(--color-text-4);}+/* Audit tab header row: section heading + Export action */+.portal-infra__audit-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 1rem;+}++/* Export modal body */+.portal-infra__export {+ display: flex;+ flex-direction: column;+ gap: 1.25rem;+}++.portal-infra__export-group {+ display: flex;+ flex-direction: column;+ gap: 0.5rem;+}++.portal-infra__export-label {+ font-size: 0.8125rem;+ font-weight: 600;+ color: var(--color-text-1);+}++.portal-infra__export-fields {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 0.5rem 1rem;+}++.portal-infra__export-error {+ margin: 0;+ font-size: 0.8125rem;+ color: var(--color-danger, #e5484d);+}++.portal-infra__export-actions {+ display: flex;+ justify-content: flex-end;+ gap: 0.75rem;+}+/* Two-column split */.portal-infra__split {display: grid;