Files
backend/src/modules/investments/portfolio/infrastructure/forecast.repository.ts
T
ksv741 d6e6c4ace5
Backend security / security (push) Successful in 8s
Backend verify / verify (push) Failing after 10m45s
Conventional commits / commits (pull_request) Successful in 29s
Backend security / security (pull_request) Successful in 8s
Backend verify / verify (pull_request) Failing after 10m37s
feat!: persist T-Bank data and synchronize reads
Store account membership, portfolio, operations, forecasts and market sources in SQLite.
Coalesce scoped refreshes, fence connection revisions, preserve complete financial
snapshots and stabilize operation period state.

BREAKING CHANGE: investment reads return data/meta resource envelopes and locally
persisted snapshots; consumers must use the matching OpenAPI contract and explicit
synchronization endpoints.
2026-09-26 21:29:15 +03:00

155 lines
4.9 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { isDeepStrictEqual } from 'node:util';
import type { Prisma } from '../../../../../generated/prisma/client';
import { PrismaService } from '../../../../prisma/prisma.service';
export type ForecastSourceVersion = {
instrumentUid: string;
source: string;
kind: string;
rangeKey: string;
dataRevision: number;
fetchedAt: Date;
};
const forecastSourceReadBatchSize = 100;
@Injectable()
export class ForecastRepository {
constructor(private readonly prisma: PrismaService) {}
resolve(input: {
userId: string;
revision: string;
membershipRevision: number;
scopeKey: string;
candidate?: object;
portfolioProjection: string;
portfolios: { accountId: string; dataRevision: number }[];
sources: ForecastSourceVersion[];
timestamps: { resourceKey: string; at: string }[];
}) {
return this.prisma.$transaction(async (tx) => {
const owner = { userId: input.userId, revision: input.revision };
if (input.candidate) {
const current = await tx.tbankConnection.updateMany({
where: {
...owner,
membershipRevision: input.membershipRevision,
invalidToken: false,
},
data: { membershipRevision: { increment: 0 } },
});
if (!current.count) return null;
}
const connection = await tx.tbankConnection.findFirst({
where: {
...owner,
membershipRevision: input.membershipRevision,
invalidToken: false,
},
});
if (!connection) return null;
const key = { ...owner, scopeKey: input.scopeKey };
const previous = await tx.tbankForecast.findUnique({
where: { userId_revision_scopeKey: key },
});
const fallback =
previous?.membershipRevision === input.membershipRevision
? previous
: null;
if (!input.candidate) return fallback;
const portfolios = await tx.tbankPortfolio.findMany({
where: {
...owner,
accountId: { in: input.portfolios.map((row) => row.accountId) },
},
select: { accountId: true, dataRevision: true },
});
if (
input.portfolios.some(
(expected) =>
!portfolios.some(
(row) =>
row.accountId === expected.accountId &&
row.dataRevision === expected.dataRevision,
),
)
)
return fallback;
// Four identity parameters per source: stay below SQLite's parameter limit.
const sources: ForecastSourceVersion[] = [];
for (
let offset = 0;
offset < input.sources.length;
offset += forecastSourceReadBatchSize
)
sources.push(
...(await tx.tbankInstrumentSource.findMany({
where: {
provider: 'tbank',
OR: input.sources
.slice(offset, offset + forecastSourceReadBatchSize)
.map(({ instrumentUid, source, kind, rangeKey }) => ({
instrumentUid,
source,
kind,
rangeKey,
})),
},
select: {
instrumentUid: true,
source: true,
kind: true,
rangeKey: true,
dataRevision: true,
fetchedAt: true,
},
})),
);
if (
input.sources.some(
(expected) =>
!sources.some(
(row) =>
row.instrumentUid === expected.instrumentUid &&
row.source === expected.source &&
row.kind === expected.kind &&
row.rangeKey === expected.rangeKey &&
row.dataRevision === expected.dataRevision &&
row.fetchedAt.valueOf() === expected.fetchedAt.valueOf(),
),
)
)
return fallback;
const revisions = JSON.parse(
JSON.stringify({
portfolioProjection: input.portfolioProjection,
portfolios: input.portfolios,
sources: input.sources,
}),
) as Prisma.InputJsonObject;
const timestamps = input.timestamps as Prisma.InputJsonArray;
if (
fallback &&
isDeepStrictEqual(fallback.dependencyRevisions, revisions) &&
isDeepStrictEqual(fallback.sourceTimestamps, timestamps)
)
return fallback;
const data = {
membershipRevision: input.membershipRevision,
payload: JSON.parse(
JSON.stringify(input.candidate),
) as Prisma.InputJsonObject,
dependencyRevisions: revisions,
sourceTimestamps: timestamps,
calculatedAt: new Date(),
};
return tx.tbankForecast.upsert({
where: { userId_revision_scopeKey: key },
create: { ...key, ...data },
update: { ...data, dataRevision: { increment: 1 } },
});
});
}
}