Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
011ae4dd08 | ||
|
|
c4c06cfd7d | ||
|
|
c22ecc6c09 | ||
|
|
b38c849726 |
@@ -80,6 +80,10 @@ dependencies {
|
||||
implementation "software.amazon.awssdk:s3:${awsSdkVersion}"
|
||||
implementation "software.amazon.awssdk:url-connection-client:${awsSdkVersion}"
|
||||
|
||||
// @DataJpaTest slice (Boot 4 ships test slices as separate starters, like webmvc-test at the
|
||||
// root) so policy.source repositories can be exercised against embedded H2.
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-data-jpa-test'
|
||||
|
||||
// Testcontainers: real MinIO/LocalStack (S3) and Valkey for integration tests in CI without
|
||||
// manually-started instances. Tests skip cleanly when Docker is unavailable.
|
||||
testImplementation "org.testcontainers:testcontainers:${testcontainersMinioVersion}"
|
||||
|
||||
+11
-2
@@ -21,6 +21,7 @@ import stirling.software.proprietary.policy.model.PolicyRun;
|
||||
import stirling.software.proprietary.policy.model.PolicyRunStatus;
|
||||
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
|
||||
import stirling.software.proprietary.policy.source.Source;
|
||||
import stirling.software.proprietary.policy.source.SourceDocCounter;
|
||||
import stirling.software.proprietary.policy.source.SourceStore;
|
||||
|
||||
/**
|
||||
@@ -37,6 +38,7 @@ public class PolicyRunner {
|
||||
private final PolicyEngine policyEngine;
|
||||
private final List<InputSource> inputSources;
|
||||
private final SourceStore sourceStore;
|
||||
private final SourceDocCounter docCounter;
|
||||
|
||||
/**
|
||||
* Trigger entry point. Pulls every referenced source; each yielded unit becomes its own run so
|
||||
@@ -65,7 +67,7 @@ public class PolicyRunner {
|
||||
policy.id());
|
||||
continue;
|
||||
}
|
||||
runIds.addAll(pullAndRun(policy, source.toInputSpec()));
|
||||
runIds.addAll(pullAndRun(policy, sourceId, source.toInputSpec()));
|
||||
}
|
||||
return runIds;
|
||||
}
|
||||
@@ -82,7 +84,11 @@ public class PolicyRunner {
|
||||
return policyEngine.submit(definition, inputs, listener);
|
||||
}
|
||||
|
||||
private List<String> pullAndRun(Policy policy, InputSpec spec) {
|
||||
/**
|
||||
* Resolves the source and starts a run per unit; records how many documents the source fed and
|
||||
* returns the ids of the runs started.
|
||||
*/
|
||||
private List<String> pullAndRun(Policy policy, String sourceId, InputSpec spec) {
|
||||
InputSource source = sourceFor(spec);
|
||||
if (source == null) {
|
||||
log.warn(
|
||||
@@ -103,9 +109,12 @@ public class PolicyRunner {
|
||||
return List.of();
|
||||
}
|
||||
List<String> runIds = new ArrayList<>();
|
||||
long docsFed = 0;
|
||||
for (ResolvedInput unit : work) {
|
||||
runIds.add(startRun(policy, unit.inputs(), unit.onComplete()));
|
||||
docsFed += unit.inputs().primary().size();
|
||||
}
|
||||
docCounter.record(sourceId, docsFed);
|
||||
return runIds;
|
||||
}
|
||||
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
/**
|
||||
* Per-source document throughput for the overview row: how many documents a source has fed into
|
||||
* runs in total and over the trailing 24-hour and 30-day windows. Counts documents <em>fed</em>
|
||||
* (picked up by a run), so a snapshot-mode source that re-reads the same files each run counts them
|
||||
* per run.
|
||||
*/
|
||||
public record DocStats(long total, long last24h, long last30d) {
|
||||
|
||||
/** Number of trailing daily buckets in a source's daily series. */
|
||||
public static final int DAYS = 30;
|
||||
|
||||
public static final DocStats ZERO = new DocStats(0, 0, 0);
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* In-memory {@link SourceDocCounter} for tests and any future no-database mode. Holds hourly
|
||||
* buckets per source; the clock is injectable so window boundaries can be exercised
|
||||
* deterministically. {@link JpaSourceDocCounter} is the runtime bean.
|
||||
*/
|
||||
public class InProcessSourceDocCounter implements SourceDocCounter {
|
||||
|
||||
private final Supplier<Instant> clock;
|
||||
private final Map<String, Map<Long, Long>> bucketsBySource = new ConcurrentHashMap<>();
|
||||
|
||||
public InProcessSourceDocCounter() {
|
||||
this(Instant::now);
|
||||
}
|
||||
|
||||
public InProcessSourceDocCounter(Supplier<Instant> clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void record(String sourceId, long docs) {
|
||||
if (docs <= 0) {
|
||||
return;
|
||||
}
|
||||
bucketsBySource
|
||||
.computeIfAbsent(sourceId, key -> new ConcurrentHashMap<>())
|
||||
.merge(currentHour(), docs, Long::sum);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, DocStats> statsFor(Collection<String> sourceIds) {
|
||||
long now = currentHour();
|
||||
Map<String, DocStats> stats = new HashMap<>();
|
||||
for (String id : sourceIds) {
|
||||
Map<Long, Long> buckets = bucketsBySource.getOrDefault(id, Map.of());
|
||||
long total = buckets.values().stream().mapToLong(Long::longValue).sum();
|
||||
long last24h =
|
||||
SourceDocWindows.sumSince(buckets, now - (SourceDocWindows.HOURS_IN_24H - 1));
|
||||
long last30d = SourceDocWindows.sumSince(buckets, SourceDocWindows.firstDayHour(now));
|
||||
stats.put(id, new DocStats(total, last24h, last30d));
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Long> dailySeriesFor(String sourceId) {
|
||||
long now = currentHour();
|
||||
Map<Long, Long> buckets = bucketsBySource.getOrDefault(sourceId, Map.of());
|
||||
return SourceDocWindows.series(SourceDocWindows.byDay(buckets), now / 24);
|
||||
}
|
||||
|
||||
private long currentHour() {
|
||||
return clock.get().getEpochSecond() / 3600;
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.IntSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Durable {@link SourceDocCounter}; the runtime bean. {@code record} keeps two things in step: an
|
||||
* hourly bucket ({@link SourceDocCountEntity}) that feeds the rolling 24h / 30d / daily-series
|
||||
* windows, and a denormalized lifetime total ({@link SourceDocTotalEntity}) read directly for the
|
||||
* all-time figure. The lifetime counter means the overview never scans a source's whole bucket
|
||||
* history, and lets {@link #pruneOldBuckets()} retire buckets past the 30-day window so the hourly
|
||||
* table stays bounded (~one row per source per active hour, for at most 30 days).
|
||||
*/
|
||||
@Service
|
||||
@ConditionalOnBooleanProperty(name = "policies.enabled")
|
||||
public class JpaSourceDocCounter implements SourceDocCounter {
|
||||
|
||||
private final SourceDocCountRepository countRepository;
|
||||
private final SourceDocTotalRepository totalRepository;
|
||||
private final Supplier<Instant> clock;
|
||||
|
||||
@Autowired
|
||||
public JpaSourceDocCounter(
|
||||
SourceDocCountRepository countRepository, SourceDocTotalRepository totalRepository) {
|
||||
this(countRepository, totalRepository, Instant::now);
|
||||
}
|
||||
|
||||
// Clock seam so tests can pin "now"; the runtime bean uses the wall clock above.
|
||||
JpaSourceDocCounter(
|
||||
SourceDocCountRepository countRepository,
|
||||
SourceDocTotalRepository totalRepository,
|
||||
Supplier<Instant> clock) {
|
||||
this.countRepository = countRepository;
|
||||
this.totalRepository = totalRepository;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void record(String sourceId, long docs) {
|
||||
if (docs <= 0) {
|
||||
return;
|
||||
}
|
||||
long bucketHour = currentHour();
|
||||
upsert(
|
||||
() -> totalRepository.increment(sourceId, docs),
|
||||
() -> totalRepository.saveAndFlush(new SourceDocTotalEntity(sourceId, docs)));
|
||||
upsert(
|
||||
() -> countRepository.increment(sourceId, bucketHour, docs),
|
||||
() ->
|
||||
countRepository.saveAndFlush(
|
||||
new SourceDocCountEntity(sourceId, bucketHour, docs)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add {@code docs} to a per-source running total: increment the existing row, else insert a new
|
||||
* one. The insert is flushed now (in its own transaction, since {@code record} is not
|
||||
* {@code @Transactional}) so a concurrent run's winning insert surfaces as a constraint
|
||||
* violation we retry as an increment, rather than as a silent {@code merge} overwrite or a
|
||||
* later doomed commit.
|
||||
*/
|
||||
private static void upsert(IntSupplier increment, Runnable insert) {
|
||||
if (increment.getAsInt() > 0) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
insert.run();
|
||||
} catch (DataIntegrityViolationException concurrentInsert) {
|
||||
increment.getAsInt();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, DocStats> statsFor(Collection<String> sourceIds) {
|
||||
if (sourceIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
long now = currentHour();
|
||||
Map<String, Long> totals = sums(totalRepository.totalsFor(sourceIds));
|
||||
Map<String, Long> last24h =
|
||||
sums(
|
||||
countRepository.sumBySourceSince(
|
||||
sourceIds, now - (SourceDocWindows.HOURS_IN_24H - 1)));
|
||||
Map<String, Long> last30d =
|
||||
sums(
|
||||
countRepository.sumBySourceSince(
|
||||
sourceIds, SourceDocWindows.firstDayHour(now)));
|
||||
|
||||
Map<String, DocStats> stats = new HashMap<>();
|
||||
for (String id : sourceIds) {
|
||||
stats.put(
|
||||
id,
|
||||
new DocStats(
|
||||
totals.getOrDefault(id, 0L),
|
||||
last24h.getOrDefault(id, 0L),
|
||||
last30d.getOrDefault(id, 0L)));
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Long> dailySeriesFor(String sourceId) {
|
||||
long now = currentHour();
|
||||
Collection<String> ids = List.of(sourceId);
|
||||
Map<Long, Long> dailyCounts =
|
||||
dailyBySource(
|
||||
countRepository.dailyCountsSince(
|
||||
ids, SourceDocWindows.firstDayHour(now)))
|
||||
.getOrDefault(sourceId, Map.of());
|
||||
return SourceDocWindows.series(dailyCounts, now / 24);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retire hourly buckets older than the 30-day window; the lifetime total is held separately, so
|
||||
* nothing reported is lost. Daily is ample - the read queries already ignore older buckets, so
|
||||
* this is purely storage hygiene.
|
||||
*/
|
||||
@Scheduled(fixedDelay = 1, timeUnit = TimeUnit.DAYS)
|
||||
public void pruneOldBuckets() {
|
||||
countRepository.deleteOlderThan(SourceDocWindows.firstDayHour(currentHour()));
|
||||
}
|
||||
|
||||
private long currentHour() {
|
||||
return clock.get().getEpochSecond() / 3600;
|
||||
}
|
||||
|
||||
private static Map<String, Long> sums(List<SourceDocSum> rows) {
|
||||
Map<String, Long> map = new HashMap<>();
|
||||
for (SourceDocSum row : rows) {
|
||||
map.put(row.sourceId(), row.count() == null ? 0L : row.count());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static Map<String, Map<Long, Long>> dailyBySource(List<SourceDayDocSum> rows) {
|
||||
Map<String, Map<Long, Long>> bySource = new HashMap<>();
|
||||
for (SourceDayDocSum row : rows) {
|
||||
bySource.computeIfAbsent(row.sourceId(), key -> new HashMap<>())
|
||||
.merge(row.day(), row.docs() == null ? 0L : row.docs(), Long::sum);
|
||||
}
|
||||
return bySource;
|
||||
}
|
||||
}
|
||||
+14
@@ -74,6 +74,20 @@ public class SourceController {
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping("/{sourceId}/document-counts")
|
||||
@Operation(
|
||||
summary = "Daily document counts for a source",
|
||||
description =
|
||||
"The trailing 30-day per-day document series (oldest first) for the source's"
|
||||
+ " sparkline.")
|
||||
public ResponseEntity<List<Long>> documentCounts(@PathVariable String sourceId) {
|
||||
return sourceStore
|
||||
.get(sourceId)
|
||||
.filter(sourceAccessGuard::canAccess)
|
||||
.map(source -> ResponseEntity.ok(overviewService.dailySeries(source.id())))
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
|
||||
@Operation(
|
||||
summary = "Create or update a source",
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
/**
|
||||
* A {@code (sourceId, epoch-day, summed document count)} row from the daily-aggregate query. The
|
||||
* day is {@code floor(bucketHour / 24)}, i.e. hours-since-epoch collapsed to days-since-epoch.
|
||||
*/
|
||||
public record SourceDayDocSum(String sourceId, Long day, Long docs) {}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.data.domain.Persistable;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.IdClass;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.Transient;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* One hour's document tally for a source: {@code bucketHour} is the hours-since-epoch the documents
|
||||
* were fed, {@code docCount} the running total for that hour. Rolling-window totals are summed from
|
||||
* these buckets. {@code sourceId} is a plain value, not a foreign key, matching the rest of the
|
||||
* subsystem so it stays decoupled from the security entities.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "policy_source_doc_counts")
|
||||
@IdClass(SourceDocCountId.class)
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class SourceDocCountEntity implements Serializable, Persistable<SourceDocCountId> {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@Column(name = "source_id")
|
||||
private String sourceId;
|
||||
|
||||
@Id
|
||||
@Column(name = "bucket_hour")
|
||||
private long bucketHour;
|
||||
|
||||
@Column(name = "doc_count")
|
||||
private long docCount;
|
||||
|
||||
public SourceDocCountEntity(String sourceId, long bucketHour, long docCount) {
|
||||
this.sourceId = sourceId;
|
||||
this.bucketHour = bucketHour;
|
||||
this.docCount = docCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transient
|
||||
public SourceDocCountId getId() {
|
||||
return new SourceDocCountId(sourceId, bucketHour);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transient
|
||||
public boolean isNew() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Composite key for {@link SourceDocCountEntity}: one row per source per hour bucket. */
|
||||
public class SourceDocCountId implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private String sourceId;
|
||||
private long bucketHour;
|
||||
|
||||
public SourceDocCountId() {}
|
||||
|
||||
public SourceDocCountId(String sourceId, long bucketHour) {
|
||||
this.sourceId = sourceId;
|
||||
this.bucketHour = bucketHour;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (!(o instanceof SourceDocCountId other)) {
|
||||
return false;
|
||||
}
|
||||
return bucketHour == other.bucketHour && Objects.equals(sourceId, other.sourceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(sourceId, bucketHour);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
public interface SourceDocCountRepository
|
||||
extends JpaRepository<SourceDocCountEntity, SourceDocCountId> {
|
||||
|
||||
/**
|
||||
* Add to an existing bucket; returns the number of rows updated (0 when the bucket is new).
|
||||
* Transactional per call so {@code JpaSourceDocCounter.record} can run it (and the retry after
|
||||
* a concurrent insert) without an enclosing transaction.
|
||||
*/
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query(
|
||||
"update SourceDocCountEntity e set e.docCount = e.docCount + :docs"
|
||||
+ " where e.sourceId = :sourceId and e.bucketHour = :bucketHour")
|
||||
int increment(
|
||||
@Param("sourceId") String sourceId,
|
||||
@Param("bucketHour") long bucketHour,
|
||||
@Param("docs") long docs);
|
||||
|
||||
/**
|
||||
* Delete hourly buckets older than {@code floor} (hours-since-epoch). Nothing reads buckets
|
||||
* before the 30-day window ({@code SourceDocWindows.firstDayHour}); the lifetime total lives in
|
||||
* {@code policy_source_doc_totals}, so retiring old buckets keeps the table bounded without
|
||||
* losing any reported figure.
|
||||
*/
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("delete from SourceDocCountEntity e where e.bucketHour < :floor")
|
||||
int deleteOlderThan(@Param("floor") long floor);
|
||||
|
||||
/**
|
||||
* Document total per source restricted to buckets at or after {@code since} (the 24h window).
|
||||
*/
|
||||
@Query(
|
||||
"select new stirling.software.proprietary.policy.source.SourceDocSum("
|
||||
+ "e.sourceId, sum(e.docCount))"
|
||||
+ " from SourceDocCountEntity e"
|
||||
+ " where e.sourceId in :ids and e.bucketHour >= :since"
|
||||
+ " group by e.sourceId")
|
||||
List<SourceDocSum> sumBySourceSince(
|
||||
@Param("ids") Collection<String> ids, @Param("since") long since);
|
||||
|
||||
/**
|
||||
* Per-source, per-day document totals for buckets at or after {@code since}, summed in the
|
||||
* database so the overview reads ~one row per source per active day instead of per active hour.
|
||||
* The day is {@code cast(floor(bucketHour / 24.0) as long)}: {@code 24.0} forces decimal
|
||||
* division and the cast pins the result to a whole day on every dialect.
|
||||
*/
|
||||
@Query(
|
||||
"select new stirling.software.proprietary.policy.source.SourceDayDocSum("
|
||||
+ "e.sourceId, cast(floor(e.bucketHour / 24.0) as long), sum(e.docCount))"
|
||||
+ " from SourceDocCountEntity e"
|
||||
+ " where e.sourceId in :ids and e.bucketHour >= :since"
|
||||
+ " group by cast(floor(e.bucketHour / 24.0) as long), e.sourceId")
|
||||
List<SourceDayDocSum> dailyCountsSince(
|
||||
@Param("ids") Collection<String> ids, @Param("since") long since);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Records and reports how many documents each source feeds into runs. Counting is bucketed by hour
|
||||
* so the overview can report rolling totals ({@link DocStats}) cheaply; {@link JpaSourceDocCounter}
|
||||
* is the runtime bean and {@link InProcessSourceDocCounter} backs tests.
|
||||
*/
|
||||
public interface SourceDocCounter {
|
||||
|
||||
/** Record that {@code docs} documents were fed from {@code sourceId} at the current time. */
|
||||
void record(String sourceId, long docs);
|
||||
|
||||
/**
|
||||
* Document totals for each given source; a source with no recorded docs maps to {@link
|
||||
* DocStats#ZERO}.
|
||||
*/
|
||||
Map<String, DocStats> statsFor(Collection<String> sourceIds);
|
||||
|
||||
/**
|
||||
* The trailing {@link DocStats#DAYS}-day daily document series for one source, oldest first,
|
||||
* for the detail-panel sparkline.
|
||||
*/
|
||||
List<Long> dailySeriesFor(String sourceId);
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
/**
|
||||
* A {@code (sourceId, summed document count)} row, populated by the doc-count aggregate queries.
|
||||
*/
|
||||
public record SourceDocSum(String sourceId, Long count) {}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.data.domain.Persistable;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.Transient;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* A source's lifetime document total, denormalized so the overview reads the all-time count in one
|
||||
* row instead of scanning the source's whole hourly-bucket history, and so {@link
|
||||
* SourceDocCountEntity} buckets can be pruned to the rolling 30-day window without losing it.
|
||||
*
|
||||
* <p>Like {@link SourceDocCountEntity}, implements {@link Persistable} reporting {@code isNew() ==
|
||||
* true} so a new source's first {@code save} {@code persist}s (a raw INSERT) and a concurrent
|
||||
* insert surfaces as a constraint violation the counter retries as an increment, rather than {@code
|
||||
* merge} silently overwriting it.
|
||||
*/
|
||||
@Entity
|
||||
@Table(name = "policy_source_doc_totals")
|
||||
@NoArgsConstructor
|
||||
@Getter
|
||||
@Setter
|
||||
public class SourceDocTotalEntity implements Serializable, Persistable<String> {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Id
|
||||
@Column(name = "source_id")
|
||||
private String sourceId;
|
||||
|
||||
@Column(name = "doc_total")
|
||||
private long docTotal;
|
||||
|
||||
public SourceDocTotalEntity(String sourceId, long docTotal) {
|
||||
this.sourceId = sourceId;
|
||||
this.docTotal = docTotal;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transient
|
||||
public String getId() {
|
||||
return sourceId;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transient
|
||||
public boolean isNew() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Repository
|
||||
public interface SourceDocTotalRepository extends JpaRepository<SourceDocTotalEntity, String> {
|
||||
|
||||
/**
|
||||
* Add to a source's lifetime total; returns the number of rows updated (0 when the source has
|
||||
* no total row yet). Transactional per call so {@code JpaSourceDocCounter.record} can run it
|
||||
* (and the retry after a concurrent insert) without an enclosing transaction.
|
||||
*/
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query(
|
||||
"update SourceDocTotalEntity e set e.docTotal = e.docTotal + :docs"
|
||||
+ " where e.sourceId = :sourceId")
|
||||
int increment(@Param("sourceId") String sourceId, @Param("docs") long docs);
|
||||
|
||||
/** Lifetime totals for the given sources, as {@code (sourceId, total)} rows. */
|
||||
@Query(
|
||||
"select new stirling.software.proprietary.policy.source.SourceDocSum("
|
||||
+ "e.sourceId, e.docTotal)"
|
||||
+ " from SourceDocTotalEntity e where e.sourceId in :ids")
|
||||
List<SourceDocSum> totalsFor(@Param("ids") Collection<String> ids);
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Shared rolling-window math over a source's document buckets, so the JPA and in-memory counters
|
||||
* agree on the window boundaries and the daily series. Both define "last 30 days" as the buckets at
|
||||
* or after {@link #firstDayHour}, and build the series from per-day counts with {@link #series}
|
||||
* (the JPA counter aggregates by day in SQL; the in-memory counter groups its hourly buckets with
|
||||
* {@link #byDay}).
|
||||
*/
|
||||
final class SourceDocWindows {
|
||||
|
||||
static final long HOURS_IN_24H = 24;
|
||||
|
||||
private SourceDocWindows() {}
|
||||
|
||||
/**
|
||||
* The hours-since-epoch at the start of the oldest day in the 30-day window, given the current
|
||||
* hour bucket. Both the "last 30 days" total and the daily series are measured from here, so
|
||||
* the KPI and the sparkline always cover the same buckets.
|
||||
*/
|
||||
static long firstDayHour(long nowHour) {
|
||||
return ((nowHour / 24) - (DocStats.DAYS - 1)) * 24;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the {@link DocStats#DAYS}-day daily series (oldest first) from per-day document counts
|
||||
* (keyed by epoch-day, i.e. hours-since-epoch / 24). {@code currentDay} is today's epoch-day;
|
||||
* the series runs back {@code DAYS} days from it.
|
||||
*/
|
||||
static List<Long> series(Map<Long, Long> dailyCounts, long currentDay) {
|
||||
long firstDay = currentDay - (DocStats.DAYS - 1);
|
||||
long[] daily = new long[DocStats.DAYS];
|
||||
for (Map.Entry<Long, Long> day : dailyCounts.entrySet()) {
|
||||
int dayIndex = (int) (day.getKey() - firstDay);
|
||||
if (dayIndex >= 0 && dayIndex < DocStats.DAYS) {
|
||||
daily[dayIndex] += day.getValue();
|
||||
}
|
||||
}
|
||||
return Arrays.stream(daily).boxed().toList();
|
||||
}
|
||||
|
||||
/** Collapse hourly buckets (keyed by hours-since-epoch) into per-day counts (keyed by day). */
|
||||
static Map<Long, Long> byDay(Map<Long, Long> hourlyCounts) {
|
||||
Map<Long, Long> dailyCounts = new HashMap<>();
|
||||
hourlyCounts.forEach((hour, count) -> dailyCounts.merge(hour / 24, count, Long::sum));
|
||||
return dailyCounts;
|
||||
}
|
||||
|
||||
/** Sum hourly buckets at or after {@code since} (hours-since-epoch). */
|
||||
static long sumSince(Map<Long, Long> hourlyCounts, long since) {
|
||||
return hourlyCounts.entrySet().stream()
|
||||
.filter(entry -> entry.getKey() >= since)
|
||||
.mapToLong(Map.Entry::getValue)
|
||||
.sum();
|
||||
}
|
||||
}
|
||||
+18
-3
@@ -30,12 +30,15 @@ public class SourceOverviewService {
|
||||
private final PolicyStore policyStore;
|
||||
private final SourceAccessGuard sourceAccessGuard;
|
||||
private final PolicyAccessGuard policyAccessGuard;
|
||||
private final SourceDocCounter docCounter;
|
||||
|
||||
public SourcesResponse overview() {
|
||||
List<Source> sources = sourceAccessGuard.visibleFrom(sourceStore);
|
||||
List<Policy> policies = policyAccessGuard.visibleFrom(policyStore);
|
||||
|
||||
Map<String, List<Policy>> referencesBySource = referencesBySource(policies);
|
||||
Map<String, DocStats> docStats =
|
||||
docCounter.statsFor(sources.stream().map(Source::id).toList());
|
||||
|
||||
List<SourceView> views =
|
||||
sources.stream()
|
||||
@@ -44,7 +47,8 @@ public class SourceOverviewService {
|
||||
toView(
|
||||
source,
|
||||
referencesBySource.getOrDefault(
|
||||
source.id(), List.of())))
|
||||
source.id(), List.of()),
|
||||
docStats.getOrDefault(source.id(), DocStats.ZERO)))
|
||||
.sorted(
|
||||
Comparator.comparingInt(SourceView::referenceCount)
|
||||
.reversed()
|
||||
@@ -54,6 +58,14 @@ public class SourceOverviewService {
|
||||
return new SourcesResponse(buildKpis(views), views);
|
||||
}
|
||||
|
||||
/**
|
||||
* The 30-day daily document series for one source (oldest first), for the expanded row's
|
||||
* sparkline.
|
||||
*/
|
||||
public List<Long> dailySeries(String sourceId) {
|
||||
return docCounter.dailySeriesFor(sourceId);
|
||||
}
|
||||
|
||||
/** Policies referencing each source id, across the caller's visible policies. */
|
||||
private static Map<String, List<Policy>> referencesBySource(List<Policy> policies) {
|
||||
Map<String, List<Policy>> bySource = new HashMap<>();
|
||||
@@ -65,7 +77,8 @@ public class SourceOverviewService {
|
||||
return bySource;
|
||||
}
|
||||
|
||||
private static SourceView toView(Source source, List<Policy> referencingPolicies) {
|
||||
private static SourceView toView(
|
||||
Source source, List<Policy> referencingPolicies, DocStats docs) {
|
||||
List<SourceView.PolicyRef> refs =
|
||||
referencingPolicies.stream()
|
||||
.map(policy -> new SourceView.PolicyRef(policy.id(), policy.name()))
|
||||
@@ -78,7 +91,9 @@ public class SourceOverviewService {
|
||||
refs.size(),
|
||||
refs,
|
||||
configRows(source),
|
||||
null);
|
||||
docs.total(),
|
||||
docs.last24h(),
|
||||
docs.last30d());
|
||||
}
|
||||
|
||||
/** A disabled (paused) source reads as "disabled"; an unreferenced one reads as "unused". */
|
||||
|
||||
+5
-3
@@ -4,8 +4,8 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* One row in the Sources overview: a persisted input connection shown exactly once, with how many
|
||||
* policies reference it (and which). {@code docsTotal} is {@code null} - per-source document volume
|
||||
* is not tracked yet; the field is reserved so a later doc-accounting pass is additive.
|
||||
* policies reference it (and which) and how many documents it has fed into runs ({@code docsTotal}
|
||||
* lifetime plus the trailing 24-hour and 30-day windows).
|
||||
*/
|
||||
public record SourceView(
|
||||
String id,
|
||||
@@ -15,7 +15,9 @@ public record SourceView(
|
||||
int referenceCount,
|
||||
List<PolicyRef> referencingPolicies,
|
||||
List<DetailRow> config,
|
||||
Long docsTotal) {
|
||||
long docsTotal,
|
||||
long docs24h,
|
||||
long docs30d) {
|
||||
|
||||
/** A policy that references this source. */
|
||||
public record PolicyRef(String id, String name) {}
|
||||
|
||||
+7
-1
@@ -33,6 +33,7 @@ import stirling.software.proprietary.policy.model.PolicyInputs;
|
||||
import stirling.software.proprietary.policy.model.PolicyRun;
|
||||
import stirling.software.proprietary.policy.model.PolicyRunStatus;
|
||||
import stirling.software.proprietary.policy.progress.PolicyProgressListener;
|
||||
import stirling.software.proprietary.policy.source.InProcessSourceDocCounter;
|
||||
import stirling.software.proprietary.policy.source.InProcessSourceStore;
|
||||
import stirling.software.proprietary.policy.source.Source;
|
||||
import stirling.software.proprietary.policy.source.SourceStore;
|
||||
@@ -53,7 +54,12 @@ class PolicyRunnerTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
runner = new PolicyRunner(policyEngine, List.of(folderSource), sourceStore);
|
||||
runner =
|
||||
new PolicyRunner(
|
||||
policyEngine,
|
||||
List.of(folderSource),
|
||||
sourceStore,
|
||||
new InProcessSourceDocCounter());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Tests the rolling-window aggregation: documents recorded at different times roll into the total,
|
||||
* the 24-hour / 30-day windows, and the daily series correctly as the clock advances.
|
||||
*/
|
||||
class InProcessSourceDocCounterTest {
|
||||
|
||||
private static InProcessSourceDocCounter seededCounter(AtomicReference<Instant> clock) {
|
||||
InProcessSourceDocCounter counter = new InProcessSourceDocCounter(clock::get);
|
||||
// 40 days ago: outside the 30-day window.
|
||||
clock.set(Instant.parse("2026-05-21T12:00:00Z"));
|
||||
counter.record("s", 100);
|
||||
// 10 days ago: inside 30 days, outside 24 hours.
|
||||
clock.set(Instant.parse("2026-06-20T12:00:00Z"));
|
||||
counter.record("s", 50);
|
||||
// 2 hours ago: inside both windows.
|
||||
clock.set(Instant.parse("2026-06-30T10:00:00Z"));
|
||||
counter.record("s", 7);
|
||||
// Query as of "now".
|
||||
clock.set(Instant.parse("2026-06-30T12:00:00Z"));
|
||||
return counter;
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollsCountsIntoTotalAnd24hAnd30dWindows() {
|
||||
AtomicReference<Instant> clock = new AtomicReference<>();
|
||||
DocStats stats = seededCounter(clock).statsFor(List.of("s")).get("s");
|
||||
|
||||
assertEquals(157, stats.total());
|
||||
assertEquals(7, stats.last24h());
|
||||
assertEquals(57, stats.last30d());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildsTheDailySeriesOldestFirst() {
|
||||
AtomicReference<Instant> clock = new AtomicReference<>();
|
||||
// Today (index 29) and 10 days ago (index 19) only; 40 days ago is outside the window.
|
||||
List<Long> series = seededCounter(clock).dailySeriesFor("s");
|
||||
|
||||
assertEquals(30, series.size());
|
||||
assertEquals(7L, series.get(29));
|
||||
assertEquals(50L, series.get(19));
|
||||
assertEquals(57L, series.stream().mapToLong(Long::longValue).sum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSourceWithNoRecordedDocsIsZero() {
|
||||
InProcessSourceDocCounter counter = new InProcessSourceDocCounter();
|
||||
assertEquals(DocStats.ZERO, counter.statsFor(List.of("unknown")).get("unknown"));
|
||||
assertEquals(Collections.nCopies(DocStats.DAYS, 0L), counter.dailySeriesFor("unknown"));
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
|
||||
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
|
||||
|
||||
/**
|
||||
* Exercises {@link JpaSourceDocCounter} against a real (H2) database so the daily-aggregate query
|
||||
* ({@code cast(floor(bucketHour / 24.0) as long)} grouping) and the record upsert are actually run,
|
||||
* not just asserted against a mock. The unit-level window math lives in {@link
|
||||
* InProcessSourceDocCounterTest}.
|
||||
*/
|
||||
@DataJpaTest
|
||||
class JpaSourceDocCounterDbTest {
|
||||
|
||||
// Pinned "now" so seeding and statsFor agree regardless of when the test runs (no hour-tick
|
||||
// flake at the boundary of a wall-clock hour).
|
||||
private static final Instant NOW = Instant.parse("2026-06-30T12:00:00Z");
|
||||
private static final long NOW_HOUR = NOW.getEpochSecond() / 3600;
|
||||
|
||||
@Autowired private SourceDocCountRepository repository;
|
||||
@Autowired private SourceDocTotalRepository totalRepository;
|
||||
|
||||
private JpaSourceDocCounter counter() {
|
||||
return new JpaSourceDocCounter(repository, totalRepository, () -> NOW);
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordIncrementsBothTheHourlyBucketAndTheLifetimeTotal() {
|
||||
JpaSourceDocCounter counter = counter();
|
||||
counter.record("s", 5);
|
||||
counter.record("s", 3);
|
||||
|
||||
DocStats stats = counter.statsFor(List.of("s")).get("s");
|
||||
assertEquals(8, stats.total()); // from the denormalized lifetime row
|
||||
assertEquals(8, stats.last24h());
|
||||
assertEquals(8, stats.last30d());
|
||||
assertEquals(8L, counter.dailySeriesFor("s").get(DocStats.DAYS - 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void statsBucketDocsByDayAndWindowFromTheDatabase() {
|
||||
// Seed buckets directly at controlled hours: today, 10 days ago, 40 days ago, plus the
|
||||
// lifetime row (record() would write it, but here we seed history directly).
|
||||
repository.saveAndFlush(new SourceDocCountEntity("s", NOW_HOUR, 7));
|
||||
repository.saveAndFlush(new SourceDocCountEntity("s", NOW_HOUR - 24L * 10, 50));
|
||||
repository.saveAndFlush(new SourceDocCountEntity("s", NOW_HOUR - 24L * 40, 100));
|
||||
totalRepository.saveAndFlush(new SourceDocTotalEntity("s", 157));
|
||||
|
||||
DocStats stats = counter().statsFor(List.of("s")).get("s");
|
||||
assertEquals(157, stats.total()); // lifetime, including the out-of-window 40-days-ago docs
|
||||
assertEquals(7, stats.last24h());
|
||||
assertEquals(57, stats.last30d());
|
||||
|
||||
// The daily series (fetched separately, per source) covers the same 30-day window.
|
||||
List<Long> series = counter().dailySeriesFor("s");
|
||||
assertEquals(DocStats.DAYS, series.size());
|
||||
assertEquals(7L, series.get(DocStats.DAYS - 1)); // today
|
||||
assertEquals(50L, series.get(DocStats.DAYS - 11)); // 10 days ago
|
||||
assertEquals(57L, series.stream().mapToLong(Long::longValue).sum());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pruneRetiresOutOfWindowBucketsButKeepsTheLifetimeTotal() {
|
||||
repository.saveAndFlush(new SourceDocCountEntity("s", NOW_HOUR, 7)); // today
|
||||
repository.saveAndFlush(new SourceDocCountEntity("s", NOW_HOUR - 24L * 40, 100)); // 40d ago
|
||||
totalRepository.saveAndFlush(new SourceDocTotalEntity("s", 107));
|
||||
|
||||
counter().pruneOldBuckets();
|
||||
|
||||
assertEquals(1, repository.count()); // only the in-window bucket remains
|
||||
DocStats stats = counter().statsFor(List.of("s")).get("s");
|
||||
assertEquals(107, stats.total()); // lifetime survives pruning
|
||||
assertEquals(7, stats.last24h());
|
||||
assertEquals(7, stats.last30d());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSourceWithNoRecordedDocsIsZero() {
|
||||
assertEquals(DocStats.ZERO, counter().statsFor(List.of("unknown")).get("unknown"));
|
||||
}
|
||||
|
||||
@SpringBootConfiguration
|
||||
@AutoConfigurationPackage
|
||||
static class TestApp {}
|
||||
}
|
||||
+6
-1
@@ -50,7 +50,12 @@ class SourceControllerTest {
|
||||
SourceAccessGuard sourceGuard = new SourceAccessGuard(userService, properties, authority);
|
||||
PolicyAccessGuard policyGuard = new PolicyAccessGuard(userService, properties, authority);
|
||||
SourceOverviewService overviewService =
|
||||
new SourceOverviewService(sourceStore, policyStore, sourceGuard, policyGuard);
|
||||
new SourceOverviewService(
|
||||
sourceStore,
|
||||
policyStore,
|
||||
sourceGuard,
|
||||
policyGuard,
|
||||
new InProcessSourceDocCounter());
|
||||
triggerManager = mock(PolicyTriggerManager.class);
|
||||
// A permissive input source so config validation passes and save can be exercised.
|
||||
InputSource folderInput = mock(InputSource.class);
|
||||
|
||||
+18
-5
@@ -1,7 +1,6 @@
|
||||
package stirling.software.proprietary.policy.source;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -31,6 +30,7 @@ class SourceOverviewServiceTest {
|
||||
|
||||
private final SourceStore sourceStore = new InProcessSourceStore();
|
||||
private final PolicyStore policyStore = new InProcessPolicyStore();
|
||||
private final SourceDocCounter docCounter = new InProcessSourceDocCounter();
|
||||
private SourceOverviewService service;
|
||||
|
||||
@BeforeEach
|
||||
@@ -41,7 +41,9 @@ class SourceOverviewServiceTest {
|
||||
PolicyManagementAuthority authority = mock(PolicyManagementAuthority.class);
|
||||
SourceAccessGuard sourceGuard = new SourceAccessGuard(userService, properties, authority);
|
||||
PolicyAccessGuard policyGuard = new PolicyAccessGuard(userService, properties, authority);
|
||||
service = new SourceOverviewService(sourceStore, policyStore, sourceGuard, policyGuard);
|
||||
service =
|
||||
new SourceOverviewService(
|
||||
sourceStore, policyStore, sourceGuard, policyGuard, docCounter);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -111,7 +113,8 @@ class SourceOverviewServiceTest {
|
||||
SourceAccessGuard sourceGuard = new SourceAccessGuard(userService, properties, authority);
|
||||
PolicyAccessGuard policyGuard = new PolicyAccessGuard(userService, properties, authority);
|
||||
SourceOverviewService scoped =
|
||||
new SourceOverviewService(sourceStore, policyStore, sourceGuard, policyGuard);
|
||||
new SourceOverviewService(
|
||||
sourceStore, policyStore, sourceGuard, policyGuard, docCounter);
|
||||
|
||||
Source ours = teamSource("Ours", "/ours", 1L);
|
||||
teamSource("Theirs", "/theirs", 2L);
|
||||
@@ -128,9 +131,19 @@ class SourceOverviewServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void documentVolumeIsNotTrackedYet() {
|
||||
void documentCountsReflectRecordedDocs() {
|
||||
Source a = source("A", "/a");
|
||||
assertNull(find(service.overview(), a.id()).docsTotal());
|
||||
Source b = source("B", "/b");
|
||||
docCounter.record(a.id(), 5);
|
||||
docCounter.record(a.id(), 3);
|
||||
|
||||
SourceView av = find(service.overview(), a.id());
|
||||
assertEquals(8, av.docsTotal());
|
||||
assertEquals(8, av.docs24h());
|
||||
assertEquals(8, av.docs30d());
|
||||
|
||||
// A source with no recorded documents reads as zero, not null.
|
||||
assertEquals(0, find(service.overview(), b.id()).docsTotal());
|
||||
}
|
||||
|
||||
private Source source(String name, String directory) {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Per-source document throughput, in two tables:
|
||||
--
|
||||
-- policy_source_doc_counts one row per source per hour bucket (hours-since-epoch), holding how
|
||||
-- many documents that source fed into runs in that hour. Feeds the
|
||||
-- rolling last-24h / last-30d windows and the 30-day daily series, and
|
||||
-- is pruned to that window so it stays bounded.
|
||||
-- policy_source_doc_totals a denormalized lifetime total per source, incremented alongside the
|
||||
-- hourly bucket, so the overview reads the all-time figure in one row
|
||||
-- instead of scanning a source's whole bucket history - and so the
|
||||
-- hourly buckets can be pruned without losing it.
|
||||
--
|
||||
-- Gated by policies.enabled like the rest of the subsystem; Hibernate ddl-auto would also create
|
||||
-- these, but the migration keeps the schema explicit for the Flyway-managed deployments.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS policy_source_doc_counts (
|
||||
source_id VARCHAR(255) NOT NULL,
|
||||
bucket_hour BIGINT NOT NULL,
|
||||
doc_count BIGINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (source_id, bucket_hour)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS policy_source_doc_totals (
|
||||
source_id VARCHAR(255) NOT NULL,
|
||||
doc_total BIGINT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (source_id)
|
||||
);
|
||||
@@ -1,5 +1,8 @@
|
||||
"""Agent modules for Stirling AI reasoning flows."""
|
||||
|
||||
from collections.abc import Iterable
|
||||
|
||||
from ._registry import AgentDescriptor, RegisterableAgent
|
||||
from .execution import ExecutionPlanningAgent
|
||||
from .orchestrator import OrchestratorAgent
|
||||
from .pdf_create import PdfCreateAgent
|
||||
@@ -8,7 +11,17 @@ from .pdf_questions import PdfQuestionAgent
|
||||
from .pdf_review import PdfReviewAgent
|
||||
from .user_spec import UserSpecAgent
|
||||
|
||||
|
||||
def build_descriptors(agents: Iterable[RegisterableAgent]) -> list[AgentDescriptor]:
|
||||
"""The canonical descriptor list driving both orchestrator routing and the MCP
|
||||
manifest. Pass the live agent singletons. Adding an agent means implementing
|
||||
``describe`` and including its instance in the caller's list.
|
||||
"""
|
||||
return [agent.describe() for agent in agents]
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AgentDescriptor",
|
||||
"ExecutionPlanningAgent",
|
||||
"OrchestratorAgent",
|
||||
"PdfCreateAgent",
|
||||
@@ -17,5 +30,7 @@ __all__ = [
|
||||
"PdfEditPlanSelection",
|
||||
"PdfQuestionAgent",
|
||||
"PdfReviewAgent",
|
||||
"RegisterableAgent",
|
||||
"UserSpecAgent",
|
||||
"build_descriptors",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Single source of truth for how each agent is exposed.
|
||||
|
||||
An agent declares one :class:`AgentDescriptor` via :meth:`RegisterableAgent.describe`.
|
||||
Two projections are derived from the collected descriptors, so neither has to be
|
||||
hand-maintained:
|
||||
|
||||
* the **orchestrator** builds its delegate ``ToolOutput`` union and ``resume``
|
||||
dispatch from descriptors whose ``orchestrator`` route is set;
|
||||
* the **MCP capabilities manifest** is built from descriptors' ``mcp`` rows.
|
||||
|
||||
Adding an agent therefore means implementing ``describe`` and adding the instance
|
||||
to ``build_descriptors`` — the orchestrator and the manifest both update for free.
|
||||
|
||||
Note: this ``AgentDescriptor`` registry (how an agent is *published*) is unrelated
|
||||
to the runtime "capability" toolsets like ``ContradictionCapability`` /
|
||||
``RagCapability`` (tools *injected into* an agent run).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic_ai.output import ToolOutput
|
||||
from pydantic_ai.tools import RunContext
|
||||
|
||||
from stirling.contracts import OrchestratorRequest, OrchestratorResponse, SupportedCapability
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
OrchestrateFn = Callable[[OrchestratorRequest], Awaitable[OrchestratorResponse]]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrchestratorDeps:
|
||||
runtime: AppRuntime
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrchestratorRoute:
|
||||
"""How an agent is exposed to the top-level orchestrator LLM and resume path.
|
||||
|
||||
``capability`` keys the resume dispatch: the orchestrator re-enters this
|
||||
delegate when a ``resume_with`` of the same value arrives.
|
||||
"""
|
||||
|
||||
capability: SupportedCapability
|
||||
tool_name: str
|
||||
tool_description: str
|
||||
orchestrate: OrchestrateFn
|
||||
|
||||
async def _invoke(self, ctx: RunContext[OrchestratorDeps]) -> OrchestratorResponse:
|
||||
return await self.orchestrate(ctx.deps.request)
|
||||
|
||||
def tool_output(self) -> ToolOutput[OrchestratorResponse]:
|
||||
return ToolOutput(self._invoke, name=self.tool_name, description=self.tool_description)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class McpCapability:
|
||||
"""One row in the MCP capabilities manifest the Java MCP server publishes."""
|
||||
|
||||
id: str
|
||||
description: str
|
||||
input_model: type[BaseModel]
|
||||
mode: Literal["sync", "async"]
|
||||
required_scope: str
|
||||
route: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentDescriptor:
|
||||
"""How one agent is published. ``orchestrator`` set => routable by the
|
||||
top-level orchestrator; ``mcp`` non-empty => exposed in the MCP manifest.
|
||||
The two are independent: an agent may be one, the other, or both."""
|
||||
|
||||
orchestrator: OrchestratorRoute | None = None
|
||||
mcp: tuple[McpCapability, ...] = ()
|
||||
|
||||
|
||||
class RegisterableAgent(ABC):
|
||||
"""Base for any agent that publishes itself to the orchestrator and/or MCP.
|
||||
|
||||
Enforces a uniform ``describe`` entry point that startup wiring collects via
|
||||
``build_descriptors``."""
|
||||
|
||||
@abstractmethod
|
||||
def describe(self) -> AgentDescriptor: ...
|
||||
@@ -1,13 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, RegisterableAgent
|
||||
from stirling.contracts import AgentExecutionRequest, CannotContinueExecutionAction, NextExecutionAction
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
|
||||
class ExecutionPlanningAgent:
|
||||
class ExecutionPlanningAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
# MCP-only: an internal sub-agent the orchestrator never delegates to.
|
||||
return AgentDescriptor(
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="agent-next-action",
|
||||
description=(
|
||||
"Decide the next execution step for an in-progress agent workflow. Returns a"
|
||||
" ToolCall, Completed, or CannotContinue action."
|
||||
),
|
||||
input_model=AgentExecutionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/agents/next-action",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def next_action(self, request: AgentExecutionRequest) -> NextExecutionAction:
|
||||
return CannotContinueExecutionAction(
|
||||
reason=f"Execution planning is not implemented yet for step {request.current_step_index}."
|
||||
|
||||
@@ -29,6 +29,7 @@ from pydantic import BaseModel, Field
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.exceptions import AgentRunError
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, RegisterableAgent
|
||||
from stirling.contracts.ledger import (
|
||||
Discrepancy,
|
||||
DiscrepancyKind,
|
||||
@@ -113,7 +114,7 @@ class StatementsResult(BaseModel):
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class MathAuditorAgent:
|
||||
class MathAuditorAgent(RegisterableAgent):
|
||||
"""
|
||||
Encapsulates the Ledger Auditor pipeline.
|
||||
|
||||
@@ -121,6 +122,37 @@ class MathAuditorAgent:
|
||||
pre-built Model objects and ModelSettings.
|
||||
"""
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
# MCP-only: the orchestrator reaches the math auditor indirectly (an agent
|
||||
# emits a plan with the MATH_AUDITOR_AGENT tool, which Java runs via the
|
||||
# examine/deliberate routes), so there is no orchestrator delegate here.
|
||||
return AgentDescriptor(
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="math-audit-examine",
|
||||
description=(
|
||||
"Examine a folio manifest of financial / numeric documents and surface the"
|
||||
" evidence that needs to be checked for arithmetic consistency."
|
||||
),
|
||||
input_model=FolioManifest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/examine",
|
||||
),
|
||||
McpCapability(
|
||||
id="math-audit-deliberate",
|
||||
description=(
|
||||
"Render a deliberated verdict on a single piece of evidence the examine step"
|
||||
" surfaced (does the arithmetic check out, with what caveats)."
|
||||
),
|
||||
input_model=Evidence,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/deliberate",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
fast_model = runtime.fast_model
|
||||
model_settings = runtime.fast_model_settings
|
||||
|
||||
@@ -1,91 +1,45 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import assert_never
|
||||
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import ToolOutput
|
||||
from pydantic_ai.tools import RunContext
|
||||
|
||||
from stirling.agents.pdf_create import PdfCreateAgent
|
||||
from stirling.agents.pdf_edit import PdfEditAgent
|
||||
from stirling.agents.pdf_questions import PdfQuestionAgent
|
||||
from stirling.agents.pdf_review import PdfReviewAgent
|
||||
from stirling.agents.user_spec import UserSpecAgent
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorDeps, OrchestratorRoute
|
||||
from stirling.contracts import (
|
||||
AgentDraftWorkflowResponse,
|
||||
ConvertMarkdownResponse,
|
||||
ExtractedTextArtifact,
|
||||
OrchestratorRequest,
|
||||
OrchestratorResponse,
|
||||
PdfEditResponse,
|
||||
PdfQuestionOrchestrateResponse,
|
||||
PdfReviewOrchestrateResponse,
|
||||
SupportedCapability,
|
||||
UnsupportedCapabilityResponse,
|
||||
format_conversation_history,
|
||||
format_file_names,
|
||||
)
|
||||
from stirling.contracts.pdf_create import PdfCreateOrchestrateResponse
|
||||
from stirling.services import AppRuntime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrchestratorDeps:
|
||||
runtime: AppRuntime
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
class OrchestratorAgent:
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
def __init__(self, runtime: AppRuntime, descriptors: list[AgentDescriptor]) -> None:
|
||||
self.runtime = runtime
|
||||
routes = [d.orchestrator for d in descriptors if d.orchestrator is not None]
|
||||
self._delegates_by_capability: dict[SupportedCapability, OrchestratorRoute] = {
|
||||
route.capability: route for route in routes
|
||||
}
|
||||
self.agent = Agent(
|
||||
model=runtime.fast_model,
|
||||
output_type=[
|
||||
ToolOutput(
|
||||
self.delegate_pdf_edit,
|
||||
name="delegate_pdf_edit",
|
||||
description="Delegate requests for PDF modifications and return the PDF edit result.",
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_pdf_question,
|
||||
name="delegate_pdf_question",
|
||||
description="Delegate questions about PDF contents and return the PDF question result.",
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_user_spec,
|
||||
name="delegate_user_spec",
|
||||
description="Delegate requests to create or revise a user agent spec and return the draft result.",
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_pdf_review,
|
||||
name="delegate_pdf_review",
|
||||
description=(
|
||||
"Delegate requests to review a PDF and leave review comments, notes, or"
|
||||
" sticky-note annotations on the document itself. Use this when the user"
|
||||
" wants the PDF returned with comments attached (e.g. 'review this',"
|
||||
" 'add review comments', 'flag unclear sentences', 'annotate with"
|
||||
" feedback')."
|
||||
),
|
||||
),
|
||||
*(route.tool_output() for route in routes),
|
||||
# PDF ingest is a canned one-shot (no agent, never resumed), so like
|
||||
# unsupported_capability it lives inline rather than in the registry.
|
||||
ToolOutput(
|
||||
self.delegate_pdf_ingest,
|
||||
name="delegate_pdf_ingest",
|
||||
description=(
|
||||
"Delegate requests to convert a PDF to Markdown or extract its content as readable text."
|
||||
),
|
||||
),
|
||||
ToolOutput(
|
||||
self.delegate_pdf_create,
|
||||
name="delegate_pdf_create",
|
||||
description=(
|
||||
"Delegate requests to create a new PDF document from scratch based on a"
|
||||
" description. Use this when the user wants to generate a new document"
|
||||
" (e.g. 'create an invoice', 'write a report', 'make a contract',"
|
||||
" 'draft a letter'). No input file is required."
|
||||
"Delegate any request to convert a PDF to Markdown or extract its content as readable text."
|
||||
),
|
||||
),
|
||||
ToolOutput(
|
||||
@@ -98,16 +52,7 @@ class OrchestratorAgent:
|
||||
system_prompt=(
|
||||
"You are the top-level orchestrator. "
|
||||
"Choose exactly one output function that best handles the request. "
|
||||
"Use delegate_pdf_edit for any requested modification of one or more PDFs. "
|
||||
"Use delegate_pdf_question for questions about the contents of the attached PDFs. "
|
||||
"Use delegate_user_spec for requests to create or define an agent spec. "
|
||||
"Use delegate_pdf_review when the user wants the PDF returned with review"
|
||||
" comments attached — anything like 'review this', 'annotate with comments',"
|
||||
" 'leave feedback on the PDF'. "
|
||||
"Use delegate_pdf_create when the user wants to generate a new document from"
|
||||
" scratch with no input file — invoices, reports, letters, contracts, etc. "
|
||||
"Use delegate_pdf_ingest for any request to convert a PDF to Markdown "
|
||||
"or extract its content as readable text. "
|
||||
"Consult each delegate tool's description and pick the single best fit. "
|
||||
"Use unsupported_capability when the user asks about the assistant itself "
|
||||
"or when none of the other outputs fit; supply a helpful message."
|
||||
),
|
||||
@@ -132,70 +77,23 @@ class OrchestratorAgent:
|
||||
return result.output
|
||||
|
||||
async def _resume(self, request: OrchestratorRequest, capability: SupportedCapability) -> OrchestratorResponse:
|
||||
"""Fast-path to get back to the correct endpoint without having to call AI.
|
||||
"""Fast-path back to the right delegate without consulting the LLM.
|
||||
|
||||
Also the entry point for the *multi-turn* flow where a delegate emits a plan with
|
||||
``resume_with`` set — Java runs the plan, captures any tool reports as artifacts, and
|
||||
re-enters via this method so the delegate can digest the reports.
|
||||
re-enters here so the delegate can digest the reports.
|
||||
"""
|
||||
match capability:
|
||||
case SupportedCapability.PDF_QUESTION:
|
||||
return await self._run_pdf_question(request)
|
||||
case SupportedCapability.PDF_REVIEW:
|
||||
return await self._run_pdf_review(request)
|
||||
case SupportedCapability.PDF_EDIT:
|
||||
return await self._run_pdf_edit(request)
|
||||
case SupportedCapability.AGENT_DRAFT:
|
||||
return await self._run_agent_draft(request)
|
||||
case SupportedCapability.PDF_CREATE:
|
||||
return await self._run_pdf_create(request)
|
||||
case (
|
||||
SupportedCapability.ORCHESTRATE
|
||||
| SupportedCapability.AGENT_REVISE
|
||||
| SupportedCapability.AGENT_NEXT_ACTION
|
||||
| SupportedCapability.MATH_AUDITOR_AGENT
|
||||
):
|
||||
raise ValueError(f"Cannot resume orchestrator with capability: {capability}")
|
||||
case _ as unreachable:
|
||||
assert_never(unreachable)
|
||||
|
||||
async def delegate_pdf_edit(self, ctx: RunContext[OrchestratorDeps]) -> PdfEditResponse:
|
||||
return await self._run_pdf_edit(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_edit(self, request: OrchestratorRequest) -> PdfEditResponse:
|
||||
return await PdfEditAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def delegate_pdf_question(self, ctx: RunContext[OrchestratorDeps]) -> PdfQuestionOrchestrateResponse:
|
||||
return await self._run_pdf_question(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_question(self, request: OrchestratorRequest) -> PdfQuestionOrchestrateResponse:
|
||||
return await PdfQuestionAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def delegate_user_spec(self, ctx: RunContext[OrchestratorDeps]) -> AgentDraftWorkflowResponse:
|
||||
return await self._run_agent_draft(ctx.deps.request)
|
||||
|
||||
async def _run_agent_draft(self, request: OrchestratorRequest) -> AgentDraftWorkflowResponse:
|
||||
return await UserSpecAgent(self.runtime).orchestrate(request)
|
||||
route = self._delegates_by_capability.get(capability)
|
||||
if route is None:
|
||||
raise ValueError(f"Cannot resume orchestrator with capability: {capability}")
|
||||
return await route.orchestrate(request)
|
||||
|
||||
async def delegate_pdf_ingest(self, ctx: RunContext[OrchestratorDeps]) -> ConvertMarkdownResponse:
|
||||
request = ctx.deps.request
|
||||
return ConvertMarkdownResponse(
|
||||
reason="PDF to Markdown requested — Java converts deterministically.",
|
||||
files_to_ingest=request.files,
|
||||
files_to_ingest=ctx.deps.request.files,
|
||||
)
|
||||
|
||||
async def delegate_pdf_review(self, ctx: RunContext[OrchestratorDeps]) -> PdfReviewOrchestrateResponse:
|
||||
return await self._run_pdf_review(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_review(self, request: OrchestratorRequest) -> PdfReviewOrchestrateResponse:
|
||||
return await PdfReviewAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def delegate_pdf_create(self, ctx: RunContext[OrchestratorDeps]) -> PdfCreateOrchestrateResponse:
|
||||
return await self._run_pdf_create(ctx.deps.request)
|
||||
|
||||
async def _run_pdf_create(self, request: OrchestratorRequest) -> PdfCreateOrchestrateResponse:
|
||||
return await PdfCreateAgent(self.runtime).orchestrate(request)
|
||||
|
||||
async def unsupported_capability(
|
||||
self,
|
||||
ctx: RunContext[OrchestratorDeps],
|
||||
|
||||
@@ -20,6 +20,7 @@ import logging
|
||||
from pydantic import Field
|
||||
from pydantic_ai import Agent
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, RegisterableAgent
|
||||
from stirling.agents.pdf_comment.prompts import COMMENT_AGENT_SYSTEM_PROMPT
|
||||
from stirling.contracts.pdf_comments import (
|
||||
MAX_COMMENT_TEXT_LENGTH,
|
||||
@@ -66,7 +67,7 @@ class LlmCommentOutput(ApiModel):
|
||||
rationale: str = Field(max_length=1_000)
|
||||
|
||||
|
||||
class PdfCommentAgent:
|
||||
class PdfCommentAgent(RegisterableAgent):
|
||||
"""Encapsulates the single-shot PDF comment generation pipeline.
|
||||
|
||||
Instantiated once at app startup with an :class:`AppRuntime`, which
|
||||
@@ -82,6 +83,22 @@ class PdfCommentAgent:
|
||||
model_settings=runtime.fast_model_settings,
|
||||
)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
# MCP-only: invoked as a tool inside the PDF review plan, never a
|
||||
# top-level orchestrator delegate.
|
||||
return AgentDescriptor(
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="pdf-comment-generate",
|
||||
description="Generate inline review comments for a PDF document.",
|
||||
input_model=PdfCommentRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-comment/generate",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def generate(self, request: PdfCommentRequest) -> PdfCommentResponse:
|
||||
"""Run the agent against a ``PdfCommentRequest`` and return comments.
|
||||
|
||||
|
||||
@@ -28,10 +28,12 @@ from jinja2 import Environment, FileSystemLoader
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.contracts import (
|
||||
EditCannotDoResponse,
|
||||
EditPlanResponse,
|
||||
OrchestratorRequest,
|
||||
SupportedCapability,
|
||||
ToolOperationStep,
|
||||
format_conversation_history,
|
||||
)
|
||||
@@ -317,7 +319,7 @@ def _safe_filename(title: str) -> str:
|
||||
# ── Agent ─────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class PdfCreateAgent:
|
||||
class PdfCreateAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self._jinja_env = _build_jinja_env()
|
||||
@@ -343,6 +345,21 @@ class PdfCreateAgent:
|
||||
model_settings={**runtime.smart_model_settings, "temperature": 0.3},
|
||||
)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_CREATE,
|
||||
tool_name="delegate_pdf_create",
|
||||
tool_description=(
|
||||
"Delegate requests to create a new PDF document from scratch based on a"
|
||||
" description. Use this when the user wants to generate a new document"
|
||||
" (e.g. 'create an invoice', 'write a report', 'make a contract',"
|
||||
" 'draft a letter'). No input file is required."
|
||||
),
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> PdfCreateOrchestrateResponse:
|
||||
history = format_conversation_history(request.conversation_history)
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._page_text import format_page_text, get_extracted_text_artifact, has_page_text
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.contracts import (
|
||||
EditCannotDoResponse,
|
||||
EditClarificationRequest,
|
||||
@@ -171,11 +172,35 @@ class PdfEditParameterSelector:
|
||||
)
|
||||
|
||||
|
||||
class PdfEditAgent:
|
||||
class PdfEditAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self.parameter_selector = PdfEditParameterSelector(runtime)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_EDIT,
|
||||
tool_name="delegate_pdf_edit",
|
||||
tool_description="Delegate any requested modification of one or more PDFs; returns the edit result.",
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="pdf-edit-plan",
|
||||
description=(
|
||||
"Produce an edit plan (a structured sequence of PDF operations) from a"
|
||||
" natural-language edit request. The plan is executed by Java through the job"
|
||||
" pipeline; this capability does not modify files itself."
|
||||
),
|
||||
input_model=PdfEditRequest,
|
||||
mode="async",
|
||||
required_scope="mcp.tools.write",
|
||||
route="/api/v1/pdf-edit",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> PdfEditResponse:
|
||||
"""Entry point for the orchestrator delegate — adapts the orchestrator's
|
||||
request shape into a :class:`PdfEditRequest` and runs the standard
|
||||
|
||||
@@ -5,6 +5,7 @@ import logging
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.agents.contradiction import ContradictionCapability, ContradictionDetector
|
||||
from stirling.agents.math_presentation import MathIntentClassifier, extract_math_verdict
|
||||
from stirling.agents.shared import ChunkedReasoner, WholeDocReaderCapability
|
||||
@@ -85,7 +86,7 @@ _MATH_SYNTH_SYSTEM_PROMPT = (
|
||||
)
|
||||
|
||||
|
||||
class PdfQuestionAgent:
|
||||
class PdfQuestionAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self._math_synth_agent: Agent[None, str] = Agent(
|
||||
@@ -103,6 +104,26 @@ class PdfQuestionAgent:
|
||||
# (mirrors the chunked-reasoner pattern).
|
||||
self._contradiction_detector = ContradictionDetector(runtime)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_QUESTION,
|
||||
tool_name="delegate_pdf_question",
|
||||
tool_description="Delegate questions about the contents of the attached PDFs; returns the answer.",
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="pdf-question-answer",
|
||||
description="Answer a natural-language question about a PDF document.",
|
||||
input_model=PdfQuestionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-question",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def handle(self, request: PdfQuestionRequest) -> PdfQuestionResponse:
|
||||
logger.info(
|
||||
"[pdf-question] handle: files=%s question=%r",
|
||||
|
||||
@@ -31,6 +31,7 @@ from typing import Literal
|
||||
from pydantic import Field
|
||||
from pydantic_ai import Agent
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.agents.contradiction import ContradictionDetector, ContradictionIntentClassifier
|
||||
from stirling.agents.contradiction.detector import _escape_for_tag
|
||||
from stirling.agents.contradiction.prompts import REVIEW_LOCALISER_PROMPT
|
||||
@@ -104,7 +105,7 @@ class _LocalisedContradictionReport(ApiModel):
|
||||
comments: list[_PairedLocalisedContradiction] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PdfReviewAgent:
|
||||
class PdfReviewAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self._localiser_agent: Agent[None, _LocalisedVerdict] = Agent(
|
||||
@@ -128,6 +129,21 @@ class PdfReviewAgent:
|
||||
# request's stages.
|
||||
self._contradiction_detector = ContradictionDetector(runtime)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.PDF_REVIEW,
|
||||
tool_name="delegate_pdf_review",
|
||||
tool_description=(
|
||||
"Delegate requests to review a PDF and leave review comments, notes, or"
|
||||
" sticky-note annotations on the document itself. Use this when the user"
|
||||
" wants the PDF returned with comments attached (e.g. 'review this',"
|
||||
" 'add review comments', 'flag unclear sentences', 'annotate with feedback')."
|
||||
),
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> PdfReviewOrchestrateResponse:
|
||||
"""Entry point for the orchestrator delegate.
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
from pydantic_ai import Agent
|
||||
from pydantic_ai.output import NativeOutput
|
||||
|
||||
from stirling.agents._registry import AgentDescriptor, McpCapability, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.agents.pdf_edit import PdfEditAgent
|
||||
from stirling.contracts import (
|
||||
AgentDraft,
|
||||
@@ -18,6 +19,7 @@ from stirling.contracts import (
|
||||
OrchestratorRequest,
|
||||
PdfEditRequest,
|
||||
PdfEditTerminalResponse,
|
||||
SupportedCapability,
|
||||
format_conversation_history,
|
||||
)
|
||||
from stirling.models import ApiModel
|
||||
@@ -30,7 +32,7 @@ class UserSpecMetadata(ApiModel):
|
||||
objective: str
|
||||
|
||||
|
||||
class UserSpecAgent:
|
||||
class UserSpecAgent(RegisterableAgent):
|
||||
def __init__(self, runtime: AppRuntime) -> None:
|
||||
self.runtime = runtime
|
||||
self.pdf_edit_agent = PdfEditAgent(runtime)
|
||||
@@ -45,6 +47,39 @@ class UserSpecAgent:
|
||||
model_settings=runtime.smart_model_settings,
|
||||
)
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=SupportedCapability.AGENT_DRAFT,
|
||||
tool_name="delegate_user_spec",
|
||||
tool_description="Delegate requests to create or define an agent spec; returns the draft result.",
|
||||
orchestrate=self.orchestrate,
|
||||
),
|
||||
mcp=(
|
||||
McpCapability(
|
||||
id="agent-draft",
|
||||
description=(
|
||||
"Draft a structured agent specification from a free-text description"
|
||||
" of the task the user wants automated."
|
||||
),
|
||||
input_model=AgentDraftRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/draft",
|
||||
),
|
||||
McpCapability(
|
||||
id="agent-revise",
|
||||
description=(
|
||||
"Revise an existing draft agent specification based on user feedback or constraint changes."
|
||||
),
|
||||
input_model=AgentRevisionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/revise",
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
async def orchestrate(self, request: OrchestratorRequest) -> AgentDraftWorkflowResponse:
|
||||
"""Entry point for the orchestrator delegate — adapts the orchestrator's
|
||||
request shape into an :class:`AgentDraftRequest` and runs the standard
|
||||
|
||||
@@ -1,160 +1,46 @@
|
||||
"""
|
||||
Curated registry of agent capabilities the MCP server (Java side) is allowed to publish.
|
||||
"""Serialize the MCP capabilities manifest the Java MCP server pulls at boot.
|
||||
|
||||
Internal sub-agents (currently only ``ExecutionPlanningAgent`` - it lives behind the orchestrator
|
||||
and has no end-user-facing API surface) are intentionally absent. The handoff spec calls for
|
||||
"user-facing" capabilities only; revisit this list when adding a new agent and ask whether MCP
|
||||
clients should be able to invoke it directly.
|
||||
The manifest is *derived* from the agent registry: every agent declares its
|
||||
exposed capabilities in ``describe()`` (see ``stirling.agents._registry``), and
|
||||
this module flattens the ``mcp`` rows of the startup descriptor list into the
|
||||
wire shape Java consumes. There is no separately maintained capability list to
|
||||
keep in sync — adding an MCP capability means adding an ``McpCapability`` to the
|
||||
owning agent's descriptor.
|
||||
|
||||
The Java side pulls ``/api/v1/agents/capabilities`` once at boot and again every few minutes; the
|
||||
manifest is the authoritative source for the ``stirling_ai`` MCP tool's operation enum.
|
||||
Curation note: exposure is opt-in. An agent is published to MCP only if its
|
||||
descriptor carries one or more ``McpCapability`` rows; registering an agent with
|
||||
the orchestrator does not auto-expose it over the (OAuth-scoped) MCP surface.
|
||||
|
||||
The Java side pulls ``/api/v1/agents/capabilities`` once at boot and again every
|
||||
few minutes; the manifest is the authoritative source for the ``stirling_ai`` MCP
|
||||
tool's operation enum.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from collections.abc import Iterable
|
||||
from typing import Any
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from stirling.contracts import (
|
||||
AgentDraftRequest,
|
||||
AgentExecutionRequest,
|
||||
AgentRevisionRequest,
|
||||
Evidence,
|
||||
FolioManifest,
|
||||
PdfCommentRequest,
|
||||
PdfEditRequest,
|
||||
PdfQuestionRequest,
|
||||
)
|
||||
from stirling.agents import AgentDescriptor
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentCapability:
|
||||
"""One row in the curated manifest.
|
||||
def manifest_payload(descriptors: Iterable[AgentDescriptor]) -> dict[str, Any]:
|
||||
"""Flatten the ``mcp`` rows of the descriptor list to the wire shape.
|
||||
|
||||
Attributes:
|
||||
id: stable capability identifier (used as the operation enum value in
|
||||
``stirling_ai``). Avoid renaming - clients persist these.
|
||||
description: one-line human-friendly summary shown inside MCP tool descriptions.
|
||||
input_model: Pydantic class whose JSON Schema becomes the capability's
|
||||
``input_schema``. Auto-derived; do not hand-write schemas.
|
||||
mode: ``"sync"`` if the capability returns content inline, ``"async"`` if it returns a
|
||||
plan that Java executes via the job pipeline.
|
||||
required_scope: coarse OAuth scope. ``mcp.tools.read`` for pure-read capabilities
|
||||
(Q&A, audits) and ``mcp.tools.write`` for anything that yields a plan / file.
|
||||
route: HTTP path Java POSTs to when invoking this capability. When a capability does
|
||||
not have a stable per-agent route yet, use the generic invoke fallback at
|
||||
``/api/v1/agents/invoke/{id}``.
|
||||
"""
|
||||
|
||||
id: str
|
||||
description: str
|
||||
input_model: type[BaseModel]
|
||||
mode: str
|
||||
required_scope: str
|
||||
route: str
|
||||
|
||||
|
||||
EXPOSED_CAPABILITIES: list[AgentCapability] = [
|
||||
AgentCapability(
|
||||
id="pdf-question-answer",
|
||||
description="Answer a natural-language question about a PDF document.",
|
||||
input_model=PdfQuestionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-question",
|
||||
),
|
||||
AgentCapability(
|
||||
id="pdf-edit-plan",
|
||||
description=(
|
||||
"Produce an edit plan (a structured sequence of PDF operations) from a"
|
||||
" natural-language edit request. The plan is executed by Java through the job"
|
||||
" pipeline; this capability does not modify files itself."
|
||||
),
|
||||
input_model=PdfEditRequest,
|
||||
mode="async",
|
||||
required_scope="mcp.tools.write",
|
||||
route="/api/v1/pdf-edit",
|
||||
),
|
||||
AgentCapability(
|
||||
id="agent-draft",
|
||||
description=(
|
||||
"Draft a structured agent specification from a free-text description of the task the user wants automated."
|
||||
),
|
||||
input_model=AgentDraftRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/draft",
|
||||
),
|
||||
AgentCapability(
|
||||
id="agent-revise",
|
||||
description=("Revise an existing draft agent specification based on user feedback or constraint changes."),
|
||||
input_model=AgentRevisionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/revise",
|
||||
),
|
||||
AgentCapability(
|
||||
id="math-audit-examine",
|
||||
description=(
|
||||
"Examine a folio manifest of financial / numeric documents and surface the"
|
||||
" evidence that needs to be checked for arithmetic consistency."
|
||||
),
|
||||
input_model=FolioManifest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/examine",
|
||||
),
|
||||
AgentCapability(
|
||||
id="math-audit-deliberate",
|
||||
description=(
|
||||
"Render a deliberated verdict on a single piece of evidence the examine step"
|
||||
" surfaced (does the arithmetic check out, with what caveats)."
|
||||
),
|
||||
input_model=Evidence,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/deliberate",
|
||||
),
|
||||
AgentCapability(
|
||||
id="pdf-comment-generate",
|
||||
description="Generate inline review comments for a PDF document.",
|
||||
input_model=PdfCommentRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-comment/generate",
|
||||
),
|
||||
AgentCapability(
|
||||
id="agent-next-action",
|
||||
description=(
|
||||
"Decide the next execution step for an in-progress agent workflow. Returns a"
|
||||
" ToolCall, Completed, or CannotContinue action."
|
||||
),
|
||||
input_model=AgentExecutionRequest,
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/agents/next-action",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def manifest_payload() -> dict[str, Any]:
|
||||
"""Serialize the curated registry to the wire shape consumed by Java.
|
||||
|
||||
Schema is derived from ``input_model.model_json_schema()`` so we never hand-write JSON
|
||||
Schema - the Pydantic model is the single source of truth.
|
||||
Schema is derived from ``input_model.model_json_schema()`` so we never
|
||||
hand-write JSON Schema - the Pydantic model is the single source of truth.
|
||||
"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for cap in EXPOSED_CAPABILITIES:
|
||||
items.append(
|
||||
{
|
||||
"id": cap.id,
|
||||
"description": cap.description,
|
||||
"input_schema": cap.input_model.model_json_schema(),
|
||||
"mode": cap.mode,
|
||||
"required_scope": cap.required_scope,
|
||||
"route": cap.route,
|
||||
}
|
||||
)
|
||||
for descriptor in descriptors:
|
||||
for cap in descriptor.mcp:
|
||||
items.append(
|
||||
{
|
||||
"id": cap.id,
|
||||
"description": cap.description,
|
||||
"input_schema": cap.input_model.model_json_schema(),
|
||||
"mode": cap.mode,
|
||||
"required_scope": cap.required_scope,
|
||||
"route": cap.route,
|
||||
}
|
||||
)
|
||||
return {"version": 1, "capabilities": items}
|
||||
|
||||
@@ -12,9 +12,12 @@ from pydantic_ai.models.instrumented import InstrumentationSettings
|
||||
from stirling.agents import (
|
||||
ExecutionPlanningAgent,
|
||||
OrchestratorAgent,
|
||||
PdfCreateAgent,
|
||||
PdfEditAgent,
|
||||
PdfQuestionAgent,
|
||||
PdfReviewAgent,
|
||||
UserSpecAgent,
|
||||
build_descriptors,
|
||||
)
|
||||
from stirling.agents.ledger import MathAuditorAgent
|
||||
from stirling.agents.pdf_comment import PdfCommentAgent
|
||||
@@ -88,13 +91,28 @@ async def lifespan(fast_api: FastAPI):
|
||||
runtime = build_runtime(settings)
|
||||
fast_api.state.settings = settings
|
||||
fast_api.state.runtime = runtime
|
||||
fast_api.state.orchestrator_agent = OrchestratorAgent(runtime)
|
||||
fast_api.state.pdf_edit_agent = PdfEditAgent(runtime)
|
||||
fast_api.state.pdf_question_agent = PdfQuestionAgent(runtime)
|
||||
fast_api.state.pdf_review_agent = PdfReviewAgent(runtime)
|
||||
fast_api.state.pdf_create_agent = PdfCreateAgent(runtime)
|
||||
fast_api.state.user_spec_agent = UserSpecAgent(runtime)
|
||||
fast_api.state.execution_planning_agent = ExecutionPlanningAgent(runtime)
|
||||
fast_api.state.math_auditor_agent = MathAuditorAgent(runtime)
|
||||
fast_api.state.pdf_comment_agent = PdfCommentAgent(runtime)
|
||||
# One descriptor list drives both orchestrator routing and the MCP manifest.
|
||||
fast_api.state.agent_descriptors = build_descriptors(
|
||||
[
|
||||
fast_api.state.pdf_edit_agent,
|
||||
fast_api.state.pdf_question_agent,
|
||||
fast_api.state.user_spec_agent,
|
||||
fast_api.state.pdf_review_agent,
|
||||
fast_api.state.pdf_create_agent,
|
||||
fast_api.state.pdf_comment_agent,
|
||||
fast_api.state.math_auditor_agent,
|
||||
fast_api.state.execution_planning_agent,
|
||||
]
|
||||
)
|
||||
fast_api.state.orchestrator_agent = OrchestratorAgent(runtime, fast_api.state.agent_descriptors)
|
||||
tracer_provider = setup_posthog_tracking(settings)
|
||||
if tracer_provider:
|
||||
Agent.instrument_all(InstrumentationSettings(tracer_provider=tracer_provider))
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from stirling.api.agent_capabilities import manifest_payload
|
||||
|
||||
@@ -12,11 +12,11 @@ router = APIRouter(prefix="/api/v1/agents", tags=["agents"])
|
||||
|
||||
|
||||
@router.get("/capabilities")
|
||||
def get_capabilities() -> dict[str, Any]:
|
||||
"""Return the curated agent capabilities manifest.
|
||||
def get_capabilities(request: Request) -> dict[str, Any]:
|
||||
"""Return the agent capabilities manifest, derived from the startup registry.
|
||||
|
||||
Gated by ``EngineSharedSecretMiddleware`` when the ``STIRLING_ENGINE_SHARED_SECRET`` env var
|
||||
is configured. In dev/local mode (no secret set), the endpoint is open - the engine binds to
|
||||
localhost only by default, so this is acceptable while iterating.
|
||||
"""
|
||||
return manifest_payload()
|
||||
return manifest_payload(request.app.state.agent_descriptors)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""
|
||||
Orchestrator ``delegate_pdf_review`` contract test.
|
||||
PDF-review delegate contract test.
|
||||
|
||||
The real orchestrator delegates PDF-review requests via a pydantic-ai tool
|
||||
output. Exercising the full ``agent.run(...)`` call would hit the LLM and
|
||||
requires building a real ``RunContext`` — so instead this test invokes
|
||||
``delegate_pdf_review`` directly with a minimal ``deps`` stand-in. That's
|
||||
enough to verify the wire contract the orchestrator produces:
|
||||
The orchestrator routes PDF-review requests to ``PdfReviewAgent.orchestrate``
|
||||
(the orchestrator merely selects the delegate; the review logic lives on the
|
||||
agent). Exercising the agent directly avoids the LLM routing call and verifies
|
||||
the wire contract the delegate produces for a plain prose-review request:
|
||||
|
||||
* it returns an ``EditPlanResponse``;
|
||||
* with exactly one step;
|
||||
@@ -16,13 +15,11 @@ enough to verify the wire contract the orchestrator produces:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from stirling.agents import OrchestratorAgent
|
||||
from stirling.agents import PdfReviewAgent
|
||||
from stirling.contracts import AiFile, OrchestratorRequest
|
||||
from stirling.contracts.pdf_edit import EditPlanResponse
|
||||
from stirling.models import FileId
|
||||
@@ -30,27 +27,28 @@ from stirling.models.agent_tool_models import AgentToolId, PdfCommentAgentParams
|
||||
from stirling.services.runtime import AppRuntime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _FakeDeps:
|
||||
request: OrchestratorRequest
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_review_wires_prompt_to_tool_step(runtime: AppRuntime) -> None:
|
||||
orchestrator = OrchestratorAgent(runtime)
|
||||
async def test_pdf_review_wires_prompt_to_tool_step(runtime: AppRuntime) -> None:
|
||||
review_agent = PdfReviewAgent(runtime)
|
||||
request = OrchestratorRequest(
|
||||
user_message="please add review comments flagging ambiguous dates",
|
||||
files=[AiFile(id=FileId("contract-id"), name="contract.pdf")],
|
||||
)
|
||||
ctx = SimpleNamespace(deps=_FakeDeps(request=request))
|
||||
|
||||
# PdfReviewAgent now classifies math intent locally via a tiny LLM. Stub it
|
||||
# to false so this test stays focused on the prose-review wire contract.
|
||||
with patch(
|
||||
"stirling.agents.pdf_review.MathIntentClassifier.classify",
|
||||
new=AsyncMock(return_value=False),
|
||||
# PdfReviewAgent classifies math and contradiction intent locally via tiny
|
||||
# LLMs. Stub both to false so this test stays focused on the prose-review
|
||||
# wire contract.
|
||||
with (
|
||||
patch(
|
||||
"stirling.agents.pdf_review.MathIntentClassifier.classify",
|
||||
new=AsyncMock(return_value=False),
|
||||
),
|
||||
patch(
|
||||
"stirling.agents.pdf_review.ContradictionIntentClassifier.classify",
|
||||
new=AsyncMock(return_value=False),
|
||||
),
|
||||
):
|
||||
response = await orchestrator.delegate_pdf_review(ctx) # type: ignore[arg-type]
|
||||
response = await review_agent.orchestrate(request)
|
||||
|
||||
assert isinstance(response, EditPlanResponse)
|
||||
assert len(response.steps) == 1
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Behavioural lock: a scripted top-level tool call reaches the right delegate.
|
||||
|
||||
No real LLM — a :class:`FunctionModel` scripts the exact tool call the orchestrator
|
||||
would have received, and we assert which delegate handled it. Built on the real
|
||||
descriptor list (via ``build_descriptors``) with each agent's ``orchestrate``
|
||||
swapped for a recording spy, so the test stays honest to whatever agents are
|
||||
actually registered.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
from pydantic_ai.messages import ModelMessage, ModelResponse, ToolCallPart
|
||||
from pydantic_ai.models.function import AgentInfo, FunctionModel
|
||||
|
||||
from stirling.agents import OrchestratorAgent, build_descriptors
|
||||
from stirling.agents._registry import AgentDescriptor, OrchestratorRoute, RegisterableAgent
|
||||
from stirling.contracts import (
|
||||
ConvertMarkdownResponse,
|
||||
EditCannotDoResponse,
|
||||
EditPlanResponse,
|
||||
OrchestratorRequest,
|
||||
OrchestratorResponse,
|
||||
PdfQuestionNotFoundResponse,
|
||||
SupportedCapability,
|
||||
)
|
||||
from stirling.services.runtime import AppRuntime
|
||||
|
||||
_REACHED: list[SupportedCapability] = []
|
||||
|
||||
|
||||
class _SpyAgent(RegisterableAgent):
|
||||
"""Stand-in agent that reproduces a real delegate's tool surface but records
|
||||
the reach and returns a fixed sentinel instead of doing work."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
capability: SupportedCapability,
|
||||
tool_name: str,
|
||||
response: OrchestratorResponse,
|
||||
) -> None:
|
||||
self._capability = capability
|
||||
self._tool_name = tool_name
|
||||
self._response = response
|
||||
|
||||
def describe(self) -> AgentDescriptor:
|
||||
return AgentDescriptor(
|
||||
orchestrator=OrchestratorRoute(
|
||||
capability=self._capability,
|
||||
tool_name=self._tool_name,
|
||||
tool_description=f"spy for {self._tool_name}",
|
||||
orchestrate=self._orchestrate,
|
||||
),
|
||||
)
|
||||
|
||||
async def _orchestrate(self, _request: OrchestratorRequest) -> OrchestratorResponse:
|
||||
_REACHED.append(self._capability)
|
||||
return self._response
|
||||
|
||||
|
||||
def _spies() -> list[RegisterableAgent]:
|
||||
return [
|
||||
_SpyAgent(SupportedCapability.PDF_EDIT, "delegate_pdf_edit", EditCannotDoResponse(reason="spy")),
|
||||
_SpyAgent(
|
||||
SupportedCapability.PDF_QUESTION,
|
||||
"delegate_pdf_question",
|
||||
PdfQuestionNotFoundResponse(reason="spy"),
|
||||
),
|
||||
_SpyAgent(SupportedCapability.PDF_REVIEW, "delegate_pdf_review", EditPlanResponse(summary="", steps=[])),
|
||||
_SpyAgent(SupportedCapability.PDF_CREATE, "delegate_pdf_create", EditPlanResponse(summary="", steps=[])),
|
||||
]
|
||||
|
||||
|
||||
def _script(tool_name: str) -> Callable[[list[ModelMessage], AgentInfo], ModelResponse]:
|
||||
def call(_messages: list[ModelMessage], _info: AgentInfo) -> ModelResponse:
|
||||
return ModelResponse(parts=[ToolCallPart(tool_name=tool_name, args={})])
|
||||
|
||||
return call
|
||||
|
||||
|
||||
async def _route(runtime: AppRuntime, tool_name: str) -> OrchestratorResponse:
|
||||
_REACHED.clear()
|
||||
scripted = replace(runtime, fast_model=FunctionModel(_script(tool_name)))
|
||||
orchestrator = OrchestratorAgent(scripted, build_descriptors(_spies()))
|
||||
return await orchestrator.handle(OrchestratorRequest(user_message="x"))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_edit_reaches_edit_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_edit")
|
||||
assert _REACHED == [SupportedCapability.PDF_EDIT]
|
||||
assert isinstance(response, EditCannotDoResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_question_reaches_question_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_question")
|
||||
assert _REACHED == [SupportedCapability.PDF_QUESTION]
|
||||
assert isinstance(response, PdfQuestionNotFoundResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_review_reaches_review_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_review")
|
||||
assert _REACHED == [SupportedCapability.PDF_REVIEW]
|
||||
assert isinstance(response, EditPlanResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_create_reaches_create_delegate(runtime: AppRuntime) -> None:
|
||||
response = await _route(runtime, "delegate_pdf_create")
|
||||
assert _REACHED == [SupportedCapability.PDF_CREATE]
|
||||
assert isinstance(response, EditPlanResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_delegate_pdf_ingest_returns_convert_markdown(runtime: AppRuntime) -> None:
|
||||
# pdf_ingest is a canned inline orchestrator tool (no agent, never resumed) —
|
||||
# no reach recorded, just a deterministic convert response.
|
||||
response = await _route(runtime, "delegate_pdf_ingest")
|
||||
assert _REACHED == []
|
||||
assert isinstance(response, ConvertMarkdownResponse)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resume_dispatches_to_matching_delegate(runtime: AppRuntime) -> None:
|
||||
_REACHED.clear()
|
||||
orchestrator = OrchestratorAgent(runtime, build_descriptors(_spies()))
|
||||
await orchestrator.handle(OrchestratorRequest(user_message="x", resume_with=SupportedCapability.PDF_REVIEW))
|
||||
assert _REACHED == [SupportedCapability.PDF_REVIEW]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resume_with_unroutable_capability_raises(runtime: AppRuntime) -> None:
|
||||
# MATH_AUDITOR_AGENT is MCP-only — not an orchestrator delegate, so it has no
|
||||
# resumable route and resuming into it must raise.
|
||||
orchestrator = OrchestratorAgent(runtime, build_descriptors(_spies()))
|
||||
with pytest.raises(ValueError, match="Cannot resume"):
|
||||
await orchestrator.handle(
|
||||
OrchestratorRequest(user_message="x", resume_with=SupportedCapability.MATH_AUDITOR_AGENT)
|
||||
)
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Lock the MCP capabilities manifest wire shape.
|
||||
|
||||
Exercises the real ``GET /api/v1/agents/capabilities`` endpoint (so it covers the
|
||||
actual startup wiring of ``app.state.agent_descriptors``) and pins every
|
||||
capability's id, metadata, and Pydantic-derived input schema. The manifest is
|
||||
built by flattening each agent's ``describe()`` rows; this suite is the guard
|
||||
that the derived manifest never drifts from the published contract.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from conftest import build_app_settings
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import BaseModel
|
||||
|
||||
from stirling.api import app
|
||||
from stirling.config import load_settings
|
||||
from stirling.contracts import (
|
||||
AgentDraftRequest,
|
||||
AgentExecutionRequest,
|
||||
AgentRevisionRequest,
|
||||
Evidence,
|
||||
FolioManifest,
|
||||
PdfCommentRequest,
|
||||
PdfEditRequest,
|
||||
PdfQuestionRequest,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest() -> Iterator[dict[str, Any]]:
|
||||
# Force test settings for the lifespan (other suites pop this override, so we
|
||||
# can't rely on a module-level set), then enter the client as a context manager
|
||||
# so the lifespan runs and populates ``app.state.agent_descriptors`` — the
|
||||
# manifest is built from that real startup registration, not a duplicated list.
|
||||
app.dependency_overrides[load_settings] = build_app_settings
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
response = client.get("/api/v1/agents/capabilities")
|
||||
finally:
|
||||
app.dependency_overrides.pop(load_settings, None)
|
||||
assert response.status_code == 200
|
||||
yield response.json()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Expected:
|
||||
description: str
|
||||
mode: str
|
||||
required_scope: str
|
||||
route: str
|
||||
input_model: type[BaseModel]
|
||||
|
||||
|
||||
# Expected per-capability metadata, keyed by id. Order-independent on purpose —
|
||||
# Java consumes the manifest as a keyed operation registry, not a sequence.
|
||||
_EXPECTED: dict[str, _Expected] = {
|
||||
"pdf-question-answer": _Expected(
|
||||
description="Answer a natural-language question about a PDF document.",
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-question",
|
||||
input_model=PdfQuestionRequest,
|
||||
),
|
||||
"pdf-edit-plan": _Expected(
|
||||
description=(
|
||||
"Produce an edit plan (a structured sequence of PDF operations) from a"
|
||||
" natural-language edit request. The plan is executed by Java through the job"
|
||||
" pipeline; this capability does not modify files itself."
|
||||
),
|
||||
mode="async",
|
||||
required_scope="mcp.tools.write",
|
||||
route="/api/v1/pdf-edit",
|
||||
input_model=PdfEditRequest,
|
||||
),
|
||||
"agent-draft": _Expected(
|
||||
description=(
|
||||
"Draft a structured agent specification from a free-text description of the task the user wants automated."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/draft",
|
||||
input_model=AgentDraftRequest,
|
||||
),
|
||||
"agent-revise": _Expected(
|
||||
description="Revise an existing draft agent specification based on user feedback or constraint changes.",
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/agents/revise",
|
||||
input_model=AgentRevisionRequest,
|
||||
),
|
||||
"math-audit-examine": _Expected(
|
||||
description=(
|
||||
"Examine a folio manifest of financial / numeric documents and surface the"
|
||||
" evidence that needs to be checked for arithmetic consistency."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/examine",
|
||||
input_model=FolioManifest,
|
||||
),
|
||||
"math-audit-deliberate": _Expected(
|
||||
description=(
|
||||
"Render a deliberated verdict on a single piece of evidence the examine step"
|
||||
" surfaced (does the arithmetic check out, with what caveats)."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/ai/math-auditor-agent/deliberate",
|
||||
input_model=Evidence,
|
||||
),
|
||||
"pdf-comment-generate": _Expected(
|
||||
description="Generate inline review comments for a PDF document.",
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/pdf-comment/generate",
|
||||
input_model=PdfCommentRequest,
|
||||
),
|
||||
"agent-next-action": _Expected(
|
||||
description=(
|
||||
"Decide the next execution step for an in-progress agent workflow. Returns a"
|
||||
" ToolCall, Completed, or CannotContinue action."
|
||||
),
|
||||
mode="sync",
|
||||
required_scope="mcp.tools.read",
|
||||
route="/api/v1/agents/next-action",
|
||||
input_model=AgentExecutionRequest,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def test_manifest_version(manifest: dict[str, Any]) -> None:
|
||||
assert manifest["version"] == 1
|
||||
|
||||
|
||||
def test_manifest_exposes_exactly_the_expected_capabilities(manifest: dict[str, Any]) -> None:
|
||||
ids = {c["id"] for c in manifest["capabilities"]}
|
||||
assert ids == set(_EXPECTED)
|
||||
|
||||
|
||||
def test_manifest_capability_metadata_and_schema(manifest: dict[str, Any]) -> None:
|
||||
by_id = {c["id"]: c for c in manifest["capabilities"]}
|
||||
for cap_id, expected in _EXPECTED.items():
|
||||
entry = by_id[cap_id]
|
||||
assert entry["description"] == expected.description, cap_id
|
||||
assert entry["mode"] == expected.mode, cap_id
|
||||
assert entry["required_scope"] == expected.required_scope, cap_id
|
||||
assert entry["route"] == expected.route, cap_id
|
||||
assert entry["input_schema"] == expected.input_model.model_json_schema(), cap_id
|
||||
@@ -28,6 +28,7 @@ components = "Components"
|
||||
infrastructure = "Infrastructure"
|
||||
usage = "Usage & Billing"
|
||||
docs = "Developer Docs"
|
||||
procurement = "Procurement"
|
||||
settings = "Settings"
|
||||
|
||||
[shell.header]
|
||||
@@ -329,7 +330,11 @@ subtitle = "{{type}} · {{status}}"
|
||||
closeAriaLabel = "Close detail"
|
||||
usedBy = "Used by"
|
||||
notReferenced = "Not referenced by any policy, so it's safe to delete."
|
||||
docsUntracked = "Per-source document volume isn't tracked yet."
|
||||
documents = "Documents"
|
||||
docsTotal = "Total seen"
|
||||
docs24h = "Last 24h"
|
||||
docs30d = "Last 30 days"
|
||||
docsTrend = "Documents over the last 30 days"
|
||||
edit = "Edit"
|
||||
pause = "Pause"
|
||||
resume = "Resume"
|
||||
@@ -1806,3 +1811,75 @@ body = "Your Stirling account session has expired. Sign in again to view billing
|
||||
loadWallet = "Couldn't load wallet"
|
||||
openStripePortal = "Couldn't open Stripe portal"
|
||||
walletUnavailable = "Wallet unavailable: {{status}} {{statusText}}"
|
||||
|
||||
[procurement]
|
||||
title = "Procurement"
|
||||
subtitle = "Get your team evaluated, contracted, and onboarded. Every document in one place."
|
||||
enterpriseBadge = "Enterprise"
|
||||
|
||||
[procurement.journey]
|
||||
eyebrow = "Your rollout"
|
||||
title = "From trial to live, one guided path"
|
||||
subtitle = "Your solutions engineer is on every step. One next action at a time; the full checklist is below."
|
||||
engineerLabel = "Your solutions engineer"
|
||||
trialTitle = "Enterprise trial"
|
||||
daysLeft_one = "{{count}} day left"
|
||||
daysLeft_other = "{{count}} days left"
|
||||
live = "You're live on Stirling Enterprise"
|
||||
nextStep = "Next step: {{action}}"
|
||||
|
||||
[procurement.docs]
|
||||
title = "Documents"
|
||||
subtitle = "Everything you need at each step of the journey, surfaced as the deal moves through it."
|
||||
here = "You're here"
|
||||
done = "Done"
|
||||
count_one = "{{count}} doc"
|
||||
count_other = "{{count}} docs"
|
||||
supportingTitle = "Supporting your evaluation"
|
||||
supportingSubtitle = "SOC 2, security reviews, tax forms and more, ready when your security or procurement team asks. Some carry a one-time fee."
|
||||
show = "Show"
|
||||
hide = "Hide"
|
||||
optional = "Optional"
|
||||
paidAddon = "Paid add-on"
|
||||
upcoming = "Upcoming"
|
||||
|
||||
[procurement.status]
|
||||
available = "Available"
|
||||
action = "Action needed"
|
||||
pending = "Pending"
|
||||
request = "On request"
|
||||
complete = "Complete"
|
||||
|
||||
[procurement.action]
|
||||
download = "Download"
|
||||
sign = "Review & sign"
|
||||
pay = "Pay now"
|
||||
upload = "Upload"
|
||||
request = "Request"
|
||||
|
||||
[procurement.modal]
|
||||
cancel = "Cancel"
|
||||
chooseFile = "Choose file"
|
||||
noFile = "No file selected"
|
||||
signTitle = "Review and sign your agreement"
|
||||
signBody = "Opens the Stirling Enterprise Agreement for e-signature: one signature covers the MSA, order form, EULA and DPA. We countersign automatically and you advance to payment."
|
||||
signCta = "Open for signature"
|
||||
payTitle = "Confirm payment"
|
||||
payBody = "Pay your committed contract by card or bank transfer through Stripe. Your workspace provisions as soon as payment clears."
|
||||
payCta = "Continue to Stripe"
|
||||
uploadTitle = "Upload your purchase order"
|
||||
uploadBody = "Send us your PO and we invoice against it on your terms. Drag in the PDF or pick a file below."
|
||||
uploadCta = "Upload purchase order"
|
||||
requestTitle = "Request this document"
|
||||
requestBodyPaid = "This is a paid add-on. Confirm and your solutions engineer will scope it and send the paperwork."
|
||||
requestBodyFree = "We generate this on demand. Confirm and your solutions engineer will send it across shortly."
|
||||
requestCta = "Request"
|
||||
downloadTitle = "Download"
|
||||
downloadBody = "Your download will begin shortly."
|
||||
downloadCta = "Download"
|
||||
|
||||
[procurement.locked]
|
||||
eyebrow = "Enterprise only"
|
||||
title = "The procurement track opens with Enterprise"
|
||||
description = "Trial keys, committed-volume quotes, the one-signature agreement, payment, and your document ledger all live here once you start an enterprise evaluation."
|
||||
talkToSales = "Talk to sales"
|
||||
|
||||
@@ -11,6 +11,7 @@ import { EditorAdmin } from "@portal/views/EditorAdmin";
|
||||
import { Infrastructure } from "@portal/views/Infrastructure";
|
||||
import { Usage } from "@portal/views/Usage";
|
||||
import { DeveloperDocs } from "@portal/views/DeveloperDocs";
|
||||
import { Procurement } from "@portal/views/Procurement";
|
||||
import { VIEW_PATHS } from "@portal/contexts/ViewContext";
|
||||
|
||||
export function ViewRouter() {
|
||||
@@ -27,6 +28,7 @@ export function ViewRouter() {
|
||||
<Route path={VIEW_PATHS.editor} element={<EditorAdmin />} />
|
||||
<Route path={VIEW_PATHS.infrastructure} element={<Infrastructure />} />
|
||||
<Route path={VIEW_PATHS.usage} element={<Usage />} />
|
||||
<Route path={VIEW_PATHS.procurement} element={<Procurement />} />
|
||||
<Route path={VIEW_PATHS.docs} element={<DeveloperDocs />} />
|
||||
{/* Account-link is now a Settings panel; redirect legacy bookmarks home. */}
|
||||
<Route path="/account-link" element={<Navigate to="/" replace />} />
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { apiClient } from "@portal/api/http";
|
||||
import type { Tier } from "@portal/contexts/TierContext";
|
||||
import type {
|
||||
DealStage,
|
||||
DocAction,
|
||||
ProcurementResponse,
|
||||
} from "@portal/mocks/procurement";
|
||||
|
||||
export type {
|
||||
Deal,
|
||||
DealStage,
|
||||
DocAction,
|
||||
DocStatus,
|
||||
JourneyStep,
|
||||
LedgerDoc,
|
||||
LedgerGroup,
|
||||
ProcurementResponse,
|
||||
QuoteInfo,
|
||||
SolutionsEngineer,
|
||||
SupportingCategory,
|
||||
SupportingGroup,
|
||||
TrialInfo,
|
||||
} from "@portal/mocks/procurement";
|
||||
export { JOURNEY } from "@portal/mocks/procurement";
|
||||
|
||||
/** GET /v1/procurement?tier=…, the deal, journey, ledger and supporting pool. */
|
||||
export async function fetchProcurement(
|
||||
tier: Tier,
|
||||
): Promise<ProcurementResponse> {
|
||||
return apiClient.local.json<ProcurementResponse>(
|
||||
`/v1/procurement?tier=${encodeURIComponent(tier)}`,
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
* Commercial actions. Each mutates the deal server-side and returns the updated
|
||||
* ProcurementResponse, the new canonical state, which the view applies so the
|
||||
* journey progresses. The MSW layer answers these today; a real backend honours
|
||||
* the same contracts unchanged.
|
||||
*/
|
||||
|
||||
/** Advance the deal to the next stage (the journey's primary CTA). */
|
||||
export async function advanceStage(
|
||||
fromStage: DealStage,
|
||||
): Promise<ProcurementResponse> {
|
||||
return apiClient.local.json<ProcurementResponse>("/v1/procurement/advance", {
|
||||
method: "POST",
|
||||
body: { fromStage },
|
||||
});
|
||||
}
|
||||
|
||||
/** Sign the Stirling Enterprise Agreement (MSA + order form + EULA + DPA). */
|
||||
export async function signAgreement(
|
||||
docId: string,
|
||||
): Promise<ProcurementResponse> {
|
||||
// A real backend opens an e-signature envelope and completes on callback;
|
||||
// here it completes immediately and advances the deal.
|
||||
return apiClient.local.json<ProcurementResponse>("/v1/procurement/sign", {
|
||||
method: "POST",
|
||||
body: { docId },
|
||||
});
|
||||
}
|
||||
|
||||
/** Pay the contract online (card / bank transfer via Stripe). */
|
||||
export async function payOnline(): Promise<ProcurementResponse> {
|
||||
return apiClient.local.json<ProcurementResponse>("/v1/procurement/pay", {
|
||||
method: "POST",
|
||||
});
|
||||
}
|
||||
|
||||
/** Upload a purchase order to invoice against (an alternate payment path). */
|
||||
export async function uploadPurchaseOrder(
|
||||
file: File,
|
||||
): Promise<ProcurementResponse> {
|
||||
// A real backend takes the PO as multipart; the mock only needs the name.
|
||||
return apiClient.local.json<ProcurementResponse>(
|
||||
"/v1/procurement/purchase-order",
|
||||
{
|
||||
method: "POST",
|
||||
body: { fileName: file.name },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Request a document that is generated on demand (some carry a one-off fee). */
|
||||
export async function requestDocument(
|
||||
docId: string,
|
||||
action: DocAction,
|
||||
): Promise<ProcurementResponse> {
|
||||
return apiClient.local.json<ProcurementResponse>(
|
||||
`/v1/procurement/documents/${encodeURIComponent(docId)}/request`,
|
||||
{ method: "POST", body: { action } },
|
||||
);
|
||||
}
|
||||
@@ -28,8 +28,10 @@ export interface SourceView {
|
||||
referenceCount: number;
|
||||
referencingPolicies: SourcePolicyRef[];
|
||||
config: SourceDetailRow[];
|
||||
/** Per-source document volume: not tracked yet (always null for now). */
|
||||
docsTotal: number | null;
|
||||
/** Documents this source has fed into runs: lifetime, plus trailing 24h / 30d windows. */
|
||||
docsTotal: number;
|
||||
docs24h: number;
|
||||
docs30d: number;
|
||||
}
|
||||
|
||||
export interface SourceKpi {
|
||||
@@ -69,6 +71,17 @@ export async function fetchSource(id: string): Promise<Source> {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/v1/sources/{id}/document-counts: the trailing 30-day daily document
|
||||
* series (oldest first) for the source's sparkline. Fetched only for the expanded
|
||||
* row, so the overview list stays lightweight.
|
||||
*/
|
||||
export async function fetchSourceDocCounts(id: string): Promise<number[]> {
|
||||
return apiClient.local.json<number[]>(
|
||||
`/api/v1/sources/${encodeURIComponent(id)}/document-counts`,
|
||||
);
|
||||
}
|
||||
|
||||
/** POST /api/v1/sources: create (blank id) or update (matched id) a source. */
|
||||
export async function createSource(source: Source): Promise<Source> {
|
||||
return apiClient.local.json<Source>("/api/v1/sources", {
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
UsageIcon,
|
||||
LinkIcon,
|
||||
DocsIcon,
|
||||
ProcurementIcon,
|
||||
SettingsIcon,
|
||||
ChevronDownIcon,
|
||||
} from "@portal/components/icons";
|
||||
@@ -135,8 +136,16 @@ export function Sidebar() {
|
||||
const { activeView, setActiveView } = useView();
|
||||
const { theme } = useTheme();
|
||||
const { openSettings } = useUI();
|
||||
const { tier } = useTier();
|
||||
const { t } = useTranslation();
|
||||
|
||||
// Procurement is the enterprise buyer's commercial journey — surfaced only to
|
||||
// enterprise tenants (it has no free/pro equivalent).
|
||||
const platformGroup: NavEntry[] =
|
||||
tier === "enterprise"
|
||||
? [{ id: "procurement", icon: <ProcurementIcon /> }, ...GROUP_PLATFORM]
|
||||
: GROUP_PLATFORM;
|
||||
|
||||
function renderGroup(entries: NavEntry[]) {
|
||||
return entries.map((entry) => (
|
||||
<NavItem
|
||||
@@ -218,7 +227,7 @@ export function Sidebar() {
|
||||
</div>
|
||||
<div className="portal-sidebar__divider" aria-hidden />
|
||||
<div className="portal-sidebar__group">
|
||||
{renderGroup(GROUP_PLATFORM)}
|
||||
{renderGroup(platformGroup)}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
|
||||
@@ -244,6 +244,16 @@ export function AgentBuilderIcon(props: IconProps) {
|
||||
);
|
||||
}
|
||||
|
||||
export function ProcurementIcon(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
<polyline points="14 2 14 8 20 8" />
|
||||
<path d="m9 15 2 2 4-4" />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function LinkIcon(props: IconProps) {
|
||||
return (
|
||||
<Svg {...props}>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { ActionModal } from "@portal/components/procurement/ActionModal";
|
||||
import type { LedgerDoc } from "@portal/api/procurement";
|
||||
import "@portal/views/Procurement.css";
|
||||
|
||||
const meta: Meta<typeof ActionModal> = {
|
||||
title: "Portal/Procurement/ActionModal",
|
||||
component: ActionModal,
|
||||
parameters: { layout: "fullscreen" },
|
||||
args: { onClose: () => {}, onDone: () => {} },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof ActionModal>;
|
||||
|
||||
const sign: LedgerDoc = {
|
||||
id: "d1",
|
||||
name: "Stirling Enterprise Agreement",
|
||||
sub: "One signature: MSA + order form + EULA + DPA.",
|
||||
status: "action",
|
||||
action: "sign",
|
||||
};
|
||||
|
||||
const pay: LedgerDoc = {
|
||||
id: "d2",
|
||||
name: "Pay online",
|
||||
sub: "Card or bank transfer via Stripe.",
|
||||
status: "pending",
|
||||
action: "pay",
|
||||
};
|
||||
|
||||
const upload: LedgerDoc = {
|
||||
id: "d3",
|
||||
name: "Purchase order",
|
||||
sub: "Upload it and we invoice against it.",
|
||||
status: "request",
|
||||
action: "upload",
|
||||
};
|
||||
|
||||
const requestPaid: LedgerDoc = {
|
||||
id: "d4",
|
||||
name: "Custom security review",
|
||||
sub: "Dedicated session with our security team.",
|
||||
status: "request",
|
||||
action: "request",
|
||||
fee: 5_000,
|
||||
};
|
||||
|
||||
export const Sign: Story = { args: { doc: sign } };
|
||||
export const Pay: Story = { args: { doc: pay } };
|
||||
export const UploadPO: Story = { args: { doc: upload } };
|
||||
export const RequestPaid: Story = { args: { doc: requestPaid } };
|
||||
@@ -0,0 +1,166 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { TFunction } from "i18next";
|
||||
import { Button, Modal } from "@shared/components";
|
||||
import type { LedgerDoc, ProcurementResponse } from "@portal/api/procurement";
|
||||
import {
|
||||
payOnline,
|
||||
requestDocument,
|
||||
signAgreement,
|
||||
uploadPurchaseOrder,
|
||||
} from "@portal/api/procurement";
|
||||
import { USD } from "@portal/components/procurement/format";
|
||||
|
||||
interface ActionCopy {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
body: string;
|
||||
cta: string;
|
||||
}
|
||||
|
||||
/** Per-action confirmation copy, with the fee folded into the CTA when present. */
|
||||
function actionCopy(doc: LedgerDoc, t: TFunction): ActionCopy {
|
||||
const fee = doc.fee !== undefined ? ` · ${USD.format(doc.fee)}` : "";
|
||||
switch (doc.action) {
|
||||
case "sign":
|
||||
return {
|
||||
title: t("procurement.modal.signTitle"),
|
||||
subtitle: doc.name,
|
||||
body: t("procurement.modal.signBody"),
|
||||
cta: t("procurement.modal.signCta"),
|
||||
};
|
||||
case "pay":
|
||||
return {
|
||||
title: t("procurement.modal.payTitle"),
|
||||
subtitle: doc.name,
|
||||
body: t("procurement.modal.payBody"),
|
||||
cta: t("procurement.modal.payCta"),
|
||||
};
|
||||
case "upload":
|
||||
return {
|
||||
title: t("procurement.modal.uploadTitle"),
|
||||
subtitle: doc.name,
|
||||
body: t("procurement.modal.uploadBody"),
|
||||
cta: t("procurement.modal.uploadCta"),
|
||||
};
|
||||
case "request":
|
||||
return {
|
||||
title: t("procurement.modal.requestTitle"),
|
||||
subtitle: doc.name,
|
||||
body: doc.fee
|
||||
? t("procurement.modal.requestBodyPaid")
|
||||
: t("procurement.modal.requestBodyFree"),
|
||||
cta: `${t("procurement.modal.requestCta")}${fee}`,
|
||||
};
|
||||
default:
|
||||
return {
|
||||
title: t("procurement.modal.downloadTitle"),
|
||||
subtitle: doc.name,
|
||||
body: t("procurement.modal.downloadBody"),
|
||||
cta: t("procurement.modal.downloadCta"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirmation modal for a document's gating action. Owns its in-flight state;
|
||||
* on success it hands the updated deal back to the caller via `onDone` so the
|
||||
* journey re-renders. Downloads are client-side and just close the modal.
|
||||
*/
|
||||
export function ActionModal({
|
||||
doc,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
doc: LedgerDoc | null;
|
||||
onClose: () => void;
|
||||
onDone: (next: ProcurementResponse) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
|
||||
if (!doc) return null;
|
||||
const copy = actionCopy(doc, t);
|
||||
const needsFile = doc.action === "upload";
|
||||
|
||||
async function submit() {
|
||||
if (!doc) return;
|
||||
setSubmitting(true);
|
||||
try {
|
||||
let next: ProcurementResponse | null = null;
|
||||
switch (doc.action) {
|
||||
case "sign":
|
||||
next = await signAgreement(doc.id);
|
||||
break;
|
||||
case "pay":
|
||||
next = await payOnline();
|
||||
break;
|
||||
case "upload":
|
||||
if (file) next = await uploadPurchaseOrder(file);
|
||||
break;
|
||||
case "request":
|
||||
next = await requestDocument(doc.id, doc.action);
|
||||
break;
|
||||
default:
|
||||
// download is client-side; no state change.
|
||||
break;
|
||||
}
|
||||
setFile(null);
|
||||
if (next) onDone(next);
|
||||
else onClose();
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onClose={onClose}
|
||||
width="md"
|
||||
title={copy.title}
|
||||
subtitle={copy.subtitle}
|
||||
footer={
|
||||
<div className="portal-proc__modal-actions">
|
||||
<Button variant="ghost" onClick={onClose}>
|
||||
{t("procurement.modal.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="gradient"
|
||||
accent="purple"
|
||||
loading={submitting}
|
||||
disabled={needsFile && !file}
|
||||
onClick={submit}
|
||||
>
|
||||
{copy.cta}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<p className="portal-proc__modal-body">{copy.body}</p>
|
||||
{needsFile && (
|
||||
<div className="portal-proc__upload">
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept=".pdf,.doc,.docx"
|
||||
className="portal-proc__upload-input"
|
||||
onChange={(e) => setFile(e.target.files?.[0] ?? null)}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
>
|
||||
{t("procurement.modal.chooseFile")}
|
||||
</Button>
|
||||
<span className="portal-proc__upload-name">
|
||||
{file ? file.name : t("procurement.modal.noFile")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { DealJourney } from "@portal/components/procurement/DealJourney";
|
||||
import { buildProcurement } from "@portal/mocks/procurement";
|
||||
import type { Deal } from "@portal/api/procurement";
|
||||
import "@portal/views/Procurement.css";
|
||||
|
||||
const data = buildProcurement("enterprise");
|
||||
const deal = data.deal as Deal;
|
||||
|
||||
const meta: Meta<typeof DealJourney> = {
|
||||
title: "Portal/Procurement/DealJourney",
|
||||
component: DealJourney,
|
||||
parameters: { layout: "padded" },
|
||||
args: { deal, journey: data.journey, onAdvance: () => {} },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof DealJourney>;
|
||||
|
||||
// Mid-journey at the Agreement stage, the seeded deal state.
|
||||
export const Default: Story = {};
|
||||
|
||||
// Evaluating: the trial strip shows runway + key; next step builds the quote.
|
||||
export const AtTrial: Story = {
|
||||
args: { deal: { ...deal, currentStage: "trial" } },
|
||||
};
|
||||
|
||||
// Terminal stage, provisioning, no further CTA.
|
||||
export const Live: Story = {
|
||||
args: { deal: { ...deal, currentStage: "active" } },
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button, Card } from "@shared/components";
|
||||
import type { Deal, DealStage, JourneyStep } from "@portal/api/procurement";
|
||||
import { StageStepper } from "@portal/components/procurement/StageStepper";
|
||||
|
||||
/**
|
||||
* The deal's commercial journey in one card: who's guiding it (the solutions
|
||||
* engineer), where it sits (the stage stepper), trial runway while evaluating,
|
||||
* and the single next action that advances the deal. Mirrors "one next action
|
||||
* at a time"; the full per-stage checklist lives in the Documents card.
|
||||
*/
|
||||
export function DealJourney({
|
||||
deal,
|
||||
journey,
|
||||
onAdvance,
|
||||
advancing = false,
|
||||
}: {
|
||||
deal: Deal;
|
||||
journey: JourneyStep[];
|
||||
onAdvance: (stage: DealStage) => void;
|
||||
advancing?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { engineer, trial, currentStage } = deal;
|
||||
const currentStep = journey.find((s) => s.stage === currentStage);
|
||||
const isTerminal =
|
||||
journey.length > 0 && journey[journey.length - 1].stage === currentStage;
|
||||
|
||||
return (
|
||||
<Card padding="none" className="portal-proc__journey">
|
||||
<div className="portal-proc__journey-head">
|
||||
<div>
|
||||
<span className="portal-proc__eyebrow">
|
||||
{t("procurement.journey.eyebrow")}
|
||||
</span>
|
||||
<h2 className="portal-proc__journey-title">
|
||||
{t("procurement.journey.title")}
|
||||
</h2>
|
||||
<p className="portal-proc__journey-sub">
|
||||
{t("procurement.journey.subtitle")}
|
||||
</p>
|
||||
</div>
|
||||
<div className="portal-proc__se">
|
||||
<span className="portal-proc__eyebrow">
|
||||
{t("procurement.journey.engineerLabel")}
|
||||
</span>
|
||||
<span className="portal-proc__se-name">{engineer.name}</span>
|
||||
<a
|
||||
className="portal-proc__se-email"
|
||||
href={`mailto:${engineer.email}`}
|
||||
>
|
||||
{engineer.email}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="portal-proc__journey-stepper">
|
||||
<StageStepper journey={journey} currentStage={currentStage} />
|
||||
</div>
|
||||
|
||||
{currentStage === "trial" && (
|
||||
<div className="portal-proc__trial">
|
||||
<span className="portal-proc__trial-title">
|
||||
{t("procurement.journey.trialTitle")}
|
||||
</span>
|
||||
<span className="portal-proc__trial-dim">
|
||||
{t("procurement.journey.daysLeft", { count: trial.daysLeft })}
|
||||
</span>
|
||||
<span className="portal-proc__trial-key">{trial.key}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="portal-proc__next">
|
||||
<div className="portal-proc__next-label">
|
||||
<span className="portal-proc__next-dot" data-live={isTerminal} />
|
||||
<span>
|
||||
{isTerminal
|
||||
? t("procurement.journey.live")
|
||||
: t("procurement.journey.nextStep", {
|
||||
action: currentStep?.gatingAction ?? "",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
{!isTerminal && currentStep && (
|
||||
<Button
|
||||
variant="gradient"
|
||||
accent="purple"
|
||||
loading={advancing}
|
||||
onClick={() => onAdvance(currentStage)}
|
||||
>
|
||||
{currentStep.gatingAction}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { DocRow } from "@portal/components/procurement/DocRow";
|
||||
import type { LedgerDoc } from "@portal/api/procurement";
|
||||
import "@portal/views/Procurement.css";
|
||||
|
||||
const meta: Meta<typeof DocRow> = {
|
||||
title: "Portal/Procurement/DocRow",
|
||||
component: DocRow,
|
||||
parameters: { layout: "padded" },
|
||||
args: { onAction: () => {} },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof DocRow>;
|
||||
|
||||
const sign: LedgerDoc = {
|
||||
id: "d1",
|
||||
name: "Stirling Enterprise Agreement",
|
||||
sub: "One signature: MSA + order form + EULA + DPA.",
|
||||
status: "action",
|
||||
action: "sign",
|
||||
};
|
||||
|
||||
const download: LedgerDoc = {
|
||||
id: "d2",
|
||||
name: "SOC 2 Type II report",
|
||||
sub: "Independent audit of our security controls.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
};
|
||||
|
||||
const paidAddon: LedgerDoc = {
|
||||
id: "d3",
|
||||
name: "Onboarding & training",
|
||||
sub: "Guided rollout and live training for your team.",
|
||||
status: "request",
|
||||
action: "request",
|
||||
optional: true,
|
||||
fee: 7_500,
|
||||
};
|
||||
|
||||
const done: LedgerDoc = {
|
||||
id: "d4",
|
||||
name: "Formal quote",
|
||||
sub: "Committed-volume pricing, term and line items.",
|
||||
status: "complete",
|
||||
action: "download",
|
||||
};
|
||||
|
||||
// Deal-advancing action, filled purple CTA.
|
||||
export const SignAction: Story = { args: { doc: sign } };
|
||||
|
||||
// Quiet outline action for a ready download.
|
||||
export const Download: Story = { args: { doc: download } };
|
||||
|
||||
// Optional paid add-on, chips flag it and the fee folds into the CTA.
|
||||
export const PaidAddon: Story = { args: { doc: paidAddon } };
|
||||
|
||||
// Completed paperwork keeps a record but offers no further action.
|
||||
export const Complete: Story = { args: { doc: done } };
|
||||
|
||||
// A row in a future, not-yet-reached stage, dimmed, marked "Upcoming", inert.
|
||||
export const Locked: Story = { args: { doc: sign, locked: true } };
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button, Chip, StatusBadge } from "@shared/components";
|
||||
import type { LedgerDoc } from "@portal/api/procurement";
|
||||
import {
|
||||
ACTION_LABEL_KEY,
|
||||
STATUS_LABEL_KEY,
|
||||
STATUS_TONE,
|
||||
USD,
|
||||
} from "@portal/components/procurement/format";
|
||||
|
||||
/** Maps a document's action to the button accent + variant. */
|
||||
function buttonStyle(doc: LedgerDoc): {
|
||||
variant: "gradient" | "outline";
|
||||
accent: "purple" | "blue";
|
||||
} {
|
||||
// The agreement signature and online payment are the deal-advancing actions;
|
||||
// give them the filled accent CTA. Everything else is a quieter outline.
|
||||
if (doc.action === "sign" || doc.action === "pay") {
|
||||
return { variant: "gradient", accent: "purple" };
|
||||
}
|
||||
return { variant: "outline", accent: "blue" };
|
||||
}
|
||||
|
||||
/**
|
||||
* A single document in the ledger or supporting pool: name + sub-line on the
|
||||
* left, status badge and action button on the right. Optional/fee-bearing docs
|
||||
* carry a chip so the buyer sees a paid add-on before clicking. `locked` is for
|
||||
* rows in a future, not-yet-reached stage: dimmed, marked "Upcoming", inert.
|
||||
*/
|
||||
export function DocRow({
|
||||
doc,
|
||||
onAction,
|
||||
locked = false,
|
||||
}: {
|
||||
doc: LedgerDoc;
|
||||
onAction: (doc: LedgerDoc) => void;
|
||||
locked?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { variant, accent } = buttonStyle(doc);
|
||||
// Locked (future-stage), in-progress (pending) and completed paperwork all
|
||||
// offer no action; only "available", "action" and "request" docs do.
|
||||
const actionable =
|
||||
!locked && doc.status !== "complete" && doc.status !== "pending";
|
||||
const label = t(ACTION_LABEL_KEY[doc.action]);
|
||||
const actionLabel =
|
||||
doc.fee !== undefined ? `${label} · ${USD.format(doc.fee)}` : label;
|
||||
|
||||
return (
|
||||
<div className="portal-proc__doc" data-locked={locked || undefined}>
|
||||
<div className="portal-proc__doc-text">
|
||||
<div className="portal-proc__doc-name-row">
|
||||
<span className="portal-proc__doc-name">{doc.name}</span>
|
||||
{doc.optional && (
|
||||
<Chip tone="neutral" size="sm">
|
||||
{t("procurement.docs.optional")}
|
||||
</Chip>
|
||||
)}
|
||||
{doc.fee !== undefined && (
|
||||
<Chip tone="amber" size="sm">
|
||||
{t("procurement.docs.paidAddon")}
|
||||
</Chip>
|
||||
)}
|
||||
</div>
|
||||
<p className="portal-proc__doc-sub">{doc.sub}</p>
|
||||
</div>
|
||||
<div className="portal-proc__doc-actions">
|
||||
<StatusBadge
|
||||
tone={locked ? "neutral" : STATUS_TONE[doc.status]}
|
||||
size="sm"
|
||||
>
|
||||
{locked
|
||||
? t("procurement.docs.upcoming")
|
||||
: t(STATUS_LABEL_KEY[doc.status])}
|
||||
</StatusBadge>
|
||||
{actionable && (
|
||||
<Button
|
||||
variant={variant}
|
||||
accent={accent}
|
||||
size="sm"
|
||||
onClick={() => onAction(doc)}
|
||||
>
|
||||
{actionLabel}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { DocumentLedger } from "@portal/components/procurement/DocumentLedger";
|
||||
import { buildProcurement } from "@portal/mocks/procurement";
|
||||
import "@portal/views/Procurement.css";
|
||||
|
||||
const data = buildProcurement("enterprise");
|
||||
|
||||
const meta: Meta<typeof DocumentLedger> = {
|
||||
title: "Portal/Procurement/DocumentLedger",
|
||||
component: DocumentLedger,
|
||||
parameters: { layout: "padded" },
|
||||
args: {
|
||||
groups: data.ledger,
|
||||
supporting: data.supporting,
|
||||
journey: data.journey,
|
||||
currentStage: data.deal?.currentStage ?? "trial",
|
||||
onAction: () => {},
|
||||
},
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof DocumentLedger>;
|
||||
|
||||
// Mid-journey: the Agreement stage is open, earlier stages read as done, later
|
||||
// stages are locked previews, and the supporting pool sits collapsed below.
|
||||
export const Default: Story = {};
|
||||
|
||||
// Day one: only the Trial stage has been reached; everything ahead is locked.
|
||||
export const AtTrial: Story = {
|
||||
args: { currentStage: "trial" },
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Card, Chip, Collapsible } from "@shared/components";
|
||||
import type {
|
||||
DealStage,
|
||||
JourneyStep,
|
||||
LedgerDoc,
|
||||
LedgerGroup,
|
||||
SupportingGroup,
|
||||
} from "@portal/api/procurement";
|
||||
import { DocRow } from "@portal/components/procurement/DocRow";
|
||||
|
||||
/**
|
||||
* The "Documents" card: every artifact the deal needs, as a stage accordion
|
||||
* that mirrors the journey. Only the current stage is open by default; earlier
|
||||
* stages read as done, later stages are locked previews. A collapsed-by-default
|
||||
* "Supporting your evaluation" pool holds the stage-agnostic paperwork.
|
||||
*/
|
||||
export function DocumentLedger({
|
||||
groups,
|
||||
supporting,
|
||||
journey,
|
||||
currentStage,
|
||||
onAction,
|
||||
}: {
|
||||
groups: LedgerGroup[];
|
||||
supporting: SupportingGroup[];
|
||||
journey: JourneyStep[];
|
||||
currentStage: DealStage;
|
||||
onAction: (doc: LedgerDoc) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const order = journey.map((s) => s.stage);
|
||||
const curIdx = order.indexOf(currentStage);
|
||||
// Follow the deal: the stage you're in opens first; any other stage can be
|
||||
// peeked. null collapses them all. Advancing moves the open section along.
|
||||
const [openStage, setOpenStage] = useState<DealStage | null>(currentStage);
|
||||
const [supportingOpen, setSupportingOpen] = useState(false);
|
||||
useEffect(() => setOpenStage(currentStage), [currentStage]);
|
||||
|
||||
return (
|
||||
<Card padding="none" className="portal-proc__docs">
|
||||
<div className="portal-proc__docs-head">
|
||||
<h2 className="portal-proc__docs-title">
|
||||
{t("procurement.docs.title")}
|
||||
</h2>
|
||||
<p className="portal-proc__docs-sub">
|
||||
{t("procurement.docs.subtitle")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="portal-proc__docs-body">
|
||||
{groups.map((group) => {
|
||||
const idx = order.indexOf(group.stage);
|
||||
const done = idx < curIdx;
|
||||
const cur = group.stage === currentStage;
|
||||
const locked = idx > curIdx;
|
||||
const blurb = journey.find((s) => s.stage === group.stage)?.blurb;
|
||||
const open = openStage === group.stage;
|
||||
const count = group.docs.length;
|
||||
|
||||
return (
|
||||
<Collapsible
|
||||
key={group.stage}
|
||||
open={open}
|
||||
onToggle={() => setOpenStage(open ? null : group.stage)}
|
||||
header={
|
||||
<>
|
||||
<span
|
||||
className="portal-proc__stage-dot"
|
||||
data-state={done ? "done" : cur ? "current" : "upcoming"}
|
||||
aria-hidden
|
||||
/>
|
||||
<span
|
||||
className="portal-proc__stage-label"
|
||||
data-current={cur || undefined}
|
||||
>
|
||||
{group.label}
|
||||
</span>
|
||||
{blurb && (
|
||||
<span className="portal-proc__stage-hint">· {blurb}</span>
|
||||
)}
|
||||
{cur && (
|
||||
<Chip tone="purple" size="sm">
|
||||
{t("procurement.docs.here")}
|
||||
</Chip>
|
||||
)}
|
||||
{done && (
|
||||
<Chip tone="green" size="sm">
|
||||
{t("procurement.docs.done")}
|
||||
</Chip>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
aside={
|
||||
<span className="portal-proc__stage-count">
|
||||
{t("procurement.docs.count", { count })}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="portal-proc__doc-list">
|
||||
{group.docs.map((doc) => (
|
||||
<DocRow
|
||||
key={doc.id}
|
||||
doc={doc}
|
||||
onAction={onAction}
|
||||
locked={locked}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</Collapsible>
|
||||
);
|
||||
})}
|
||||
|
||||
{supporting.length > 0 && (
|
||||
<Collapsible
|
||||
className="portal-proc__supporting-acc"
|
||||
open={supportingOpen}
|
||||
onToggle={() => setSupportingOpen((o) => !o)}
|
||||
header={
|
||||
<span className="portal-proc__supporting-head">
|
||||
<span className="portal-proc__stage-label">
|
||||
{t("procurement.docs.supportingTitle")}
|
||||
</span>
|
||||
<span className="portal-proc__supporting-sub">
|
||||
{t("procurement.docs.supportingSubtitle")}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
aside={
|
||||
<span className="portal-proc__acc-toggle-label">
|
||||
{supportingOpen
|
||||
? t("procurement.docs.hide")
|
||||
: t("procurement.docs.show")}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<div className="portal-proc__supporting-groups">
|
||||
{supporting.map((group) => (
|
||||
<div
|
||||
key={group.category}
|
||||
className="portal-proc__supporting-group"
|
||||
>
|
||||
<div className="portal-proc__group-label">{group.label}</div>
|
||||
<div className="portal-proc__doc-list portal-proc__doc-list--boxed">
|
||||
{group.docs.map((doc) => (
|
||||
<DocRow key={doc.id} doc={doc} onAction={onAction} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Collapsible>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { LockedState } from "@portal/components/procurement/LockedState";
|
||||
import { JOURNEY } from "@portal/mocks/procurement";
|
||||
import "@portal/views/Procurement.css";
|
||||
|
||||
const meta: Meta<typeof LockedState> = {
|
||||
title: "Portal/Procurement/LockedState",
|
||||
component: LockedState,
|
||||
parameters: { layout: "padded" },
|
||||
args: { onTalkToSales: () => {} },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof LockedState>;
|
||||
|
||||
// Shown to free/pro buyers, the journey preview behind the upgrade prompt.
|
||||
export const Default: Story = {
|
||||
args: { journey: JOURNEY },
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button, Card, EmptyState } from "@shared/components";
|
||||
import type { JourneyStep } from "@portal/api/procurement";
|
||||
import { StageStepper } from "@portal/components/procurement/StageStepper";
|
||||
|
||||
/**
|
||||
* Enterprise-only gate for free/pro buyers. Shows the journey as a greyed
|
||||
* preview behind an upgrade prompt so the buyer understands what the
|
||||
* commercial track looks like before they talk to sales.
|
||||
*/
|
||||
export function LockedState({
|
||||
journey,
|
||||
onTalkToSales,
|
||||
}: {
|
||||
journey: JourneyStep[];
|
||||
onTalkToSales: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="portal-proc__locked">
|
||||
<EmptyState
|
||||
eyebrow={t("procurement.locked.eyebrow")}
|
||||
title={t("procurement.locked.title")}
|
||||
description={t("procurement.locked.description")}
|
||||
actions={
|
||||
<Button variant="gradient" accent="purple" onClick={onTalkToSales}>
|
||||
{t("procurement.locked.talkToSales")}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<Card padding="loose" className="portal-proc__journey-stepper">
|
||||
<StageStepper journey={journey} currentStage="trial" locked />
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { StageStepper } from "@portal/components/procurement/StageStepper";
|
||||
import { JOURNEY } from "@portal/mocks/procurement";
|
||||
import "@portal/views/Procurement.css";
|
||||
|
||||
const meta: Meta<typeof StageStepper> = {
|
||||
title: "Portal/Procurement/StageStepper",
|
||||
component: StageStepper,
|
||||
parameters: { layout: "padded" },
|
||||
args: { journey: JOURNEY },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof StageStepper>;
|
||||
|
||||
export const AtAgreement: Story = { args: { currentStage: "security" } };
|
||||
|
||||
export const AtTrial: Story = { args: { currentStage: "trial" } };
|
||||
|
||||
// Greyed preview for the free/pro upgrade gate, no stage is current.
|
||||
export const Locked: Story = { args: { currentStage: "trial", locked: true } };
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Fragment } from "react";
|
||||
import type { DealStage, JourneyStep } from "@portal/api/procurement";
|
||||
|
||||
/** Status of a step relative to the deal's current stage. */
|
||||
type StepState = "complete" | "current" | "upcoming";
|
||||
|
||||
/**
|
||||
* The five-stage commercial journey as a horizontal band of labelled dots with
|
||||
* connectors between them. Purely presentational, the gating action lives in
|
||||
* the journey card's next-step row, not on the dots. `locked` greys the whole
|
||||
* band for the free/pro upgrade preview, where no stage is current.
|
||||
*/
|
||||
export function StageStepper({
|
||||
journey,
|
||||
currentStage,
|
||||
locked = false,
|
||||
}: {
|
||||
journey: JourneyStep[];
|
||||
currentStage: DealStage;
|
||||
locked?: boolean;
|
||||
}) {
|
||||
const order = journey.map((s) => s.stage);
|
||||
const curIdx = locked ? -1 : order.indexOf(currentStage);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`portal-proc__steps${locked ? " portal-proc__steps--locked" : ""}`}
|
||||
>
|
||||
{journey.map((step, i) => {
|
||||
const state: StepState =
|
||||
i < curIdx ? "complete" : i === curIdx ? "current" : "upcoming";
|
||||
return (
|
||||
<Fragment key={step.stage}>
|
||||
{i > 0 && (
|
||||
<span
|
||||
className="portal-proc__step-line"
|
||||
data-filled={i <= curIdx}
|
||||
aria-hidden
|
||||
/>
|
||||
)}
|
||||
<div className={`portal-proc__step portal-proc__step--${state}`}>
|
||||
<span className="portal-proc__step-dot" aria-hidden />
|
||||
<span className="portal-proc__step-label">{step.label}</span>
|
||||
</div>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** Shared formatting + status/action mappings for the Procurement surface. */
|
||||
|
||||
import type { StatusTone } from "@shared/components";
|
||||
import type { DocAction, DocStatus } from "@portal/api/procurement";
|
||||
|
||||
export const USD = new Intl.NumberFormat(undefined, {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
maximumFractionDigits: 0,
|
||||
});
|
||||
|
||||
/** Document status → badge tone. Action items lean amber to pull the eye. */
|
||||
export const STATUS_TONE: Record<DocStatus, StatusTone> = {
|
||||
available: "success",
|
||||
action: "warning",
|
||||
pending: "info",
|
||||
request: "neutral",
|
||||
complete: "neutral",
|
||||
};
|
||||
|
||||
/** Document status → translation key for the short badge label. */
|
||||
export const STATUS_LABEL_KEY: Record<DocStatus, string> = {
|
||||
available: "procurement.status.available",
|
||||
action: "procurement.status.action",
|
||||
pending: "procurement.status.pending",
|
||||
request: "procurement.status.request",
|
||||
complete: "procurement.status.complete",
|
||||
};
|
||||
|
||||
/** Action → translation key for the button label (the fee, when present, is appended by the caller). */
|
||||
export const ACTION_LABEL_KEY: Record<DocAction, string> = {
|
||||
download: "procurement.action.download",
|
||||
sign: "procurement.action.sign",
|
||||
pay: "procurement.action.pay",
|
||||
upload: "procurement.action.upload",
|
||||
request: "procurement.action.request",
|
||||
};
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import type { SourceView } from "@portal/api/sources";
|
||||
import { SourceDetailCard } from "@portal/components/sources/SourceDetailCard";
|
||||
import { sampleDailySeries } from "@portal/mocks/sampleDailySeries";
|
||||
|
||||
const SAMPLE_SERIES = sampleDailySeries(330);
|
||||
|
||||
const IN_USE: SourceView = {
|
||||
id: "src-claims",
|
||||
@@ -16,7 +19,9 @@ const IN_USE: SourceView = {
|
||||
{ label: "Directory", value: "/data/claims-intake" },
|
||||
{ label: "Mode", value: "consume" },
|
||||
],
|
||||
docsTotal: null,
|
||||
docsTotal: 45230,
|
||||
docs24h: 312,
|
||||
docs30d: 9870,
|
||||
};
|
||||
|
||||
const ORPHANED: SourceView = {
|
||||
@@ -27,7 +32,9 @@ const ORPHANED: SourceView = {
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [{ label: "Directory", value: "/data/archive" }],
|
||||
docsTotal: null,
|
||||
docsTotal: 45230,
|
||||
docs24h: 312,
|
||||
docs30d: 9870,
|
||||
};
|
||||
|
||||
const meta: Meta<typeof SourceDetailCard> = {
|
||||
@@ -35,6 +42,7 @@ const meta: Meta<typeof SourceDetailCard> = {
|
||||
component: SourceDetailCard,
|
||||
parameters: { layout: "padded" },
|
||||
args: {
|
||||
docSeries: SAMPLE_SERIES,
|
||||
onClose: () => {},
|
||||
onEdit: () => {},
|
||||
onTogglePause: () => {},
|
||||
|
||||
@@ -7,6 +7,7 @@ import "@portal/views/Sources.css";
|
||||
|
||||
interface SourceDetailCardProps {
|
||||
source: SourceView;
|
||||
docSeries: number[];
|
||||
onClose: () => void;
|
||||
onEdit: (source: SourceView) => void;
|
||||
onTogglePause: (source: SourceView) => void;
|
||||
@@ -18,6 +19,7 @@ interface SourceDetailCardProps {
|
||||
/** Expanded detail for the selected source row, with edit/pause/delete actions. */
|
||||
export function SourceDetailCard({
|
||||
source,
|
||||
docSeries,
|
||||
onClose,
|
||||
onEdit,
|
||||
onTogglePause,
|
||||
@@ -55,7 +57,7 @@ export function SourceDetailCard({
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<SourceDetailPanel source={source} />
|
||||
<SourceDetailPanel source={source} docSeries={docSeries} />
|
||||
|
||||
<div className="portal-sources__detail-actions">
|
||||
<Button
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import type { SourceView } from "@portal/api/sources";
|
||||
import { SourceDetailPanel } from "@portal/components/sources/SourceDetailPanel";
|
||||
import { sampleDailySeries } from "@portal/mocks/sampleDailySeries";
|
||||
|
||||
const SAMPLE_SERIES = sampleDailySeries(330);
|
||||
|
||||
const IN_USE: SourceView = {
|
||||
id: "src-claims",
|
||||
@@ -16,7 +19,9 @@ const IN_USE: SourceView = {
|
||||
{ label: "Directory", value: "/data/claims-intake" },
|
||||
{ label: "Mode", value: "consume" },
|
||||
],
|
||||
docsTotal: null,
|
||||
docsTotal: 45230,
|
||||
docs24h: 312,
|
||||
docs30d: 9870,
|
||||
};
|
||||
|
||||
const ORPHANED: SourceView = {
|
||||
@@ -27,7 +32,9 @@ const ORPHANED: SourceView = {
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [{ label: "Directory", value: "/data/archive" }],
|
||||
docsTotal: null,
|
||||
docsTotal: 1180,
|
||||
docs24h: 0,
|
||||
docs30d: 0,
|
||||
};
|
||||
|
||||
const meta: Meta<typeof SourceDetailPanel> = {
|
||||
@@ -45,6 +52,8 @@ const meta: Meta<typeof SourceDetailPanel> = {
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof SourceDetailPanel>;
|
||||
|
||||
export const InUse: Story = { args: { source: IN_USE } };
|
||||
export const InUse: Story = {
|
||||
args: { source: IN_USE, docSeries: SAMPLE_SERIES },
|
||||
};
|
||||
/** A source no policy references is called out as safe to delete. */
|
||||
export const Orphaned: Story = { args: { source: ORPHANED } };
|
||||
export const Orphaned: Story = { args: { source: ORPHANED, docSeries: [] } };
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Chip, StatTile } from "@shared/components";
|
||||
import type { SourceView } from "@portal/api/sources";
|
||||
import { Sparkline } from "@portal/components/sources/Sparkline";
|
||||
import "@portal/views/Sources.css";
|
||||
|
||||
interface SourceDetailPanelProps {
|
||||
source: SourceView;
|
||||
/** The 30-day daily series for the sparkline, fetched per source when expanded. */
|
||||
docSeries: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Expanded detail for a source row: its config (key/value) plus which policies
|
||||
* reference it. A 0-reference source is called out as safe to delete.
|
||||
* Expanded detail for a source row: its config (key/value), the documents it has
|
||||
* fed into runs, and which policies reference it (a 0-reference source is called
|
||||
* out as safe to delete).
|
||||
*/
|
||||
export function SourceDetailPanel({ source }: { source: SourceView }) {
|
||||
export function SourceDetailPanel({
|
||||
source,
|
||||
docSeries,
|
||||
}: SourceDetailPanelProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="portal-sources__detail">
|
||||
@@ -38,9 +49,31 @@ export function SourceDetailPanel({ source }: { source: SourceView }) {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="portal-sources__muted">
|
||||
{t("sources.detail.docsUntracked")}
|
||||
</p>
|
||||
<div className="portal-sources__detail-section">
|
||||
<span className="portal-sources__detail-heading">
|
||||
{t("sources.detail.documents")}
|
||||
</span>
|
||||
<div className="portal-sources__stat-grid">
|
||||
<StatTile
|
||||
label={t("sources.detail.docsTotal")}
|
||||
value={source.docsTotal.toLocaleString()}
|
||||
/>
|
||||
<StatTile
|
||||
label={t("sources.detail.docs24h")}
|
||||
value={source.docs24h.toLocaleString()}
|
||||
/>
|
||||
<StatTile
|
||||
label={t("sources.detail.docs30d")}
|
||||
value={source.docs30d.toLocaleString()}
|
||||
/>
|
||||
</div>
|
||||
{docSeries.length > 0 && (
|
||||
<Sparkline
|
||||
data={docSeries}
|
||||
ariaLabel={t("sources.detail.docsTrend")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ const SOURCES: SourceView[] = [
|
||||
{ label: "Directory", value: "/data/claims-intake" },
|
||||
{ label: "Mode", value: "consume" },
|
||||
],
|
||||
docsTotal: null,
|
||||
docsTotal: 45230,
|
||||
docs24h: 312,
|
||||
docs30d: 9870,
|
||||
},
|
||||
{
|
||||
id: "src-archive",
|
||||
@@ -27,7 +29,9 @@ const SOURCES: SourceView[] = [
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [{ label: "Directory", value: "/data/archive" }],
|
||||
docsTotal: null,
|
||||
docsTotal: 1180,
|
||||
docs24h: 0,
|
||||
docs30d: 0,
|
||||
},
|
||||
{
|
||||
id: "src-legacy",
|
||||
@@ -37,7 +41,9 @@ const SOURCES: SourceView[] = [
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [{ label: "Directory", value: "/mnt/legacy" }],
|
||||
docsTotal: null,
|
||||
docsTotal: 48600,
|
||||
docs24h: 0,
|
||||
docs30d: 0,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { render } from "@testing-library/react";
|
||||
import { Sparkline } from "@portal/components/sources/Sparkline";
|
||||
|
||||
function pointsOf(container: HTMLElement): string[] {
|
||||
const poly = container.querySelector("polyline");
|
||||
return (poly?.getAttribute("points") ?? "")
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
describe("Sparkline", () => {
|
||||
it("draws one point per value", () => {
|
||||
const { container } = render(<Sparkline data={[1, 5, 2, 8, 3]} />);
|
||||
expect(pointsOf(container)).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("renders nothing for an empty series", () => {
|
||||
const { container } = render(<Sparkline data={[]} />);
|
||||
expect(container.querySelector("svg")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders a flat finite line for an all-zero series (no divide-by-zero)", () => {
|
||||
const { container } = render(<Sparkline data={[0, 0, 0, 0]} />);
|
||||
const ys = pointsOf(container).map((p) => Number(p.split(",")[1]));
|
||||
expect(ys).toHaveLength(4);
|
||||
expect(ys.every(Number.isFinite)).toBe(true);
|
||||
// All equal: a zero series is a single horizontal line, not NaN-laden.
|
||||
expect(new Set(ys).size).toBe(1);
|
||||
});
|
||||
|
||||
it("puts the peak value at the top of the band", () => {
|
||||
const { container } = render(<Sparkline data={[0, 10]} height={36} />);
|
||||
const ys = pointsOf(container).map((p) => Number(p.split(",")[1]));
|
||||
// y grows downward in SVG, so the larger value (10) sits at the smaller y.
|
||||
expect(ys[1]).toBeLessThan(ys[0]);
|
||||
});
|
||||
|
||||
it("exposes its aria-label", () => {
|
||||
const { container } = render(
|
||||
<Sparkline data={[1, 2]} ariaLabel="Docs trend" />,
|
||||
);
|
||||
expect(container.querySelector("svg")?.getAttribute("aria-label")).toBe(
|
||||
"Docs trend",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import "@portal/views/Sources.css";
|
||||
|
||||
interface SparklineProps {
|
||||
/** Series values, oldest first. */
|
||||
data: number[];
|
||||
/** Drawing height in px; the width fills the container. */
|
||||
height?: number;
|
||||
ariaLabel?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A tiny dependency-free trend line: normalises {@code data} to its own peak and draws a single
|
||||
* polyline. The viewBox is fixed while the rendered width fills the container (the stroke stays
|
||||
* crisp via non-scaling-stroke), so it adapts to any column without distorting the line weight.
|
||||
*/
|
||||
export function Sparkline({ data, height = 36, ariaLabel }: SparklineProps) {
|
||||
if (data.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const width = 240;
|
||||
const pad = 3;
|
||||
const max = Math.max(...data, 1);
|
||||
const stepX = data.length > 1 ? width / (data.length - 1) : 0;
|
||||
const points = data
|
||||
.map((value, i) => {
|
||||
const x = i * stepX;
|
||||
const y = pad + (1 - value / max) * (height - 2 * pad);
|
||||
return `${x.toFixed(1)},${y.toFixed(1)}`;
|
||||
})
|
||||
.join(" ");
|
||||
|
||||
return (
|
||||
<svg
|
||||
className="portal-sparkline"
|
||||
width="100%"
|
||||
height={height}
|
||||
viewBox={`0 0 ${width} ${height}`}
|
||||
preserveAspectRatio="none"
|
||||
role="img"
|
||||
aria-label={ariaLabel}
|
||||
>
|
||||
<polyline
|
||||
points={points}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.5"
|
||||
strokeLinejoin="round"
|
||||
strokeLinecap="round"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export type ViewId =
|
||||
| "infrastructure"
|
||||
| "usage"
|
||||
| "docs"
|
||||
| "procurement"
|
||||
| "settings";
|
||||
|
||||
export const VIEW_LABELS: Record<ViewId, string> = {
|
||||
@@ -29,6 +30,7 @@ export const VIEW_LABELS: Record<ViewId, string> = {
|
||||
infrastructure: "Infrastructure",
|
||||
usage: "Usage & Billing",
|
||||
docs: "Developer Docs",
|
||||
procurement: "Procurement",
|
||||
settings: "Settings",
|
||||
};
|
||||
|
||||
@@ -45,6 +47,7 @@ export const VIEW_PATHS: Record<ViewId, string> = {
|
||||
infrastructure: "/infrastructure",
|
||||
usage: "/usage",
|
||||
docs: "/docs",
|
||||
procurement: "/procurement",
|
||||
settings: "/settings",
|
||||
};
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { searchHandlers } from "@portal/mocks/handlers/search";
|
||||
import { pipelinesHandlers } from "@portal/mocks/handlers/pipelines";
|
||||
import { sourcesHandlers } from "@portal/mocks/handlers/sources";
|
||||
import { infrastructureHandlers } from "@portal/mocks/handlers/infrastructure";
|
||||
import { procurementHandlers } from "@portal/mocks/handlers/procurement";
|
||||
import { docsHandlers } from "@portal/mocks/handlers/docs";
|
||||
import { settingsHandlers } from "@portal/mocks/handlers/settings";
|
||||
import { usersHandlers } from "@portal/mocks/handlers/users";
|
||||
@@ -28,6 +29,7 @@ export const handlers = [
|
||||
...sourcesHandlers,
|
||||
...infrastructureHandlers,
|
||||
...docsHandlers,
|
||||
...procurementHandlers,
|
||||
...settingsHandlers,
|
||||
...usersHandlers,
|
||||
...agentsHandlers,
|
||||
@@ -39,3 +41,4 @@ export const handlers = [
|
||||
];
|
||||
|
||||
export { resetNotificationsStore } from "@portal/mocks/handlers/notifications";
|
||||
export { resetProcurementStore } from "@portal/mocks/handlers/procurement";
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { http, HttpResponse, delay } from "msw";
|
||||
import type { Tier } from "@portal/contexts/TierContext";
|
||||
import {
|
||||
JOURNEY,
|
||||
buildProcurement,
|
||||
seedEnterpriseDeal,
|
||||
type DealStage,
|
||||
type ProcurementResponse,
|
||||
} from "@portal/mocks/procurement";
|
||||
import {
|
||||
advanceDeal,
|
||||
payDeal,
|
||||
requestDoc,
|
||||
signDoc,
|
||||
uploadPurchaseOrder,
|
||||
} from "@portal/mocks/procurementMachine";
|
||||
|
||||
/**
|
||||
* Stateful mock of the commercial backend. The write endpoints drive the
|
||||
* procurement state machine over one in-memory enterprise deal, so the journey
|
||||
* genuinely progresses within a session, advancing a stage flips the gating
|
||||
* paperwork, unlocks the next stage's documents, and the GET reflects every
|
||||
* prior write. Swapping in the real backend is just deleting these handlers;
|
||||
* the api/ contracts and the state-machine semantics stay.
|
||||
*/
|
||||
let store = seedEnterpriseDeal();
|
||||
|
||||
/** Reseed the deal to its starting (mid-journey) state, used by tests + replay. */
|
||||
export function resetProcurementStore() {
|
||||
store = seedEnterpriseDeal();
|
||||
}
|
||||
|
||||
function snapshot(): ProcurementResponse {
|
||||
return {
|
||||
tier: "enterprise",
|
||||
unlocked: true,
|
||||
deal: store.deal,
|
||||
journey: JOURNEY,
|
||||
ledger: store.ledger,
|
||||
supporting: store.supporting,
|
||||
};
|
||||
}
|
||||
|
||||
export const procurementHandlers = [
|
||||
http.get("/v1/procurement", async ({ request }) => {
|
||||
await delay(120);
|
||||
const tier = (new URL(request.url).searchParams.get("tier") ??
|
||||
"pro") as Tier;
|
||||
// Only the enterprise tenant has a live deal; others get the locked payload.
|
||||
if (tier !== "enterprise") return HttpResponse.json(buildProcurement(tier));
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
|
||||
// POST /v1/procurement/advance, the journey's primary "next step".
|
||||
http.post("/v1/procurement/advance", async ({ request }) => {
|
||||
await delay(140);
|
||||
const { fromStage } = (await request.json()) as { fromStage: DealStage };
|
||||
advanceDeal(store, fromStage);
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
|
||||
// POST /v1/procurement/sign, e-sign the agreement, then advance.
|
||||
http.post("/v1/procurement/sign", async ({ request }) => {
|
||||
await delay(160);
|
||||
const { docId } = (await request.json()) as { docId: string };
|
||||
signDoc(store, docId);
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
|
||||
// POST /v1/procurement/pay, confirm online payment, then advance.
|
||||
http.post("/v1/procurement/pay", async () => {
|
||||
await delay(160);
|
||||
payDeal(store);
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
|
||||
// POST /v1/procurement/purchase-order, upload a PO (an alternate pay path).
|
||||
http.post("/v1/procurement/purchase-order", async () => {
|
||||
await delay(160);
|
||||
uploadPurchaseOrder(store);
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
|
||||
// POST /v1/procurement/documents/:docId/request, queue an on-demand doc.
|
||||
http.post("/v1/procurement/documents/:docId/request", async ({ params }) => {
|
||||
await delay(140);
|
||||
requestDoc(store, String(params.docId));
|
||||
return HttpResponse.json(snapshot());
|
||||
}),
|
||||
];
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
SourceView,
|
||||
SourcesResponse,
|
||||
} from "@portal/api/sources";
|
||||
import { sampleDailySeries } from "@portal/mocks/sampleDailySeries";
|
||||
|
||||
/**
|
||||
* Stateful mock for the Sources surface so the portal works fully offline with
|
||||
@@ -66,6 +67,27 @@ const references: Record<string, SourcePolicyRef[]> = {
|
||||
"src-contracts": [{ id: "pol_contract", name: "Contract Review" }],
|
||||
};
|
||||
|
||||
/** Per-source document throughput, mirroring the backend's docsTotal / 24h / 30d. */
|
||||
const docCounts: Record<
|
||||
string,
|
||||
{ total: number; last24h: number; last30d: number }
|
||||
> = {
|
||||
"src-claims": { total: 45230, last24h: 312, last30d: 9870 },
|
||||
"src-contracts": { total: 12840, last24h: 96, last30d: 2310 },
|
||||
"src-archive": { total: 1180, last24h: 0, last30d: 0 },
|
||||
"src-legacy": { total: 48600, last24h: 0, last30d: 0 },
|
||||
};
|
||||
|
||||
function docsFor(id: string): {
|
||||
total: number;
|
||||
last24h: number;
|
||||
last30d: number;
|
||||
daily: number[];
|
||||
} {
|
||||
const counts = docCounts[id] ?? { total: 0, last24h: 0, last30d: 0 };
|
||||
return { ...counts, daily: sampleDailySeries(counts.last30d / 30) };
|
||||
}
|
||||
|
||||
let store: StoredSource[] = seedSources();
|
||||
|
||||
let idCounter = 0;
|
||||
@@ -97,6 +119,7 @@ function toSourceView(
|
||||
source: StoredSource,
|
||||
refs: SourcePolicyRef[],
|
||||
): SourceView {
|
||||
const docs = docsFor(source.id);
|
||||
return {
|
||||
id: source.id,
|
||||
name: source.name,
|
||||
@@ -105,7 +128,9 @@ function toSourceView(
|
||||
referenceCount: refs.length,
|
||||
referencingPolicies: refs,
|
||||
config: configRows(source.options),
|
||||
docsTotal: null,
|
||||
docsTotal: docs.total,
|
||||
docs24h: docs.last24h,
|
||||
docs30d: docs.last30d,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -142,6 +167,13 @@ export const sourcesHandlers = [
|
||||
return HttpResponse.json(source);
|
||||
}),
|
||||
|
||||
http.get("/api/v1/sources/:id/document-counts", async ({ params }) => {
|
||||
await delay(120);
|
||||
const source = store.find((s) => s.id === params.id);
|
||||
if (!source) return new HttpResponse(null, { status: 404 });
|
||||
return HttpResponse.json(docsFor(source.id).daily);
|
||||
}),
|
||||
|
||||
http.post("/api/v1/sources", async ({ request }) => {
|
||||
await delay(120);
|
||||
const incoming = (await request.json()) as Source;
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
/**
|
||||
* Procurement fixtures and the types api/procurement.ts shares with them.
|
||||
* api/procurement.ts imports the types; the MSW handlers in
|
||||
* mocks/handlers/procurement.ts serve this fixture data over the intercepted
|
||||
* httpJson() calls. Components never reach into this module directly.
|
||||
*
|
||||
* Procurement models the enterprise commercial journey, trial → quote →
|
||||
* agreement → payment → implementation, plus the paperwork ledger that rides
|
||||
* alongside it. The journey is enterprise-only; free/pro tiers receive a
|
||||
* minimal locked payload the view renders as an upgrade prompt.
|
||||
*
|
||||
* Once a real commercial backend exists the MSW handlers stop being registered
|
||||
* and these fixtures can be deleted (or kept as test seeds).
|
||||
*/
|
||||
|
||||
import type { Tier } from "@portal/contexts/TierContext";
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Journey stages */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* The five-stage enterprise journey. The id is the contract value the backend
|
||||
* advances; the labels below are the buyer-facing stage names (Agreement and
|
||||
* Payment read more plainly than the internal `security` / `procurement`).
|
||||
*/
|
||||
export type DealStage =
|
||||
| "trial"
|
||||
| "quote"
|
||||
| "security"
|
||||
| "procurement"
|
||||
| "active";
|
||||
|
||||
export interface JourneyStep {
|
||||
stage: DealStage;
|
||||
/** Buyer-facing stage name. */
|
||||
label: string;
|
||||
/** One-line description of what happens at this stage. */
|
||||
blurb: string;
|
||||
/**
|
||||
* Label for the single action that advances this stage. The current stage
|
||||
* surfaces its gating action; `active` is terminal (provisioning).
|
||||
*/
|
||||
gatingAction: string;
|
||||
}
|
||||
|
||||
/** Ordered journey definition, the stepper renders this verbatim. */
|
||||
export const JOURNEY: JourneyStep[] = [
|
||||
{
|
||||
stage: "trial",
|
||||
label: "Trial",
|
||||
blurb: "Evaluate Stirling against your documents and workflows.",
|
||||
gatingAction: "Build your quote",
|
||||
},
|
||||
{
|
||||
stage: "quote",
|
||||
label: "Quote",
|
||||
blurb: "Review committed-volume pricing and contract term.",
|
||||
gatingAction: "Accept your quote",
|
||||
},
|
||||
{
|
||||
stage: "security",
|
||||
label: "Agreement",
|
||||
blurb: "One signature covers MSA, order form, EULA and DPA.",
|
||||
gatingAction: "Review and sign your agreement",
|
||||
},
|
||||
{
|
||||
stage: "procurement",
|
||||
label: "Payment",
|
||||
blurb: "Pay by card, bank transfer, or against a purchase order.",
|
||||
gatingAction: "Confirm payment",
|
||||
},
|
||||
{
|
||||
stage: "active",
|
||||
label: "Implementation",
|
||||
blurb: "Provision your workspace and run the go-live playbook.",
|
||||
gatingAction: "Provisioning your workspace",
|
||||
},
|
||||
];
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Deal header */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export interface SolutionsEngineer {
|
||||
name: string;
|
||||
title: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface TrialInfo {
|
||||
/** License key seeded for the evaluation. */
|
||||
key: string;
|
||||
/** ISO date the trial began. */
|
||||
startedOn: string;
|
||||
/** ISO date the trial expires. */
|
||||
endsOn: string;
|
||||
/** Whole days remaining (derived in the fixture for a stable demo number). */
|
||||
daysLeft: number;
|
||||
extensionsUsed: number;
|
||||
maxExtensions: number;
|
||||
}
|
||||
|
||||
export interface QuoteInfo {
|
||||
number: string;
|
||||
/** Annual contract value, in USD. */
|
||||
amount: number;
|
||||
/** Contract term, e.g. "12 months". */
|
||||
term: string;
|
||||
/** ISO date the quote expires. */
|
||||
validUntil: string;
|
||||
}
|
||||
|
||||
export interface Deal {
|
||||
company: string;
|
||||
currentStage: DealStage;
|
||||
engineer: SolutionsEngineer;
|
||||
trial: TrialInfo;
|
||||
quote: QuoteInfo;
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Document ledger + supporting pool */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
/**
|
||||
* Lifecycle of a single document.
|
||||
* available: ready to grab now (download/sign/pay/upload as the action says)
|
||||
* action: waiting on the buyer to act (the gating paperwork of a stage)
|
||||
* pending: issued, awaiting the other side / a system step
|
||||
* request: not generated yet; the buyer asks for it (some carry a fee)
|
||||
* complete: done, kept for the record
|
||||
*/
|
||||
export type DocStatus =
|
||||
| "available"
|
||||
| "action"
|
||||
| "pending"
|
||||
| "request"
|
||||
| "complete";
|
||||
|
||||
/** What pressing the document's button does. */
|
||||
export type DocAction = "download" | "sign" | "pay" | "upload" | "request";
|
||||
|
||||
export interface LedgerDoc {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Sub-line describing what the document is / what it covers. */
|
||||
sub: string;
|
||||
status: DocStatus;
|
||||
action: DocAction;
|
||||
/** Buyer-skippable paperwork (e.g. paid onboarding). */
|
||||
optional?: boolean;
|
||||
/** One-off fee in USD when the document/service is a paid add-on. */
|
||||
fee?: number;
|
||||
}
|
||||
|
||||
/** Document ledger grouped by the journey stage the paperwork belongs to. */
|
||||
export interface LedgerGroup {
|
||||
stage: DealStage;
|
||||
/** Buyer-facing stage name (matches JourneyStep.label). */
|
||||
label: string;
|
||||
docs: LedgerDoc[];
|
||||
}
|
||||
|
||||
/** Categories the stage-agnostic supporting pool is grouped under. */
|
||||
export type SupportingCategory =
|
||||
| "security"
|
||||
| "legal"
|
||||
| "corporate"
|
||||
| "procurement";
|
||||
|
||||
export interface SupportingGroup {
|
||||
category: SupportingCategory;
|
||||
label: string;
|
||||
docs: LedgerDoc[];
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Full procurement payload */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
export interface ProcurementResponse {
|
||||
tier: Tier;
|
||||
/** True only for enterprise, gates the whole journey + ledger. */
|
||||
unlocked: boolean;
|
||||
/** Present only when unlocked. */
|
||||
deal: Deal | null;
|
||||
journey: JourneyStep[];
|
||||
ledger: LedgerGroup[];
|
||||
supporting: SupportingGroup[];
|
||||
}
|
||||
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
/* Fixtures */
|
||||
/* ──────────────────────────────────────────────────────────────────────── */
|
||||
|
||||
const ENTERPRISE_DEAL: Deal = {
|
||||
company: "Northwind Logistics",
|
||||
// The buyer has accepted the quote and is at the agreement signature, the
|
||||
// mid-journey state shows the most surface area (completed + active + ahead).
|
||||
currentStage: "security",
|
||||
engineer: {
|
||||
name: "Priya Raman",
|
||||
title: "Senior Solutions Engineer",
|
||||
email: "priya.raman@stirlingpdf.com",
|
||||
},
|
||||
trial: {
|
||||
key: "TRIAL-NWND-7F3A-2C9E",
|
||||
startedOn: daysFromNow(-23),
|
||||
endsOn: daysFromNow(7),
|
||||
daysLeft: 7,
|
||||
extensionsUsed: 1,
|
||||
maxExtensions: 2,
|
||||
},
|
||||
quote: {
|
||||
number: "Q-2026-0488",
|
||||
amount: 84_000,
|
||||
term: "12 months",
|
||||
validUntil: daysFromNow(14),
|
||||
},
|
||||
};
|
||||
|
||||
/** Document ledger for the live enterprise deal, grouped by stage. */
|
||||
const ENTERPRISE_LEDGER: LedgerGroup[] = [
|
||||
{
|
||||
stage: "trial",
|
||||
label: "Trial",
|
||||
docs: [
|
||||
{
|
||||
id: "doc-trial-quickstart",
|
||||
name: "Trial quick-start guide",
|
||||
sub: "Stand up the evaluation environment in under an hour.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "doc-trial-handout",
|
||||
name: "Evaluator handout",
|
||||
sub: "Share Stirling's capabilities with your evaluation team.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
stage: "quote",
|
||||
label: "Quote",
|
||||
docs: [
|
||||
{
|
||||
id: "doc-quote-formal",
|
||||
name: "Formal quote",
|
||||
sub: "Committed-volume pricing, term and line items, Q-2026-0488.",
|
||||
status: "complete",
|
||||
action: "download",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
stage: "security",
|
||||
label: "Agreement",
|
||||
docs: [
|
||||
{
|
||||
id: "doc-agreement-enterprise",
|
||||
name: "Stirling Enterprise Agreement",
|
||||
sub: "One signature: MSA + order form + EULA + DPA.",
|
||||
status: "action",
|
||||
action: "sign",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
stage: "procurement",
|
||||
label: "Payment",
|
||||
docs: [
|
||||
{
|
||||
id: "doc-pay-online",
|
||||
name: "Pay online",
|
||||
sub: "Card or bank transfer via Stripe.",
|
||||
status: "pending",
|
||||
action: "pay",
|
||||
},
|
||||
{
|
||||
id: "doc-pay-wire",
|
||||
name: "Bank transfer instructions",
|
||||
sub: "Wire details, plus RIB for EU buyers.",
|
||||
status: "pending",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "doc-pay-po",
|
||||
name: "Purchase order",
|
||||
sub: "Upload it and we invoice against it.",
|
||||
status: "request",
|
||||
action: "upload",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
stage: "active",
|
||||
label: "Implementation",
|
||||
docs: [
|
||||
{
|
||||
id: "doc-active-playbook",
|
||||
name: "Go-live playbook",
|
||||
sub: "Cut-over steps, rollback plan, and success checks.",
|
||||
status: "pending",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "doc-active-admin",
|
||||
name: "Administrator setup guide",
|
||||
sub: "SSO, regions, audit export and seat provisioning.",
|
||||
status: "pending",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "doc-active-onboarding",
|
||||
name: "Onboarding & training",
|
||||
sub: "Guided rollout and live training for your team.",
|
||||
status: "request",
|
||||
action: "request",
|
||||
optional: true,
|
||||
fee: 7_500,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/** Stage-agnostic supporting documents, grouped by category. */
|
||||
const ENTERPRISE_SUPPORTING: SupportingGroup[] = [
|
||||
{
|
||||
category: "security",
|
||||
label: "Security",
|
||||
docs: [
|
||||
{
|
||||
id: "sup-soc2",
|
||||
name: "SOC 2 Type II report",
|
||||
sub: "Independent audit of our security controls.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "sup-caiq",
|
||||
name: "Security questionnaire (CAIQ)",
|
||||
sub: "Pre-filled Consensus Assessments Initiative Questionnaire.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "sup-pentest",
|
||||
name: "Penetration test summary",
|
||||
sub: "Latest third-party penetration test results.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "sup-custom-review",
|
||||
name: "Custom security review",
|
||||
sub: "Dedicated session with our security team for your assessment.",
|
||||
status: "request",
|
||||
action: "request",
|
||||
fee: 5_000,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
category: "legal",
|
||||
label: "Legal",
|
||||
docs: [
|
||||
{
|
||||
id: "sup-baa",
|
||||
name: "Business Associate Agreement (HIPAA)",
|
||||
sub: "Required when processing protected health information.",
|
||||
status: "request",
|
||||
action: "request",
|
||||
fee: 2_500,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
category: "corporate",
|
||||
label: "Corporate",
|
||||
docs: [
|
||||
{
|
||||
id: "sup-w9",
|
||||
name: "IRS Form W-9",
|
||||
sub: "Our taxpayer identification for your records.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "sup-incorporation",
|
||||
name: "Certificate of Incorporation",
|
||||
sub: "Proof of our legal entity registration.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
{
|
||||
id: "sup-insurance",
|
||||
name: "Certificate of Insurance",
|
||||
sub: "Liability and cyber insurance coverage evidence.",
|
||||
status: "available",
|
||||
action: "download",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
category: "procurement",
|
||||
label: "Procurement",
|
||||
docs: [
|
||||
{
|
||||
id: "sup-vendor-onboarding",
|
||||
name: "Vendor onboarding form",
|
||||
sub: "We fill out your procurement-portal forms for you.",
|
||||
status: "request",
|
||||
action: "request",
|
||||
fee: 1_500,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
/** Structured deep clone of plain fixture data (no functions / class instances). */
|
||||
function clone<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A fresh, mutable copy of the live enterprise deal, deal header, stage ledger
|
||||
* and supporting pool. The MSW layer seeds its in-memory store from this so the
|
||||
* write handlers can advance the journey within a session without mutating the
|
||||
* shared fixtures. The journey definition (JOURNEY) is immutable and shared.
|
||||
*/
|
||||
export function seedEnterpriseDeal(): {
|
||||
deal: Deal;
|
||||
ledger: LedgerGroup[];
|
||||
supporting: SupportingGroup[];
|
||||
} {
|
||||
return {
|
||||
deal: clone(ENTERPRISE_DEAL),
|
||||
ledger: clone(ENTERPRISE_LEDGER),
|
||||
supporting: clone(ENTERPRISE_SUPPORTING),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the procurement payload for a tier. Enterprise gets the full live
|
||||
* deal; free/pro get a minimal locked payload the view renders as an
|
||||
* "enterprise-only" upgrade state.
|
||||
*/
|
||||
export function buildProcurement(tier: Tier): ProcurementResponse {
|
||||
if (tier !== "enterprise") {
|
||||
// Locked tiers still receive the journey definition so the view can render
|
||||
// a greyed preview of the steps behind the upgrade prompt.
|
||||
return {
|
||||
tier,
|
||||
unlocked: false,
|
||||
deal: null,
|
||||
journey: JOURNEY,
|
||||
ledger: [],
|
||||
supporting: [],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
tier,
|
||||
unlocked: true,
|
||||
deal: ENTERPRISE_DEAL,
|
||||
journey: JOURNEY,
|
||||
ledger: ENTERPRISE_LEDGER,
|
||||
supporting: ENTERPRISE_SUPPORTING,
|
||||
};
|
||||
}
|
||||
|
||||
/** ISO date (YYYY-MM-DD) `n` days from today; negative for the past. */
|
||||
function daysFromNow(n: number): string {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() + n);
|
||||
return d.toISOString().slice(0, 10);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { seedEnterpriseDeal } from "@portal/mocks/procurement";
|
||||
import {
|
||||
advanceDeal,
|
||||
payDeal,
|
||||
requestDoc,
|
||||
signDoc,
|
||||
uploadPurchaseOrder,
|
||||
type ProcurementStore,
|
||||
} from "@portal/mocks/procurementMachine";
|
||||
|
||||
let store: ProcurementStore;
|
||||
beforeEach(() => {
|
||||
store = seedEnterpriseDeal();
|
||||
});
|
||||
|
||||
function status(s: ProcurementStore, id: string): string | undefined {
|
||||
return [
|
||||
...s.ledger.flatMap((g) => g.docs),
|
||||
...s.supporting.flatMap((g) => g.docs),
|
||||
].find((d) => d.id === id)?.status;
|
||||
}
|
||||
|
||||
describe("seed", () => {
|
||||
it("starts mid-journey at the agreement, awaiting signature", () => {
|
||||
expect(store.deal.currentStage).toBe("security");
|
||||
expect(status(store, "doc-agreement-enterprise")).toBe("action");
|
||||
});
|
||||
|
||||
it("is an independent copy each call (writes never touch the fixture)", () => {
|
||||
advanceDeal(store, "security");
|
||||
const fresh = seedEnterpriseDeal();
|
||||
expect(fresh.deal.currentStage).toBe("security");
|
||||
});
|
||||
});
|
||||
|
||||
describe("advanceDeal", () => {
|
||||
it("completes the stage's gating doc and unlocks the next stage", () => {
|
||||
advanceDeal(store, "security");
|
||||
expect(store.deal.currentStage).toBe("procurement");
|
||||
expect(status(store, "doc-agreement-enterprise")).toBe("complete");
|
||||
// Payment paperwork becomes actionable / downloadable on entry.
|
||||
expect(status(store, "doc-pay-online")).toBe("action");
|
||||
expect(status(store, "doc-pay-wire")).toBe("available");
|
||||
});
|
||||
|
||||
it("ignores a stale stage so a double-click can't skip ahead", () => {
|
||||
advanceDeal(store, "security"); // → procurement
|
||||
advanceDeal(store, "security"); // stale, no-op
|
||||
expect(store.deal.currentStage).toBe("procurement");
|
||||
});
|
||||
|
||||
it("is a no-op at the terminal stage", () => {
|
||||
advanceDeal(store, "security"); // → procurement
|
||||
advanceDeal(store, "procurement"); // → active
|
||||
expect(store.deal.currentStage).toBe("active");
|
||||
advanceDeal(store, "active"); // terminal
|
||||
expect(store.deal.currentStage).toBe("active");
|
||||
});
|
||||
});
|
||||
|
||||
describe("document actions", () => {
|
||||
it("signing completes the agreement and advances the deal", () => {
|
||||
signDoc(store, "doc-agreement-enterprise");
|
||||
expect(status(store, "doc-agreement-enterprise")).toBe("complete");
|
||||
expect(store.deal.currentStage).toBe("procurement");
|
||||
});
|
||||
|
||||
it("paying clears payment and advances to implementation", () => {
|
||||
advanceDeal(store, "security"); // → procurement
|
||||
payDeal(store);
|
||||
expect(store.deal.currentStage).toBe("active");
|
||||
expect(status(store, "doc-pay-online")).toBe("complete");
|
||||
});
|
||||
|
||||
it("uploading a PO is an alternate payment path that also advances", () => {
|
||||
advanceDeal(store, "security"); // → procurement
|
||||
uploadPurchaseOrder(store);
|
||||
expect(store.deal.currentStage).toBe("active");
|
||||
});
|
||||
|
||||
it("requesting an on-demand document moves it to pending", () => {
|
||||
requestDoc(store, "sup-custom-review");
|
||||
expect(status(store, "sup-custom-review")).toBe("pending");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* The procurement deal's state machine, the exact server-side semantics the
|
||||
* mock backend enforces, as pure functions over a {@link ProcurementStore}.
|
||||
*
|
||||
* Kept separate from the MSW handler (which just owns one in-memory store and
|
||||
* wires these to endpoints) so the rules are unit-testable without a network,
|
||||
* and so a real backend has a precise spec to mirror. Every function mutates
|
||||
* the store in place, there's a single instance per session.
|
||||
*/
|
||||
|
||||
import {
|
||||
JOURNEY,
|
||||
type Deal,
|
||||
type DealStage,
|
||||
type DocAction,
|
||||
type DocStatus,
|
||||
type LedgerDoc,
|
||||
type LedgerGroup,
|
||||
type SupportingGroup,
|
||||
} from "@portal/mocks/procurement";
|
||||
|
||||
export interface ProcurementStore {
|
||||
deal: Deal;
|
||||
ledger: LedgerGroup[];
|
||||
supporting: SupportingGroup[];
|
||||
}
|
||||
|
||||
/** Document actions that gate a stage, completing them moves the deal forward. */
|
||||
const GATING: DocAction[] = ["sign", "pay", "upload"];
|
||||
|
||||
function nextStage(stage: DealStage): DealStage | null {
|
||||
const i = JOURNEY.findIndex((s) => s.stage === stage);
|
||||
return i >= 0 && i < JOURNEY.length - 1 ? JOURNEY[i + 1].stage : null;
|
||||
}
|
||||
|
||||
function allDocs(store: ProcurementStore): LedgerDoc[] {
|
||||
return [
|
||||
...store.ledger.flatMap((g) => g.docs),
|
||||
...store.supporting.flatMap((g) => g.docs),
|
||||
];
|
||||
}
|
||||
|
||||
function setDocStatus(store: ProcurementStore, id: string, status: DocStatus) {
|
||||
const doc = allDocs(store).find((d) => d.id === id);
|
||||
if (doc) doc.status = status;
|
||||
}
|
||||
|
||||
function stageOfDoc(
|
||||
store: ProcurementStore,
|
||||
id: string,
|
||||
): DealStage | undefined {
|
||||
return store.ledger.find((g) => g.docs.some((d) => d.id === id))?.stage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advance the deal one stage. Completing a stage marks its outstanding gating
|
||||
* docs done; entering the next stage promotes that stage's paperwork from
|
||||
* "pending" to actionable (gating → action needed, downloads → available).
|
||||
* No-ops on a stale `from` so a double-click can't skip a stage.
|
||||
*/
|
||||
export function advanceDeal(store: ProcurementStore, from: DealStage) {
|
||||
if (store.deal.currentStage !== from) return;
|
||||
const to = nextStage(from);
|
||||
if (!to) return;
|
||||
|
||||
store.ledger
|
||||
.find((g) => g.stage === from)
|
||||
?.docs.forEach((d) => {
|
||||
if (d.status === "action") d.status = "complete";
|
||||
});
|
||||
|
||||
store.deal.currentStage = to;
|
||||
|
||||
store.ledger
|
||||
.find((g) => g.stage === to)
|
||||
?.docs.forEach((d) => {
|
||||
if (d.status !== "pending") return;
|
||||
if (GATING.includes(d.action)) d.status = "action";
|
||||
else if (d.action === "download") d.status = "available";
|
||||
});
|
||||
}
|
||||
|
||||
/** Complete the current stage's doc matching an action, then advance past it. */
|
||||
function completeAndAdvance(store: ProcurementStore, action: DocAction) {
|
||||
const stage = store.deal.currentStage;
|
||||
store.ledger
|
||||
.find((g) => g.stage === stage)
|
||||
?.docs.forEach((d) => {
|
||||
if (d.action === action) d.status = "complete";
|
||||
});
|
||||
advanceDeal(store, stage);
|
||||
}
|
||||
|
||||
/** Sign the agreement: complete the doc and advance out of its stage. */
|
||||
export function signDoc(store: ProcurementStore, docId: string) {
|
||||
setDocStatus(store, docId, "complete");
|
||||
const stage = stageOfDoc(store, docId);
|
||||
if (stage && stage === store.deal.currentStage) advanceDeal(store, stage);
|
||||
}
|
||||
|
||||
/** Confirm online payment, then advance to implementation. */
|
||||
export function payDeal(store: ProcurementStore) {
|
||||
completeAndAdvance(store, "pay");
|
||||
}
|
||||
|
||||
/** Upload a purchase order (an alternate payment path), then advance. */
|
||||
export function uploadPurchaseOrder(store: ProcurementStore) {
|
||||
completeAndAdvance(store, "upload");
|
||||
}
|
||||
|
||||
/** Queue an on-demand document, it moves to "pending" until generated. */
|
||||
export function requestDoc(store: ProcurementStore, docId: string) {
|
||||
setDocStatus(store, docId, "pending");
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* A gentle, deterministic 30-point daily series averaging ~`avg`/day, shaped by a sine wave so mock
|
||||
* and Storybook sparklines have something to draw. Shared so the mock handler and the source stories
|
||||
* stay in sync instead of each carrying their own copy of the formula.
|
||||
*/
|
||||
export function sampleDailySeries(avg: number): number[] {
|
||||
return Array.from({ length: 30 }, (_, i) =>
|
||||
Math.round(avg * (0.5 + Math.abs(Math.sin((i + 1) / 3)))),
|
||||
);
|
||||
}
|
||||
@@ -93,7 +93,9 @@ const SOURCES: SourcesResponse = {
|
||||
referenceCount: 1,
|
||||
referencingPolicies: [],
|
||||
config: [],
|
||||
docsTotal: null,
|
||||
docsTotal: 0,
|
||||
docs24h: 0,
|
||||
docs30d: 0,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
.portal-proc {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
padding: 1.5rem;
|
||||
max-width: 84rem;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* Page header */
|
||||
.portal-proc__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.portal-proc__title {
|
||||
margin: 0;
|
||||
font-size: 1.375rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__subtitle {
|
||||
margin: 0.25rem 0 0;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
/* Eyebrow label shared by the journey header + SE block */
|
||||
.portal-proc__eyebrow {
|
||||
display: block;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-text-5);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
/* ── Journey card ─────────────────────────────────────────────────────── */
|
||||
/* Stacked, border-divided sections: header / stepper / trial / next step. */
|
||||
.portal-proc__journey-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 1.25rem 1.5rem;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.portal-proc__journey-title {
|
||||
margin: 0;
|
||||
font-size: 1.0625rem;
|
||||
font-weight: 700;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__journey-sub {
|
||||
margin: 0.25rem 0 0;
|
||||
max-width: 36rem;
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.5;
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
.portal-proc__se {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
text-align: right;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.portal-proc__se .portal-proc__eyebrow {
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.portal-proc__se-name {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__se-email {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-blue);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.portal-proc__se-email:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* Stepper band */
|
||||
.portal-proc__journey-stepper {
|
||||
padding: 1.125rem 1.5rem;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-proc__steps {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.portal-proc__steps--locked {
|
||||
opacity: 0.55;
|
||||
filter: grayscale(0.4);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.portal-proc__step {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
min-width: 4rem;
|
||||
}
|
||||
|
||||
.portal-proc__step-dot {
|
||||
width: 0.875rem;
|
||||
height: 0.875rem;
|
||||
border-radius: 50%;
|
||||
background: var(--color-border-input);
|
||||
}
|
||||
|
||||
.portal-proc__step--complete .portal-proc__step-dot {
|
||||
background: var(--color-green);
|
||||
}
|
||||
|
||||
.portal-proc__step--current .portal-proc__step-dot {
|
||||
background: var(--color-purple);
|
||||
box-shadow: 0 0 0 4px var(--color-purple-light);
|
||||
}
|
||||
|
||||
.portal-proc__step-label {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
color: var(--color-text-5);
|
||||
}
|
||||
|
||||
.portal-proc__step--complete .portal-proc__step-label {
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
.portal-proc__step--current .portal-proc__step-label {
|
||||
font-weight: 700;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
/* Connector aligns with the 0.875rem dots: (14px − 2px) / 2 = 6px down */
|
||||
.portal-proc__step-line {
|
||||
flex: 1;
|
||||
height: 2px;
|
||||
margin: 0.375rem 0.375rem 0;
|
||||
background: var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-proc__step-line[data-filled="true"] {
|
||||
background: var(--color-green);
|
||||
}
|
||||
|
||||
/* Trial status strip (shown while evaluating) */
|
||||
.portal-proc__trial {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 0.75rem 1.5rem;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
background: var(--color-bg-code);
|
||||
}
|
||||
|
||||
.portal-proc__trial-title {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__trial-dim {
|
||||
font-size: 0.78125rem;
|
||||
color: var(--color-text-5);
|
||||
}
|
||||
|
||||
.portal-proc__trial-key {
|
||||
font-family:
|
||||
ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
|
||||
font-size: 0.6875rem;
|
||||
color: var(--color-text-4);
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border-input);
|
||||
border-radius: 0.375rem;
|
||||
padding: 0.1875rem 0.5rem;
|
||||
}
|
||||
|
||||
/* Next-step row: one primary action at a time */
|
||||
.portal-proc__next {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
padding: 1rem 1.5rem;
|
||||
}
|
||||
|
||||
.portal-proc__next-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
font-size: 0.84375rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__next-dot {
|
||||
width: 0.5rem;
|
||||
height: 0.5rem;
|
||||
border-radius: 50%;
|
||||
background: var(--color-amber);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.portal-proc__next-dot[data-live="true"] {
|
||||
background: var(--color-green);
|
||||
}
|
||||
|
||||
/* ── Documents card ───────────────────────────────────────────────────── */
|
||||
.portal-proc__docs-head {
|
||||
padding: 1.125rem 1.5rem;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-proc__docs-title {
|
||||
margin: 0;
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 700;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__docs-sub {
|
||||
margin: 0.25rem 0 0;
|
||||
font-size: 0.78125rem;
|
||||
color: var(--color-text-5);
|
||||
}
|
||||
|
||||
.portal-proc__docs-body {
|
||||
padding: 0.375rem 1.5rem 1.125rem;
|
||||
}
|
||||
|
||||
/* Accordion spacing — the disclosure chrome itself lives in shared Collapsible
|
||||
(.sui-collapsible); here we only space the stacked sections. */
|
||||
.portal-proc__docs-body .sui-collapsible {
|
||||
margin-top: 0.875rem;
|
||||
}
|
||||
|
||||
/* Stage header bits */
|
||||
.portal-proc__stage-dot {
|
||||
width: 0.4375rem;
|
||||
height: 0.4375rem;
|
||||
border-radius: 50%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.portal-proc__stage-dot[data-state="done"] {
|
||||
background: var(--color-green);
|
||||
}
|
||||
|
||||
.portal-proc__stage-dot[data-state="current"] {
|
||||
background: var(--color-purple);
|
||||
}
|
||||
|
||||
.portal-proc__stage-dot[data-state="upcoming"] {
|
||||
background: var(--color-border-input);
|
||||
}
|
||||
|
||||
.portal-proc__stage-label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.03em;
|
||||
text-transform: uppercase;
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
.portal-proc__stage-label[data-current] {
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__stage-hint {
|
||||
font-size: 0.71875rem;
|
||||
color: var(--color-text-5);
|
||||
}
|
||||
|
||||
.portal-proc__stage-count {
|
||||
font-size: 0.6875rem;
|
||||
color: var(--color-text-5);
|
||||
}
|
||||
|
||||
/* Document lists inside the accordion */
|
||||
.portal-proc__doc-list {
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-proc__doc-list--boxed {
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: 0.5rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Supporting section — extra separation from the stage accordion above it.
|
||||
Scoped to match the general .sui-collapsible spacing rule's specificity. */
|
||||
.portal-proc__docs-body .portal-proc__supporting-acc {
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.portal-proc__supporting-head {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.125rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.portal-proc__supporting-sub {
|
||||
font-size: 0.71875rem;
|
||||
font-weight: 400;
|
||||
line-height: 1.45;
|
||||
color: var(--color-text-5);
|
||||
}
|
||||
|
||||
.portal-proc__acc-toggle-label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-proc__supporting-groups {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
border-top: 1px solid var(--color-border-light);
|
||||
padding: 0.875rem;
|
||||
}
|
||||
|
||||
.portal-proc__group-label {
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-text-5);
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
/* ── Document rows (ledger + supporting) ──────────────────────────────── */
|
||||
.portal-proc__doc {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem 0.875rem;
|
||||
border-bottom: 1px solid var(--color-border-light);
|
||||
}
|
||||
|
||||
.portal-proc__doc:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.portal-proc__doc[data-locked] {
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.portal-proc__doc-text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.portal-proc__doc-name-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.portal-proc__doc-name {
|
||||
font-size: 0.84375rem;
|
||||
font-weight: 600;
|
||||
color: var(--color-text-1);
|
||||
}
|
||||
|
||||
.portal-proc__doc-sub {
|
||||
margin: 0.0625rem 0 0;
|
||||
font-size: 0.71875rem;
|
||||
line-height: 1.4;
|
||||
color: var(--color-text-5);
|
||||
}
|
||||
|
||||
.portal-proc__doc-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ── Locked state ─────────────────────────────────────────────────────── */
|
||||
.portal-proc__locked {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
/* ── Action modal ─────────────────────────────────────────────────────── */
|
||||
.portal-proc__modal-body {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.55;
|
||||
color: var(--color-text-2);
|
||||
}
|
||||
|
||||
.portal-proc__modal-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 0.625rem;
|
||||
}
|
||||
|
||||
.portal-proc__upload {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.portal-proc__upload-input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.portal-proc__upload-name {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-4);
|
||||
}
|
||||
|
||||
@media (max-width: 48rem) {
|
||||
.portal-proc__journey-head {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.portal-proc__se {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.portal-proc__steps {
|
||||
overflow-x: auto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Card, Skeleton, StatusBadge } from "@shared/components";
|
||||
import { useTier } from "@portal/contexts/TierContext";
|
||||
import { useAsync } from "@portal/hooks/useAsync";
|
||||
import {
|
||||
advanceStage,
|
||||
fetchProcurement,
|
||||
type DealStage,
|
||||
type LedgerDoc,
|
||||
type ProcurementResponse,
|
||||
} from "@portal/api/procurement";
|
||||
import { DealJourney } from "@portal/components/procurement/DealJourney";
|
||||
import { DocumentLedger } from "@portal/components/procurement/DocumentLedger";
|
||||
import { ActionModal } from "@portal/components/procurement/ActionModal";
|
||||
import { LockedState } from "@portal/components/procurement/LockedState";
|
||||
import "@portal/views/Procurement.css";
|
||||
|
||||
/**
|
||||
* Procurement: the enterprise commercial journey (trial to live) plus the
|
||||
* document ledger. Enterprise-only: free/pro buyers see a locked upgrade state.
|
||||
*/
|
||||
export function Procurement() {
|
||||
const { t } = useTranslation();
|
||||
const { tier } = useTier();
|
||||
const [activeDoc, setActiveDoc] = useState<LedgerDoc | null>(null);
|
||||
const [advancing, setAdvancing] = useState(false);
|
||||
|
||||
const state = useAsync<ProcurementResponse>(
|
||||
() => fetchProcurement(tier),
|
||||
[tier],
|
||||
);
|
||||
|
||||
// Write actions return the new canonical state; we hold it here so the
|
||||
// journey reflects every action immediately. Cleared when the tier (and so
|
||||
// the deal) changes, falling back to whatever the GET loaded.
|
||||
const [applied, setApplied] = useState<ProcurementResponse | null>(null);
|
||||
useEffect(() => setApplied(null), [tier]);
|
||||
const data = applied ?? (state.loading ? null : state.data);
|
||||
|
||||
async function onAdvance(stage: DealStage) {
|
||||
setAdvancing(true);
|
||||
try {
|
||||
setApplied(await advanceStage(stage));
|
||||
} finally {
|
||||
setAdvancing(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="portal-proc">
|
||||
<header className="portal-proc__header">
|
||||
<div>
|
||||
<h1 className="portal-proc__title">{t("procurement.title")}</h1>
|
||||
<p className="portal-proc__subtitle">{t("procurement.subtitle")}</p>
|
||||
</div>
|
||||
<StatusBadge tone="purple" size="md">
|
||||
{t("procurement.enterpriseBadge")}
|
||||
</StatusBadge>
|
||||
</header>
|
||||
|
||||
{state.loading && (
|
||||
<Card padding="loose">
|
||||
<Skeleton width="12rem" height="1.25rem" />
|
||||
<Skeleton height="8rem" />
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{data && !data.unlocked && (
|
||||
<LockedState
|
||||
journey={data.journey}
|
||||
onTalkToSales={() => {
|
||||
// TODO(backend): POST /v1/procurement/sales-contact, for now this
|
||||
// is the sidebar's upgrade path; hand off to the account team.
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{data && data.unlocked && data.deal && (
|
||||
<>
|
||||
<DealJourney
|
||||
deal={data.deal}
|
||||
journey={data.journey}
|
||||
onAdvance={onAdvance}
|
||||
advancing={advancing}
|
||||
/>
|
||||
<DocumentLedger
|
||||
groups={data.ledger}
|
||||
supporting={data.supporting}
|
||||
journey={data.journey}
|
||||
currentStage={data.deal.currentStage}
|
||||
onAction={setActiveDoc}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<ActionModal
|
||||
doc={activeDoc}
|
||||
onClose={() => setActiveDoc(null)}
|
||||
onDone={(next) => {
|
||||
setApplied(next);
|
||||
setActiveDoc(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -238,6 +238,13 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.portal-sparkline {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 0.5rem;
|
||||
color: var(--color-blue);
|
||||
}
|
||||
|
||||
.portal-sources__chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -16,11 +16,13 @@ vi.mock("react-i18next", () => ({
|
||||
|
||||
const fetchSources = vi.fn();
|
||||
const fetchSource = vi.fn();
|
||||
const fetchSourceDocCounts = vi.fn();
|
||||
const createSource = vi.fn();
|
||||
const deleteSource = vi.fn();
|
||||
vi.mock("@portal/api/sources", () => ({
|
||||
fetchSources: () => fetchSources(),
|
||||
fetchSource: (id: string) => fetchSource(id),
|
||||
fetchSourceDocCounts: (id: string) => fetchSourceDocCounts(id),
|
||||
createSource: (source: unknown) => createSource(source),
|
||||
deleteSource: (id: string) => deleteSource(id),
|
||||
}));
|
||||
@@ -43,7 +45,9 @@ const RESPONSE: SourcesResponse = {
|
||||
{ id: "pol-2", name: "Classification" },
|
||||
],
|
||||
config: [{ label: "Directory", value: "/data/incoming" }],
|
||||
docsTotal: null,
|
||||
docsTotal: 1240,
|
||||
docs24h: 18,
|
||||
docs30d: 540,
|
||||
},
|
||||
{
|
||||
id: "src-orphan",
|
||||
@@ -53,7 +57,9 @@ const RESPONSE: SourcesResponse = {
|
||||
referenceCount: 0,
|
||||
referencingPolicies: [],
|
||||
config: [{ label: "Directory", value: "/tmp/scratch" }],
|
||||
docsTotal: null,
|
||||
docsTotal: 1240,
|
||||
docs24h: 18,
|
||||
docs30d: 540,
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -70,6 +76,8 @@ describe("Sources view", () => {
|
||||
beforeEach(() => {
|
||||
fetchSources.mockReset();
|
||||
fetchSource.mockReset();
|
||||
fetchSourceDocCounts.mockReset();
|
||||
fetchSourceDocCounts.mockResolvedValue([]);
|
||||
createSource.mockReset();
|
||||
deleteSource.mockReset();
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
createSource,
|
||||
deleteSource,
|
||||
fetchSource,
|
||||
fetchSourceDocCounts,
|
||||
fetchSources,
|
||||
type Source,
|
||||
type SourcesResponse,
|
||||
@@ -49,6 +50,21 @@ export function Sources() {
|
||||
const sources = data?.sources ?? [];
|
||||
const expanded = sources.find((s) => s.id === expandedId) ?? null;
|
||||
|
||||
// The 30-day sparkline series lives off the list endpoint; fetch it for the one
|
||||
// expanded row only (empty while collapsed, so no request fires).
|
||||
const docSeriesState = useAsync<{ id: string; series: number[] }>(
|
||||
() =>
|
||||
expandedId
|
||||
? fetchSourceDocCounts(expandedId).then((series) => ({
|
||||
id: expandedId,
|
||||
series,
|
||||
}))
|
||||
: Promise.resolve({ id: "", series: [] }),
|
||||
[expandedId],
|
||||
);
|
||||
const docSeries =
|
||||
docSeriesState.data?.id === expandedId ? docSeriesState.data.series : [];
|
||||
|
||||
function openCreate() {
|
||||
setEditingSource(null);
|
||||
setWizardOpen(true);
|
||||
@@ -166,6 +182,7 @@ export function Sources() {
|
||||
{expanded && (
|
||||
<SourceDetailCard
|
||||
source={expanded}
|
||||
docSeries={docSeries}
|
||||
onClose={() => setExpandedId(null)}
|
||||
onEdit={openEdit}
|
||||
onTogglePause={togglePause}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
.sui-collapsible {
|
||||
border: 1px solid var(--color-border-light);
|
||||
border-radius: 0.5625rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sui-collapsible__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
padding: 0.75rem 0.875rem;
|
||||
background: var(--color-surface);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background-color 0.15s ease;
|
||||
}
|
||||
|
||||
.sui-collapsible__head:hover {
|
||||
background: var(--color-bg-hover);
|
||||
}
|
||||
|
||||
.sui-collapsible__head-main {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sui-collapsible__head-end {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
margin-left: auto;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sui-collapsible__chevron {
|
||||
color: var(--color-text-5);
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.sui-collapsible__chevron[data-open="true"] {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
/* Grid-rows disclosure: 0fr → 1fr, no magic max-height */
|
||||
.sui-collapsible__body {
|
||||
display: grid;
|
||||
grid-template-rows: 0fr;
|
||||
transition: grid-template-rows 0.25s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
.sui-collapsible__body[data-open="true"] {
|
||||
grid-template-rows: 1fr;
|
||||
}
|
||||
|
||||
.sui-collapsible__body-inner {
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useState } from "react";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { Collapsible } from "@shared/components/Collapsible";
|
||||
|
||||
const meta: Meta<typeof Collapsible> = {
|
||||
title: "Components/Collapsible",
|
||||
component: Collapsible,
|
||||
parameters: { layout: "padded" },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof Collapsible>;
|
||||
|
||||
// open/onToggle are a controlled pair, so the stories own the state.
|
||||
export const Default: Story = {
|
||||
render: () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<div style={{ maxWidth: "40rem" }}>
|
||||
<Collapsible
|
||||
open={open}
|
||||
onToggle={() => setOpen((o) => !o)}
|
||||
header={<strong>Section title</strong>}
|
||||
aside={<span style={{ fontSize: "0.75rem" }}>3 items</span>}
|
||||
>
|
||||
<div style={{ padding: "0.875rem", borderTop: "1px solid #eee" }}>
|
||||
Body content revealed when the section is open.
|
||||
</div>
|
||||
</Collapsible>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
// Stacked instances form an accordion; each section toggles independently.
|
||||
export const Accordion: Story = {
|
||||
render: () => {
|
||||
const [open, setOpen] = useState<number | null>(0);
|
||||
const sections = ["Trial", "Quote", "Agreement"];
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
maxWidth: "40rem",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "0.75rem",
|
||||
}}
|
||||
>
|
||||
{sections.map((label, i) => (
|
||||
<Collapsible
|
||||
key={label}
|
||||
open={open === i}
|
||||
onToggle={() => setOpen(open === i ? null : i)}
|
||||
header={<strong>{label}</strong>}
|
||||
>
|
||||
<div style={{ padding: "0.875rem", borderTop: "1px solid #eee" }}>
|
||||
{label} details.
|
||||
</div>
|
||||
</Collapsible>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ReactNode } from "react";
|
||||
import "@shared/components/Collapsible.css";
|
||||
|
||||
export interface CollapsibleProps {
|
||||
/** Whether the section is expanded. Controlled — pair with `onToggle`. */
|
||||
open: boolean;
|
||||
onToggle: () => void;
|
||||
/** Header content (left/main side); the chevron is appended automatically. */
|
||||
header: ReactNode;
|
||||
/** Right-aligned header content shown before the chevron (a count, a label). */
|
||||
aside?: ReactNode;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A single bordered disclosure section: an always-visible header that toggles,
|
||||
* and a body that animates open/closed via a grid-rows transition (no magic
|
||||
* max-height). Stack several to build an accordion. Header content is fully
|
||||
* caller-supplied, so it suits both terse and rich (icon + chips + count) rows.
|
||||
*/
|
||||
export function Collapsible({
|
||||
open,
|
||||
onToggle,
|
||||
header,
|
||||
aside,
|
||||
children,
|
||||
className,
|
||||
}: CollapsibleProps) {
|
||||
return (
|
||||
<div
|
||||
className={["sui-collapsible", className ?? ""].filter(Boolean).join(" ")}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="sui-collapsible__head"
|
||||
onClick={onToggle}
|
||||
aria-expanded={open}
|
||||
>
|
||||
<span className="sui-collapsible__head-main">{header}</span>
|
||||
<span className="sui-collapsible__head-end">
|
||||
{aside}
|
||||
<svg
|
||||
className="sui-collapsible__chevron"
|
||||
data-open={open}
|
||||
viewBox="0 0 24 24"
|
||||
width={16}
|
||||
height={16}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden
|
||||
>
|
||||
<polyline points="6 9 12 15 18 9" />
|
||||
</svg>
|
||||
</span>
|
||||
</button>
|
||||
<div className="sui-collapsible__body" data-open={open}>
|
||||
<div className="sui-collapsible__body-inner">{children}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ export * from "@shared/components/Banner";
|
||||
export * from "@shared/components/Toast";
|
||||
|
||||
// Compound
|
||||
export * from "@shared/components/Collapsible";
|
||||
export * from "@shared/components/Tabs";
|
||||
export * from "@shared/components/Dropdown";
|
||||
export * from "@shared/components/Drawer";
|
||||
|
||||
Reference in New Issue
Block a user