fix(officer): scope reasons and forecasts to the run that produced the score

Both repositories were queried by enterprise alone, so every reason code and
every forecast point ever written came back. A run-287 model score was being
rendered beside run-145 rule sentences, and one enterprise's six-month chart
drew 102 points from seventeen different runs.

Now read through findByEnterpriseIdAndRunId..., resolved from the newest run.
The same unscoped query existed in EnterpriseAppService and is fixed there
too.

Also adds GET /officer/app-enrolled: which borrowers on this caller's book
have a phone login. Not every borrower is enrolled and that is the design —
the platform scores a book from core banking and UPI whether or not the owner
installs anything — so the console needs to know rather than offering to open
an app that does not exist. Scoped by intersecting with the caller's own book,
so it cannot be used to discover that an id exists on another bank's.

EnterpriseRow gains firstBreachHorizon, firstBreachMonth and topDriver so the
dashboard can rank by lead time instead of by composite score.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
LincPay
2026-08-25 13:44:22 +05:30
co-authored by Claude Opus 5
parent 6b4aec468d
commit e7c93e29ea
6 changed files with 108 additions and 4 deletions
@@ -41,6 +41,7 @@ public class OfficerService {
/** Sentinel used by the console when no block filter is applied. */
public static final String ALL_BLOCKS = "ALL";
private final com.lincfusion.udyamlinc.auth.UdyamUserRepository userRepository;
private final EnterpriseRepository enterpriseRepository;
private final LedgerEntryRepository ledgerRepository;
private final SectorRepository sectorRepository;
@@ -66,6 +67,28 @@ public class OfficerService {
return toRows(enterprisesIn(tenant, block));
}
/**
* Which of this caller's borrowers can sign in to the phone app.
*
* <p>Not every borrower is enrolled, and that is the design rather than a gap:
* the platform scores a book from core banking and UPI whether or not the owner
* ever installs anything. A console that offered to open the app for a borrower
* who has none would be promising a screen that does not exist.
*
* <p>Scoped by intersecting with the caller's own book, so this cannot be used
* to discover that an id exists on another bank's book.
*/
public List<String> appEnrolled(TenantContext tenant, String block) {
List<String> mine = enterprisesIn(tenant, block).stream()
.map(Enterprise::getEnterpriseId).toList();
if (mine.isEmpty()) return List.of();
return userRepository.findByScopeIgnoreCaseAndEnterpriseIdIn("ENTERPRISE", mine).stream()
.map(com.lincfusion.udyamlinc.auth.UdyamUser::getEnterpriseId)
.filter(java.util.Objects::nonNull)
.sorted()
.toList();
}
public EnterpriseDetailResponse detail(TenantContext tenant, String enterpriseId) {
Enterprise enterprise = requireEnterprise(tenant, enterpriseId);
StressScore score = scoreRepository.findFirstByEnterpriseIdOrderByComputedAtDesc(enterpriseId).orElse(null);
@@ -75,8 +98,18 @@ public class OfficerService {
sectorCode(enterprise),
districtName(enterprise),
score,
reasonRepository.findByEnterpriseIdOrderByRankAsc(enterpriseId),
pointRepository.findByEnterpriseIdOrderByHorizonAsc(enterpriseId),
// Scoped to the run the score came from. Unscoped, this returned
// every reason ever stored for the enterprise, so tonight's model
// score arrived beside sentences a rule engine wrote months ago —
// one number, two engines explaining it. If the score predates the
// reason table, an empty list is the honest answer.
score == null || score.getRunId() == null
? List.of()
: reasonRepository.findByEnterpriseIdAndRunIdOrderByRankAsc(enterpriseId, score.getRunId()),
// Scoped to the score's run, for the same reason the reason codes are.
score == null || score.getRunId() == null
? List.of()
: pointRepository.findByEnterpriseIdAndRunIdOrderByHorizonAsc(enterpriseId, score.getRunId()),
alertRepository.findByEnterpriseIdOrderByRaisedAtDesc(enterpriseId),
visitRepository.findByEnterpriseIdOrderByDueDateAsc(enterpriseId),
ledgerRepository.findByEnterpriseIdOrderByEntryDateDesc(enterpriseId).stream().limit(60).toList());
@@ -238,6 +271,23 @@ public class OfficerService {
Map<String, List<StressScore>> history = scoreRepository.findAll().stream()
.collect(Collectors.groupingBy(StressScore::getEnterpriseId));
// Lead time and the leading reason, both from the newest run only. Three
// bulk queries rather than two per enterprise — this feeds a list of 263.
Long latestRun = scoreRepository.findAll().stream()
.map(StressScore::getRunId).filter(java.util.Objects::nonNull)
.max(Long::compareTo).orElse(null);
Map<String, ForecastPoint> firstBreach = latestRun == null ? Map.of()
: pointRepository.findByRunIdOrderByHorizonAsc(latestRun).stream()
.filter(p -> Boolean.TRUE.equals(p.getBreach()))
.collect(Collectors.toMap(ForecastPoint::getEnterpriseId, Function.identity(),
(a, b) -> a.getHorizon() <= b.getHorizon() ? a : b));
Map<String, ReasonCode> topReason = latestRun == null ? Map.of()
: reasonRepository.findByRunIdOrderByRankAsc(latestRun).stream()
.collect(Collectors.toMap(ReasonCode::getEnterpriseId, Function.identity(),
(a, b) -> a.getRank() <= b.getRank() ? a : b));
return rows.stream()
.map(e -> new EnterpriseRow(
e.getId(),
@@ -254,7 +304,15 @@ public class OfficerService {
e.getScore(),
e.getBand(),
trendOf(history.get(e.getEnterpriseId()), e.getScore()),
e.getLastScoredAt() == null ? null : e.getLastScoredAt().toString()))
e.getLastScoredAt() == null ? null : e.getLastScoredAt().toString(),
firstBreach.containsKey(e.getEnterpriseId())
? firstBreach.get(e.getEnterpriseId()).getHorizon() : null,
firstBreach.containsKey(e.getEnterpriseId())
? firstBreach.get(e.getEnterpriseId()).getMonth() : null,
topReason.containsKey(e.getEnterpriseId())
? topReason.get(e.getEnterpriseId()).getSentenceEn() : null,
topReason.containsKey(e.getEnterpriseId())
? topReason.get(e.getEnterpriseId()).getSentenceHi() : null))
.toList();
}