fix(portfolio): publish new complete forecast regardless of request window (WealthLedger/backend#55) (#156)
Backend verify / commits (push) Skipped
Backend verify / security (push) Successful in 1m11s
Backend verify / verify (push) Failing after 7m6s

This commit was merged in pull request #156.
This commit is contained in:
2026-11-02 22:42:46 +03:00
parent 554410a271
commit 169bee1da5
5 changed files with 182 additions and 29 deletions
@@ -26,6 +26,7 @@ export class ForecastRepository {
membershipRevision: number;
portfolioProjection: string;
portfolios: { accountId: string; dataRevision: number }[];
replacesLatest?: boolean;
revision: string;
scopeKey: string;
sources: ForecastSourceVersion[];
@@ -51,32 +52,30 @@ export class ForecastRepository {
const previous = await tx.tbankForecast.findUnique({
where: { userId_revision_scopeKey: key },
});
// An events read serves the account's latest complete forecast whatever
// the requested window; other scopes keep their exact-key row.
const requestedWindow = eventsWindow(input.scopeKey);
const saved = previous ?? (requestedWindow
? (
await tx.tbankForecast.findMany({
where: {
...owner,
scopeKey: { startsWith: 'events/' },
membershipRevision: input.membershipRevision,
const latest = requestedWindow
? await tx.tbankForecast.findFirst({
where: {
...owner,
// scopeKey is `events/[accountId,from,to]` JSON: pin the account.
scopeKey: {
startsWith: `events/[${JSON.stringify(requestedWindow.accountId)},`,
},
})
).find((forecast) => {
const window = eventsWindow(forecast.scopeKey);
return (
window &&
window.accountId === requestedWindow.accountId &&
window.from <= requestedWindow.to &&
requestedWindow.from <= window.to
);
membershipRevision: input.membershipRevision,
},
orderBy: [{ calculatedAt: 'desc' }, { scopeKey: 'asc' }],
})
: null);
: previous;
const fallback =
saved?.membershipRevision === input.membershipRevision
? saved
: null;
latest?.membershipRevision === input.membershipRevision ? latest : null;
if (!input.candidate) return fallback;
if (!previous && fallback) return fallback;
// Only the default window may replace the latest forecast; an explicit
// range is served from it and publishes only when nothing is saved.
if (!input.replacesLatest && fallback && fallback.scopeKey !== input.scopeKey) {
return fallback;
}
const portfolios = await tx.tbankPortfolio.findMany({
where: {
...owner,
@@ -152,7 +151,7 @@ export class ForecastRepository {
) as Prisma.InputJsonObject;
const timestamps = input.timestamps as Prisma.InputJsonArray;
if (
fallback &&
fallback?.scopeKey === input.scopeKey &&
isDeepStrictEqual(fallback.dependencyRevisions, revisions) &&
isDeepStrictEqual(fallback.sourceTimestamps, timestamps)
) {