Compare commits
13
Commits
v2.4.0
...
a7e98c0ec3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7e98c0ec3 | ||
|
|
4e3e58e288 | ||
|
|
1ddebbdbad | ||
|
|
6488e5d1ad | ||
|
|
5c7ff312ee | ||
|
|
0f65ba7f13 | ||
|
|
fa0a6e5603 | ||
|
|
bade5fae1c | ||
|
|
1a5de9bebd | ||
|
|
aeb4647fda | ||
|
|
169bee1da5 | ||
|
|
554410a271 | ||
|
|
a80bbbf1e2 |
+6
-6
@@ -29,9 +29,9 @@ market — котировками, income — выплатами/личными
|
||||
domain из-за extraction в функцию. Boundary mappers преобразуют внешние records;
|
||||
чистые расчёты portfolio/banking остаются у domain owner.
|
||||
|
||||
PrismaService владеет DB lifecycle. Самостоятельные use cases получают данные
|
||||
через concrete repositories; существующие связные CRUD/transaction services
|
||||
сохраняют прямые queries по [data convention](conventions/data.md).
|
||||
PrismaService владеет DB lifecycle. Application services/use cases получают
|
||||
данные через concrete repositories; запросы и CAS живут в infrastructure
|
||||
по [data convention](conventions/data.md).
|
||||
Money — currency + decimal string; расчёты используют точные общие helpers.
|
||||
|
||||
Auth управляет identity/session; TbankAccessService проверяет доступ к счёту и
|
||||
@@ -201,9 +201,9 @@ Circular dependencies устраняй изменением ownership/compositio
|
||||
конкретные infrastructure providers, зарегистрированные module. Infrastructure
|
||||
может использовать application types/input и domain rules; новые interfaces
|
||||
ради инверсии зависимостей не обязательны. Domain не импортирует presentation или
|
||||
infrastructure. Существующие связные CRUD/transaction services могут сохранять прямые queries
|
||||
по [Data](conventions/data.md); use case получает данные через repository и сам
|
||||
Prisma queries не выполняет. Entity/interface на каждую таблицу не требуется.
|
||||
infrastructure. Application не строит Prisma queries: use case и связный CRUD
|
||||
service обращаются к репозиторию по [Data](conventions/data.md). Entity/interface
|
||||
на каждую таблицу не требуется.
|
||||
DTO остаются транспортными runtime classes; существующее использование DTO
|
||||
на application boundary допустимо по [HTTP API](conventions/http-api.md).
|
||||
|
||||
|
||||
+10
-10
@@ -34,19 +34,19 @@ candidate, не повод дублировать их при новом use cas
|
||||
вызывает repository, затем чистый `bankSummary` и формирует ответ. Prisma records
|
||||
не становятся domain entities: расчёт получает только нужные ему значения.
|
||||
|
||||
Не создавай обёртку на каждый вызов Prisma. Существующие связные CRUD/transaction
|
||||
services (auth, lifecycle подключения, изменения карт/операций/категорий)
|
||||
сохраняют queries рядом с CAS и проверками инварианта, если их перенос требует
|
||||
лишь набора pass-through методов. Новая самостоятельная read/write capability
|
||||
получает repository method; самостоятельный use case не выполняет Prisma queries.
|
||||
`BankCardsRepository.write` сохраняет общую retry/transaction boundary для
|
||||
существующих banking services. Такой callback с Prisma transaction client —
|
||||
локальная техническая граница этих services, не API для domain или use cases.
|
||||
Application-код не импортирует PrismaService и не строит Prisma queries.
|
||||
Репозиторий владеет запросом и CAS-проверкой результата, а application —
|
||||
правилами и формированием ответа. Типы Prisma допустимы только в type-only
|
||||
импортах для существующей транзакционной границы. Не создавай обёртку
|
||||
на каждый вызов Prisma без текущего потребителя. `BankCardsRepository.write`
|
||||
сохраняет retry/transaction boundary для банковских записей; callback с
|
||||
transaction client — локальная техническая граница, не API для domain.
|
||||
|
||||
Выбирай только нужные данные, сохраняй user/account ownership в запросах и
|
||||
application checks. Предварительный lookup не заменяет unique constraint при race.
|
||||
Пример: AuthService обрабатывает P2002 и использует conditional `updateMany`
|
||||
для refresh rotation. Сначала пойми invariant; не копируй его flow в другой use case.
|
||||
Пример: AuthRepository преобразует P2002 в результат регистрации и выполняет
|
||||
conditional `updateMany` для refresh rotation; AuthService сохраняет HTTP
|
||||
error contract. Сначала пойми invariant; не копируй его flow в другой use case.
|
||||
|
||||
Transaction не охватывает сетевой T-Bank вызов как будто это одна atomic DB
|
||||
операция. Планируй порядок и compensation по текущей задаче; не удерживай DB
|
||||
|
||||
@@ -67,7 +67,7 @@ jobs:
|
||||
- name: Audit runtime and development dependencies
|
||||
run: |
|
||||
npm audit --omit=dev --audit-level=low
|
||||
npm audit --include=dev --audit-level=high --ignore-advisory=GHSA-hp3w-g68c-fv3c
|
||||
npm audit --include=dev --audit-level=high
|
||||
|
||||
verify:
|
||||
needs: [commits, security]
|
||||
|
||||
+3
-2
@@ -158,13 +158,14 @@ export default defineConfig(
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/**/*.use-case.ts'],
|
||||
files: ['src/**/application/**/*.ts'],
|
||||
ignores: tests,
|
||||
rules: {
|
||||
'no-restricted-imports': ['error', {
|
||||
patterns: [{
|
||||
group: prismaImports,
|
||||
message: 'Use cases obtain data through concrete repositories.',
|
||||
allowTypeImports: true,
|
||||
message: 'Application code obtains data through concrete repositories; type-only imports are allowed.',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
|
||||
+30
-1
@@ -2,7 +2,8 @@
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended",
|
||||
":semanticCommitTypeAll(chore)"
|
||||
":semanticCommitTypeAll(chore)",
|
||||
"security:minimumReleaseAgeNpm"
|
||||
],
|
||||
"timezone": "Europe/Moscow",
|
||||
"labels": [
|
||||
@@ -10,6 +11,13 @@
|
||||
],
|
||||
"dependencyDashboard": true,
|
||||
"rangeStrategy": "pin",
|
||||
"prConcurrentLimit": 5,
|
||||
"lockFileMaintenance": {
|
||||
"enabled": true,
|
||||
"schedule": [
|
||||
"before 4am on the first day of the month"
|
||||
]
|
||||
},
|
||||
"packageRules": [
|
||||
{
|
||||
"matchUpdateTypes": [
|
||||
@@ -18,6 +26,27 @@
|
||||
],
|
||||
"groupName": "non-major dependencies"
|
||||
},
|
||||
{
|
||||
"matchManagers": [
|
||||
"github-actions"
|
||||
],
|
||||
"matchUpdateTypes": [
|
||||
"minor",
|
||||
"patch"
|
||||
],
|
||||
"groupName": "non-major github actions"
|
||||
},
|
||||
{
|
||||
"matchManagers": [
|
||||
"docker-compose",
|
||||
"dockerfile"
|
||||
],
|
||||
"matchUpdateTypes": [
|
||||
"minor",
|
||||
"patch"
|
||||
],
|
||||
"groupName": "non-major container images"
|
||||
},
|
||||
{
|
||||
"matchUpdateTypes": [
|
||||
"major"
|
||||
|
||||
@@ -7,10 +7,10 @@ import type {
|
||||
TbankInstrument as MetadataRow,
|
||||
Prisma,
|
||||
} from '../../../generated/prisma/client';
|
||||
import type { TbankSyncAttempt } from './tbank-access.service';
|
||||
import type { TbankInstrument } from './tbank.client';
|
||||
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { isJoinableRunningAttempt, type TbankSyncAttempt } from './tbank-access.service';
|
||||
import { TbankErrorCode } from './tbank-error-code';
|
||||
|
||||
const FIRST_BATCH_OFFSET = 0;
|
||||
@@ -131,11 +131,7 @@ export class InstrumentMetadataRepository {
|
||||
const previous = await tx.tbankSyncWork.findUnique({
|
||||
where: { userId_revision_scopeKey: scope },
|
||||
});
|
||||
if (
|
||||
previous?.state === 'running' &&
|
||||
previous.processRunId === runId &&
|
||||
active.has(previous.attemptId)
|
||||
) {
|
||||
if (isJoinableRunningAttempt(previous, runId, active)) {
|
||||
return { work: previous, launch: false };
|
||||
}
|
||||
const data = {
|
||||
|
||||
@@ -25,6 +25,22 @@ export type TbankSyncAttempt = {
|
||||
userId: string;
|
||||
};
|
||||
|
||||
// Join rule shared by sync reservations: the same process joins its own running attempt
|
||||
// only while that attempt is still active in memory. Set and Map both satisfy `has`.
|
||||
export function isJoinableRunningAttempt<
|
||||
T extends { attemptId: string; processRunId: string; state: string },
|
||||
>(
|
||||
previous: null | T,
|
||||
processRunId: string,
|
||||
active: { has(attemptId: string): boolean },
|
||||
): previous is T {
|
||||
return (
|
||||
previous?.state === 'running' &&
|
||||
previous.processRunId === processRunId &&
|
||||
active.has(previous.attemptId)
|
||||
);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TbankAccessService {
|
||||
constructor(
|
||||
@@ -62,11 +78,7 @@ export class TbankAccessService {
|
||||
const previous = await tx.tbankSyncWork.findUnique({
|
||||
where: { userId_revision_scopeKey: scope },
|
||||
});
|
||||
if (
|
||||
previous?.state === 'running' &&
|
||||
previous.processRunId === processRunId &&
|
||||
active.has(previous.attemptId)
|
||||
) {
|
||||
if (isJoinableRunningAttempt(previous, processRunId, active)) {
|
||||
return { work: previous, launch: false };
|
||||
}
|
||||
const data = {
|
||||
|
||||
@@ -3,6 +3,7 @@ export { InstrumentMetadataService } from './instrument-metadata.service';
|
||||
export { metadataKey } from './instrument-metadata.service';
|
||||
export type { MetadataIdentity } from './instrument-metadata.service';
|
||||
export {
|
||||
isJoinableRunningAttempt,
|
||||
TbankAccessService,
|
||||
type TbankSyncAttempt,
|
||||
} from './tbank-access.service';
|
||||
|
||||
@@ -2,6 +2,8 @@ import { ConflictException, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { createHash } from 'crypto';
|
||||
|
||||
import { AuthRepository } from '../infrastructure/auth.repository';
|
||||
|
||||
jest.mock('bcrypt', () => ({
|
||||
hash: jest.fn(() => Promise.resolve('password-hash')),
|
||||
compare: jest.fn(() => Promise.resolve(true)),
|
||||
@@ -51,7 +53,7 @@ describe('AuthService', () => {
|
||||
delete: jest.fn(),
|
||||
},
|
||||
};
|
||||
const service = new AuthService(prisma as never, jwt);
|
||||
const service = new AuthService(new AuthRepository(prisma as never), jwt);
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
@@ -7,15 +7,13 @@ import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { createHash, randomUUID } from 'crypto';
|
||||
|
||||
import { Session, User } from '../../../../generated/prisma/client';
|
||||
import type { Session, User } from '../../../../generated/prisma/client';
|
||||
|
||||
import { HttpErrorCode } from '../../../common/error-code';
|
||||
import { isPrismaErrorCode, PrismaErrorCode } from '../../../prisma/prisma-error-code';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { AuthRepository } from '../infrastructure/auth.repository';
|
||||
import { AuthErrorCode } from './auth-error-code';
|
||||
import { AuthenticationResult, AuthUser, RefreshPayload } from './auth.types';
|
||||
|
||||
const EXPECTED_ROTATED_SESSIONS = 1;
|
||||
|
||||
const PASSWORD_HASH_ROUNDS = 12;
|
||||
export const REFRESH_TTL_MS = 604_800_000;
|
||||
|
||||
@@ -28,7 +26,7 @@ const DUMMY_PASSWORD_HASH =
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly repository: AuthRepository,
|
||||
private readonly jwt: JwtService,
|
||||
) {}
|
||||
|
||||
@@ -36,27 +34,18 @@ export class AuthService {
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<AuthenticationResult> {
|
||||
const existing = await this.prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
const existing = await this.repository.findUserByEmail(email);
|
||||
if (existing) {
|
||||
throw new ConflictException({ code: AuthErrorCode.EmailAlreadyRegistered });
|
||||
}
|
||||
|
||||
let user: User;
|
||||
try {
|
||||
user = await this.prisma.user.create({
|
||||
data: {
|
||||
id: randomUUID(),
|
||||
email,
|
||||
passwordHash: await bcrypt.hash(password, PASSWORD_HASH_ROUNDS),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintError(error)) {
|
||||
throw new ConflictException({ code: AuthErrorCode.EmailAlreadyRegistered });
|
||||
}
|
||||
throw error;
|
||||
const user = await this.repository.createUser({
|
||||
id: randomUUID(),
|
||||
email,
|
||||
passwordHash: await bcrypt.hash(password, PASSWORD_HASH_ROUNDS),
|
||||
});
|
||||
if (!user) {
|
||||
throw new ConflictException({ code: AuthErrorCode.EmailAlreadyRegistered });
|
||||
}
|
||||
return this.createSession(user);
|
||||
}
|
||||
@@ -65,9 +54,7 @@ export class AuthService {
|
||||
email: string,
|
||||
password: string,
|
||||
): Promise<AuthenticationResult> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { email },
|
||||
});
|
||||
const user = await this.repository.findUserByEmail(email);
|
||||
const valid = await bcrypt.compare(
|
||||
password,
|
||||
user?.passwordHash ?? DUMMY_PASSWORD_HASH,
|
||||
@@ -92,10 +79,7 @@ export class AuthService {
|
||||
if (payload.type !== 'refresh') {
|
||||
throw new UnauthorizedException({ code: HttpErrorCode.Unauthorized });
|
||||
}
|
||||
const session = await this.prisma.session.findUnique({
|
||||
where: { id: payload.sid },
|
||||
include: { user: true },
|
||||
});
|
||||
const session = await this.repository.findSessionWithUser(payload.sid);
|
||||
if (
|
||||
!session ||
|
||||
session.userId !== payload.sub ||
|
||||
@@ -103,7 +87,7 @@ export class AuthService {
|
||||
session.expiresAt <= new Date()
|
||||
) {
|
||||
if (session && !session.revokedAt) {
|
||||
await this.prisma.session.delete({ where: { id: session.id } });
|
||||
await this.repository.deleteSession(session.id);
|
||||
}
|
||||
throw new UnauthorizedException({ code: HttpErrorCode.Unauthorized });
|
||||
}
|
||||
@@ -124,18 +108,13 @@ export class AuthService {
|
||||
return;
|
||||
}
|
||||
if (payload.type !== 'refresh') return;
|
||||
const session = await this.prisma.session.findUnique({
|
||||
where: { id: payload.sid },
|
||||
});
|
||||
const session = await this.repository.findSession(payload.sid);
|
||||
if (
|
||||
session &&
|
||||
!session.revokedAt &&
|
||||
session.refreshTokenHash === this.hash(token)
|
||||
) {
|
||||
await this.prisma.session.update({
|
||||
where: { id: session.id },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
await this.repository.revokeSession(session.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +123,7 @@ export class AuthService {
|
||||
}
|
||||
|
||||
async userById(id: string): Promise<User> {
|
||||
const user = await this.prisma.user.findUnique({ where: { id } });
|
||||
const user = await this.repository.findUserById(id);
|
||||
if (!user) throw new UnauthorizedException({ code: HttpErrorCode.Unauthorized });
|
||||
return user;
|
||||
}
|
||||
@@ -152,14 +131,7 @@ export class AuthService {
|
||||
private async createSession(
|
||||
user: User,
|
||||
): Promise<AuthenticationResult> {
|
||||
const session = await this.prisma.session.create({
|
||||
data: {
|
||||
id: randomUUID(),
|
||||
userId: user.id,
|
||||
refreshTokenHash: '',
|
||||
expiresAt: new Date(),
|
||||
},
|
||||
});
|
||||
const session = await this.repository.createSession(user.id, randomUUID());
|
||||
return this.rotateSession({ ...session, user });
|
||||
}
|
||||
|
||||
@@ -180,16 +152,8 @@ export class AuthService {
|
||||
refreshTokenHash: this.hash(refreshToken),
|
||||
expiresAt: new Date(Date.now() + REFRESH_TTL_MS),
|
||||
};
|
||||
if (expectedRefreshTokenHash) {
|
||||
const updated = await this.prisma.session.updateMany({
|
||||
where: { id: session.id, refreshTokenHash: expectedRefreshTokenHash },
|
||||
data,
|
||||
});
|
||||
if (updated.count !== EXPECTED_ROTATED_SESSIONS) {
|
||||
throw new UnauthorizedException({ code: HttpErrorCode.Unauthorized });
|
||||
}
|
||||
} else {
|
||||
await this.prisma.session.update({ where: { id: session.id }, data });
|
||||
if (!(await this.repository.rotateSession(session.id, data, expectedRefreshTokenHash))) {
|
||||
throw new UnauthorizedException({ code: HttpErrorCode.Unauthorized });
|
||||
}
|
||||
return {
|
||||
user: this.toUser(session.user),
|
||||
@@ -205,12 +169,3 @@ export class AuthService {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
}
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
isPrismaErrorCode(error.code, PrismaErrorCode.UniqueConstraint)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { PassportModule } from '@nestjs/passport';
|
||||
|
||||
import { Environment } from '../../config/env.validation';
|
||||
import { AuthService } from './application/auth.service';
|
||||
import { AuthRepository } from './infrastructure/auth.repository';
|
||||
import { JwtStrategy } from './infrastructure/jwt.strategy';
|
||||
import { AuthController } from './presentation/auth.controller';
|
||||
import { JwtAuthGuard } from './presentation/jwt-auth.guard';
|
||||
@@ -22,6 +23,6 @@ import { JwtAuthGuard } from './presentation/jwt-auth.guard';
|
||||
],
|
||||
exports: [JwtAuthGuard],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtStrategy, JwtAuthGuard],
|
||||
providers: [AuthService, AuthRepository, JwtStrategy, JwtAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { isPrismaErrorCode, PrismaErrorCode } from '../../../prisma/prisma-error-code';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
|
||||
const EXPECTED_ROTATED_SESSIONS = 1;
|
||||
|
||||
@Injectable()
|
||||
export class AuthRepository {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
findUserByEmail(email: string) {
|
||||
return this.prisma.user.findUnique({ where: { email } });
|
||||
}
|
||||
|
||||
async createUser(data: { email: string; id: string; passwordHash: string }) {
|
||||
try {
|
||||
return await this.prisma.user.create({ data });
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintError(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
findUserById(id: string) {
|
||||
return this.prisma.user.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
findSessionWithUser(id: string) {
|
||||
return this.prisma.session.findUnique({
|
||||
where: { id },
|
||||
include: { user: true },
|
||||
});
|
||||
}
|
||||
|
||||
findSession(id: string) {
|
||||
return this.prisma.session.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
deleteSession(id: string) {
|
||||
return this.prisma.session.delete({ where: { id } });
|
||||
}
|
||||
|
||||
revokeSession(id: string) {
|
||||
return this.prisma.session.update({
|
||||
where: { id },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
createSession(userId: string, id: string) {
|
||||
return this.prisma.session.create({
|
||||
data: { id, userId, refreshTokenHash: '', expiresAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
async rotateSession(
|
||||
id: string,
|
||||
data: { expiresAt: Date; refreshTokenHash: string },
|
||||
expectedRefreshTokenHash?: string,
|
||||
): Promise<boolean> {
|
||||
if (expectedRefreshTokenHash) {
|
||||
const updated = await this.prisma.session.updateMany({
|
||||
where: { id, refreshTokenHash: expectedRefreshTokenHash },
|
||||
data,
|
||||
});
|
||||
return updated.count === EXPECTED_ROTATED_SESSIONS;
|
||||
}
|
||||
await this.prisma.session.update({ where: { id }, data });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === 'object' &&
|
||||
error !== null &&
|
||||
'code' in error &&
|
||||
isPrismaErrorCode(error.code, PrismaErrorCode.UniqueConstraint)
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { BankCard, Prisma } from '../../../../../generated/prisma/client';
|
||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||
import type { BankCard, Prisma } from '../../../../../generated/prisma/client';
|
||||
|
||||
import { bankBalance } from '../domain/bank-card.calculations';
|
||||
import { rubMoney } from '../domain/rub-money';
|
||||
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||
@@ -20,24 +20,13 @@ import {
|
||||
missing,
|
||||
} from './bank-card-input';
|
||||
|
||||
const EXPECTED_UPDATED_CARDS = 1;
|
||||
|
||||
type Tx = Prisma.TransactionClient;
|
||||
@Injectable()
|
||||
export class BankCardsService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly repository: BankCardsRepository,
|
||||
) {}
|
||||
constructor(private readonly repository: BankCardsRepository) {}
|
||||
|
||||
private async cardView(tx: Tx, card: BankCard): Promise<BankCardDto> {
|
||||
const rows = await tx.bankCardOperation.findMany({
|
||||
where: {
|
||||
userId: card.userId,
|
||||
deletedAt: null,
|
||||
OR: [{ cardId: card.id }, { targetCardId: card.id }],
|
||||
},
|
||||
});
|
||||
const rows = await this.repository.cardOperations(tx, card);
|
||||
return {
|
||||
id: card.id,
|
||||
name: card.name,
|
||||
@@ -53,20 +42,15 @@ export class BankCardsService {
|
||||
}
|
||||
|
||||
list(userId: string, includeArchived = false) {
|
||||
return this.prisma.$transaction(async (tx) =>
|
||||
Promise.all(
|
||||
(
|
||||
await tx.bankCard.findMany({
|
||||
where: { userId, ...(includeArchived ? {} : { archivedAt: null }) },
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
})
|
||||
).map((card) => this.cardView(tx, card)),
|
||||
),
|
||||
return this.repository.read(async (tx) =>
|
||||
Promise.all((await this.repository.cards(tx, userId, includeArchived)).map(
|
||||
(card) => this.cardView(tx, card),
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
get(userId: string, id: string) {
|
||||
return this.prisma.$transaction(async (tx) =>
|
||||
return this.repository.read(async (tx) =>
|
||||
this.cardView(tx, await this.repository.card(tx, userId, id)),
|
||||
);
|
||||
}
|
||||
@@ -75,7 +59,7 @@ export class BankCardsService {
|
||||
const input = cardInput(dto),
|
||||
hash = fingerprint(input);
|
||||
return this.repository.write(async (tx) => {
|
||||
const existing = await tx.bankCard.findUnique({ where: { id: dto.id } });
|
||||
const existing = await this.repository.cardById(tx, dto.id);
|
||||
if (existing) {
|
||||
if (existing.userId !== userId) missing();
|
||||
// eslint-disable-next-line security/detect-possible-timing-attacks -- This compares an idempotency fingerprint after ownership validation, not a secret.
|
||||
@@ -88,8 +72,11 @@ export class BankCardsService {
|
||||
await this.repository.seed(tx, userId);
|
||||
return this.cardView(
|
||||
tx,
|
||||
await tx.bankCard.create({
|
||||
data: { ...input, id: dto.id, userId, createFingerprint: hash },
|
||||
await this.repository.createCard(tx, {
|
||||
...input,
|
||||
id: dto.id,
|
||||
userId,
|
||||
createFingerprint: hash,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -122,20 +109,16 @@ export class BankCardsService {
|
||||
}
|
||||
currentDate(input.openingDate);
|
||||
if (
|
||||
await tx.bankCardOperation.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
date: { lt: input.openingDate },
|
||||
OR: [{ cardId: id }, { targetCardId: id }],
|
||||
},
|
||||
})
|
||||
await this.repository.hasOperationsBefore(tx, userId, id, input.openingDate)
|
||||
) {
|
||||
fail(BankErrorCode.OpeningDateConflict);
|
||||
}
|
||||
const changed = await tx.bankCard.updateMany({
|
||||
where: { id, userId, version: dto.version },
|
||||
data: {
|
||||
const updated = await this.repository.updateCard(
|
||||
tx,
|
||||
userId,
|
||||
id,
|
||||
dto.version,
|
||||
{
|
||||
...input,
|
||||
paymentSystem: input.paymentSystem ?? null,
|
||||
version: { increment: 1 },
|
||||
@@ -147,9 +130,8 @@ export class BankCardsService {
|
||||
: null,
|
||||
}),
|
||||
},
|
||||
});
|
||||
if (changed.count !== EXPECTED_UPDATED_CARDS) conflict();
|
||||
return this.cardView(tx, await this.repository.card(tx, userId, id));
|
||||
);
|
||||
return this.cardView(tx, updated);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { GoneException, Injectable } from '@nestjs/common';
|
||||
|
||||
import {
|
||||
import type {
|
||||
BankCardOperation,
|
||||
Prisma,
|
||||
} from '../../../../../generated/prisma/client';
|
||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||
|
||||
import { FIRST_PAGE } from '../domain/bank-card-limits';
|
||||
import { BankOperationKind } from '../domain/bank-operation-kind';
|
||||
import { rubMoney, ZERO_KOPECKS } from '../domain/rub-money';
|
||||
@@ -28,15 +28,10 @@ import {
|
||||
periodBounds,
|
||||
} from './bank-card-input';
|
||||
|
||||
const EXPECTED_UPDATED_ROWS = 1;
|
||||
|
||||
type Tx = Prisma.TransactionClient;
|
||||
@Injectable()
|
||||
export class BankOperationsService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly repository: BankCardsRepository,
|
||||
) {}
|
||||
constructor(private readonly repository: BankCardsRepository) {}
|
||||
|
||||
private async operationView(
|
||||
tx: Tx,
|
||||
@@ -51,21 +46,14 @@ export class BankOperationsService {
|
||||
: null;
|
||||
const categoryId = source?.categoryId ?? row.categoryId;
|
||||
const category = categoryId
|
||||
? await tx.expenseCategory.findFirst({
|
||||
where: { id: categoryId, userId: row.userId },
|
||||
})
|
||||
? await this.repository.category(tx, row.userId, categoryId)
|
||||
: null;
|
||||
const refunds =
|
||||
row.kind === BankOperationKind.Expense || source
|
||||
? await tx.bankCardOperation.findMany({
|
||||
where: {
|
||||
userId: row.userId,
|
||||
originalExpenseId: source?.id ?? row.id,
|
||||
deletedAt: null,
|
||||
...(source ? { id: { not: row.id } } : {}),
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const refunds = [] as Awaited<ReturnType<BankCardsRepository['refunds']>>;
|
||||
if (row.kind === BankOperationKind.Expense || source) {
|
||||
refunds.push(...await this.repository.refunds(
|
||||
tx, row.userId, source?.id ?? row.id, source?.id ? row.id : undefined,
|
||||
));
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
kind: row.kind as BankOperationDto['kind'],
|
||||
@@ -94,51 +82,7 @@ export class BankOperationsService {
|
||||
private async pageViews(tx: Tx, rows: BankCardOperation[]) {
|
||||
const userId = rows[0]?.userId;
|
||||
if (!userId) return [];
|
||||
const cardIds = new Set(
|
||||
rows.flatMap((row) =>
|
||||
[row.cardId, row.targetCardId].filter(
|
||||
(id): id is string => id !== null,
|
||||
),
|
||||
),
|
||||
);
|
||||
const sourceIds = new Set(
|
||||
rows.flatMap((row) => (row.originalExpenseId ? [row.originalExpenseId] : [])),
|
||||
);
|
||||
const [cards, sources] = await Promise.all([
|
||||
tx.bankCard.findMany({ where: { userId, id: { in: [...cardIds] } } }),
|
||||
tx.bankCardOperation.findMany({
|
||||
where: { userId, id: { in: [...sourceIds] } },
|
||||
}),
|
||||
]);
|
||||
const categoryIds = new Set(
|
||||
rows
|
||||
.map(
|
||||
(row) =>
|
||||
sources.find((source) => source.id === row.originalExpenseId)
|
||||
?.categoryId ?? row.categoryId,
|
||||
)
|
||||
.filter((id): id is string => id !== null),
|
||||
);
|
||||
const expenseIds = new Set(
|
||||
rows.flatMap((row) => {
|
||||
const source = sources.find((item) => item.id === row.originalExpenseId);
|
||||
return row.kind === BankOperationKind.Expense || source
|
||||
? [source?.id ?? row.id]
|
||||
: [];
|
||||
}),
|
||||
);
|
||||
const [categories, refunds] = await Promise.all([
|
||||
tx.expenseCategory.findMany({
|
||||
where: { userId, id: { in: [...categoryIds] } },
|
||||
}),
|
||||
tx.bankCardOperation.findMany({
|
||||
where: {
|
||||
userId,
|
||||
originalExpenseId: { in: [...expenseIds] },
|
||||
deletedAt: null,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const { cards, sources, categories, refunds } = await this.repository.operationViewData(tx, userId, rows);
|
||||
const cardsById = new Map(cards.map((card) => [card.id, card]));
|
||||
const sourcesById = new Map(sources.map((source) => [source.id, source]));
|
||||
const categoriesById = new Map(categories.map((category) => [category.id, category]));
|
||||
@@ -227,16 +171,12 @@ export class BankOperationsService {
|
||||
if (input.kind === BankOperationKind.Expense) {
|
||||
if (input.originalExpenseId) fail();
|
||||
if (!input.categoryId) {
|
||||
const category = await tx.expenseCategory.findUnique({
|
||||
where: { userId_seedKey: { userId, seedKey: 'other' } },
|
||||
});
|
||||
const category = await this.repository.defaultCategory(tx, userId);
|
||||
if (!category) missing();
|
||||
input.categoryId = category.id;
|
||||
}
|
||||
if (
|
||||
!(await tx.expenseCategory.findFirst({
|
||||
where: { userId, id: input.categoryId },
|
||||
}))
|
||||
!(await this.repository.category(tx, userId, input.categoryId))
|
||||
) {
|
||||
missing();
|
||||
}
|
||||
@@ -258,29 +198,11 @@ export class BankOperationsService {
|
||||
) {
|
||||
fail(BankErrorCode.InvalidRefund);
|
||||
}
|
||||
if (
|
||||
(
|
||||
await tx.bankCardOperation.updateMany({
|
||||
where: {
|
||||
id: source.id,
|
||||
userId,
|
||||
version: source.version,
|
||||
deletedAt: null,
|
||||
},
|
||||
data: { version: { increment: 1 } },
|
||||
})
|
||||
).count !== EXPECTED_UPDATED_ROWS
|
||||
) {
|
||||
conflict();
|
||||
}
|
||||
const refunds = await tx.bankCardOperation.findMany({
|
||||
where: {
|
||||
userId,
|
||||
originalExpenseId: source.id,
|
||||
deletedAt: null,
|
||||
...(old ? { id: { not: old.id } } : {}),
|
||||
},
|
||||
});
|
||||
await this.repository.updateOperation(tx,
|
||||
{ id: source.id, userId, version: source.version, deletedAt: null },
|
||||
{ version: { increment: 1 } },
|
||||
);
|
||||
const refunds = await this.repository.refunds(tx, userId, source.id, old?.id);
|
||||
if (input.date < source.date) fail(BankErrorCode.InvalidDate);
|
||||
if (
|
||||
refunds.reduce((sum, r) => sum + r.amountKopecks, ZERO_KOPECKS) +
|
||||
@@ -291,9 +213,7 @@ export class BankOperationsService {
|
||||
}
|
||||
}
|
||||
if (old?.kind === BankOperationKind.Expense) {
|
||||
const refunds = await tx.bankCardOperation.findMany({
|
||||
where: { userId, originalExpenseId: old.id, deletedAt: null },
|
||||
});
|
||||
const refunds = await this.repository.refunds(tx, userId, old.id);
|
||||
if (
|
||||
refunds.length &&
|
||||
(input.cardId !== old.cardId ||
|
||||
@@ -310,9 +230,7 @@ export class BankOperationsService {
|
||||
const normalized = operationInput(dto),
|
||||
hash = fingerprint(normalized);
|
||||
return this.repository.write(async (tx) => {
|
||||
const existing = await tx.bankCardOperation.findUnique({
|
||||
where: { id: dto.id },
|
||||
});
|
||||
const existing = await this.repository.operationById(tx, dto.id);
|
||||
if (existing) {
|
||||
if (existing.userId !== userId) missing();
|
||||
// eslint-disable-next-line security/detect-possible-timing-attacks -- This compares an idempotency fingerprint after ownership validation, not a secret.
|
||||
@@ -328,15 +246,15 @@ export class BankOperationsService {
|
||||
await this.validateOperation(tx, userId, input);
|
||||
return this.operationView(
|
||||
tx,
|
||||
await tx.bankCardOperation.create({
|
||||
data: { ...input, id: dto.id, userId, createFingerprint: hash },
|
||||
await this.repository.createOperation(tx, {
|
||||
...input, id: dto.id, userId, createFingerprint: hash,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
getOperation(userId: string, id: string) {
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
return this.repository.read(async (tx) => {
|
||||
const row = await this.repository.operation(tx, userId, id);
|
||||
if (row.deletedAt) missing();
|
||||
return this.operationView(tx, row);
|
||||
@@ -361,16 +279,10 @@ export class BankOperationsService {
|
||||
description: dto.description ?? old.description ?? undefined,
|
||||
});
|
||||
await this.validateOperation(tx, userId, input, old);
|
||||
if (
|
||||
(
|
||||
await tx.bankCardOperation.updateMany({
|
||||
where: { id, userId, version: dto.version, deletedAt: null },
|
||||
data: { ...input, version: { increment: 1 } },
|
||||
})
|
||||
).count !== EXPECTED_UPDATED_ROWS
|
||||
) {
|
||||
conflict();
|
||||
}
|
||||
await this.repository.updateOperation(tx,
|
||||
{ id, userId, version: dto.version, deletedAt: null },
|
||||
{ ...input, version: { increment: 1 } },
|
||||
);
|
||||
return this.operationView(
|
||||
tx,
|
||||
await this.repository.operation(tx, userId, id),
|
||||
@@ -389,9 +301,7 @@ export class BankOperationsService {
|
||||
}
|
||||
if (
|
||||
row.kind === BankOperationKind.Expense &&
|
||||
(await tx.bankCardOperation.findFirst({
|
||||
where: { userId, originalExpenseId: id, deletedAt: null },
|
||||
}))
|
||||
(await this.repository.dependentRefund(tx, userId, id))
|
||||
) {
|
||||
conflict(BankErrorCode.DependentRefunds);
|
||||
}
|
||||
@@ -401,27 +311,15 @@ export class BankOperationsService {
|
||||
userId,
|
||||
row.originalExpenseId,
|
||||
);
|
||||
if (
|
||||
(
|
||||
await tx.bankCardOperation.updateMany({
|
||||
where: { id: source.id, userId, version: source.version },
|
||||
data: { version: { increment: 1 } },
|
||||
})
|
||||
).count !== EXPECTED_UPDATED_ROWS
|
||||
) {
|
||||
conflict();
|
||||
}
|
||||
}
|
||||
if (
|
||||
(
|
||||
await tx.bankCardOperation.updateMany({
|
||||
where: { id, userId, version, deletedAt: null },
|
||||
data: { deletedAt: new Date(), version: { increment: 1 } },
|
||||
})
|
||||
).count !== EXPECTED_UPDATED_ROWS
|
||||
) {
|
||||
conflict();
|
||||
await this.repository.updateOperation(tx,
|
||||
{ id: source.id, userId, version: source.version },
|
||||
{ version: { increment: 1 } },
|
||||
);
|
||||
}
|
||||
await this.repository.updateOperation(tx,
|
||||
{ id, userId, version, deletedAt: null },
|
||||
{ deletedAt: new Date(), version: { increment: 1 } },
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -434,25 +332,13 @@ export class BankOperationsService {
|
||||
const period = expenses
|
||||
? undefined
|
||||
: periodBounds(query as BankOperationsQueryDto);
|
||||
return this.prisma.$transaction(async (tx) => {
|
||||
return this.repository.read(async (tx) => {
|
||||
await this.repository.card(tx, userId, id);
|
||||
const limit = query.limit ?? DEFAULT_BANK_PAGE_SIZE,
|
||||
page = query.page ?? FIRST_PAGE;
|
||||
const where: Prisma.BankCardOperationWhereInput = {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
OR: [{ cardId: id }, { targetCardId: id }],
|
||||
...(period
|
||||
? { date: { gte: period.from, lte: period.to } }
|
||||
: { kind: BankOperationKind.Expense }),
|
||||
};
|
||||
const total = await tx.bankCardOperation.count({ where });
|
||||
const rows = await tx.bankCardOperation.findMany({
|
||||
where,
|
||||
orderBy: [{ date: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - FIRST_PAGE) * limit,
|
||||
take: limit,
|
||||
});
|
||||
const { total, rows } = await this.repository.operationPage(
|
||||
tx, userId, id, period, limit, page,
|
||||
);
|
||||
return {
|
||||
items: await this.pageViews(tx, rows),
|
||||
total,
|
||||
|
||||
@@ -1,81 +1,24 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||
import { MAX_CATEGORY_NAME_LENGTH } from '../domain/bank-card-limits';
|
||||
import { BankCardsRepository } from '../infrastructure/bank-cards.repository';
|
||||
import { conflict, missing, name } from './bank-card-input';
|
||||
|
||||
const EXPECTED_UPDATED_CATEGORIES = 1;
|
||||
const VERSION_INCREMENT = 1;
|
||||
import { name } from './bank-card-input';
|
||||
|
||||
@Injectable()
|
||||
export class ExpenseCategoriesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly repository: BankCardsRepository,
|
||||
) {}
|
||||
constructor(private readonly repository: BankCardsRepository) {}
|
||||
|
||||
async categories(userId: string) {
|
||||
return (
|
||||
await this.prisma.expenseCategory.findMany({
|
||||
where: { userId },
|
||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||
})
|
||||
).map(({ id, name, seedKey, version }) => ({
|
||||
id,
|
||||
name,
|
||||
isDefault: seedKey === 'other',
|
||||
version,
|
||||
}));
|
||||
return this.repository.categories(userId);
|
||||
}
|
||||
|
||||
createCategory(userId: string, value: string) {
|
||||
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
||||
return this.repository.write(async (tx) => {
|
||||
await this.repository.seed(tx, userId);
|
||||
const row = await tx.expenseCategory.create({
|
||||
data: {
|
||||
id: randomUUID(),
|
||||
userId,
|
||||
name: label,
|
||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||
},
|
||||
});
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
isDefault: false,
|
||||
version: row.version,
|
||||
};
|
||||
});
|
||||
return this.repository.createCategory(userId, label);
|
||||
}
|
||||
|
||||
updateCategory(userId: string, id: string, value: string, version: number) {
|
||||
const label = name(value, MAX_CATEGORY_NAME_LENGTH);
|
||||
return this.repository.write(async (tx) => {
|
||||
const row = await tx.expenseCategory.findFirst({ where: { id, userId } });
|
||||
if (!row) missing();
|
||||
if (
|
||||
(
|
||||
await tx.expenseCategory.updateMany({
|
||||
where: { id, userId, version },
|
||||
data: {
|
||||
name: label,
|
||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||
version: { increment: 1 },
|
||||
},
|
||||
})
|
||||
).count !== EXPECTED_UPDATED_CATEGORIES
|
||||
) {
|
||||
conflict();
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name: label,
|
||||
isDefault: row.seedKey === 'other',
|
||||
version: version + VERSION_INCREMENT,
|
||||
};
|
||||
});
|
||||
return this.repository.updateCategory(userId, id, label, version);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { Prisma } from '../../../../../generated/prisma/client';
|
||||
import { BankCard, BankCardOperation, Prisma } from '../../../../../generated/prisma/client';
|
||||
import { isPrismaErrorCode, PrismaErrorCode } from '../../../../prisma/prisma-error-code';
|
||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||
import {
|
||||
@@ -9,10 +9,15 @@ import {
|
||||
conflict,
|
||||
missing,
|
||||
} from '../application/bank-card-input';
|
||||
import { FIRST_PAGE } from '../domain/bank-card-limits';
|
||||
import { BankOperationKind } from '../domain/bank-operation-kind';
|
||||
|
||||
const INITIAL_RETRY_COUNT = 0;
|
||||
const LAST_SEED_OFFSET = 1;
|
||||
const EXPECTED_UPDATED_CARDS = 1;
|
||||
const EXPECTED_UPDATED_OPERATIONS = 1;
|
||||
const EXPECTED_UPDATED_CATEGORIES = 1;
|
||||
const VERSION_INCREMENT = 1;
|
||||
|
||||
type Tx = Prisma.TransactionClient;
|
||||
const TRANSACTION_MAX_WAIT_MS = 10_000;
|
||||
@@ -32,6 +37,220 @@ const seeds = [
|
||||
@Injectable()
|
||||
export class BankCardsRepository {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
|
||||
read<T>(run: (tx: Tx) => Promise<T>): Promise<T> {
|
||||
return this.prisma.$transaction(run);
|
||||
}
|
||||
|
||||
cards(tx: Tx, userId: string, includeArchived = false) {
|
||||
return tx.bankCard.findMany({
|
||||
where: { userId, ...(includeArchived ? {} : { archivedAt: null }) },
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
});
|
||||
}
|
||||
|
||||
cardOperations(tx: Tx, card: BankCard) {
|
||||
return tx.bankCardOperation.findMany({
|
||||
where: {
|
||||
userId: card.userId,
|
||||
deletedAt: null,
|
||||
OR: [{ cardId: card.id }, { targetCardId: card.id }],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
operationById(tx: Tx, id: string) {
|
||||
return tx.bankCardOperation.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
createOperation(tx: Tx, data: Prisma.BankCardOperationUncheckedCreateInput) {
|
||||
return tx.bankCardOperation.create({ data });
|
||||
}
|
||||
|
||||
async updateOperation(
|
||||
tx: Tx,
|
||||
where: Prisma.BankCardOperationWhereInput,
|
||||
data: Prisma.BankCardOperationUpdateManyMutationInput,
|
||||
) {
|
||||
const result = await tx.bankCardOperation.updateMany({ where, data });
|
||||
if (result.count !== EXPECTED_UPDATED_OPERATIONS) conflict();
|
||||
}
|
||||
|
||||
category(tx: Tx, userId: string, id: string) {
|
||||
return tx.expenseCategory.findFirst({ where: { id, userId } });
|
||||
}
|
||||
|
||||
defaultCategory(tx: Tx, userId: string) {
|
||||
return tx.expenseCategory.findUnique({
|
||||
where: { userId_seedKey: { userId, seedKey: 'other' } },
|
||||
});
|
||||
}
|
||||
|
||||
refunds(tx: Tx, userId: string, originalExpenseId: string, excludeId?: string) {
|
||||
return tx.bankCardOperation.findMany({
|
||||
where: {
|
||||
userId,
|
||||
originalExpenseId,
|
||||
deletedAt: null,
|
||||
...(excludeId ? { id: { not: excludeId } } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
dependentRefund(tx: Tx, userId: string, originalExpenseId: string) {
|
||||
return tx.bankCardOperation.findFirst({
|
||||
where: { userId, originalExpenseId, deletedAt: null },
|
||||
});
|
||||
}
|
||||
|
||||
async operationViewData(tx: Tx, userId: string, rows: BankCardOperation[]) {
|
||||
const cardIds = new Set(rows.flatMap((row) =>
|
||||
[row.cardId, row.targetCardId].filter((id): id is string => id !== null),
|
||||
));
|
||||
const sourceIds = new Set(rows.flatMap((row) =>
|
||||
row.originalExpenseId ? [row.originalExpenseId] : [],
|
||||
));
|
||||
const [cards, sources] = await Promise.all([
|
||||
tx.bankCard.findMany({ where: { userId, id: { in: [...cardIds] } } }),
|
||||
tx.bankCardOperation.findMany({ where: { userId, id: { in: [...sourceIds] } } }),
|
||||
]);
|
||||
const categoryIds = new Set(rows.map((row) =>
|
||||
sources.find((source) => source.id === row.originalExpenseId)?.categoryId ?? row.categoryId,
|
||||
).filter((id): id is string => id !== null));
|
||||
const expenseIds = new Set(rows.flatMap((row) => {
|
||||
const source = sources.find((item) => item.id === row.originalExpenseId);
|
||||
return row.kind === BankOperationKind.Expense || source ? [source?.id ?? row.id] : [];
|
||||
}));
|
||||
const [categories, refunds] = await Promise.all([
|
||||
tx.expenseCategory.findMany({ where: { userId, id: { in: [...categoryIds] } } }),
|
||||
tx.bankCardOperation.findMany({
|
||||
where: { userId, originalExpenseId: { in: [...expenseIds] }, deletedAt: null },
|
||||
}),
|
||||
]);
|
||||
return { cards, sources, categories, refunds };
|
||||
}
|
||||
|
||||
async operationPage(
|
||||
tx: Tx,
|
||||
userId: string,
|
||||
id: string,
|
||||
period: undefined | { from: string; to: string },
|
||||
limit: number,
|
||||
page: number,
|
||||
) {
|
||||
const where: Prisma.BankCardOperationWhereInput = {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
OR: [{ cardId: id }, { targetCardId: id }],
|
||||
...(period
|
||||
? { date: { gte: period.from, lte: period.to } }
|
||||
: { kind: BankOperationKind.Expense }),
|
||||
};
|
||||
const total = await tx.bankCardOperation.count({ where });
|
||||
const rows = await tx.bankCardOperation.findMany({
|
||||
where,
|
||||
orderBy: [{ date: 'desc' }, { createdAt: 'desc' }, { id: 'desc' }],
|
||||
skip: (page - FIRST_PAGE) * limit,
|
||||
take: limit,
|
||||
});
|
||||
return { total, rows };
|
||||
}
|
||||
|
||||
cardById(tx: Tx, id: string) {
|
||||
return tx.bankCard.findUnique({ where: { id } });
|
||||
}
|
||||
|
||||
createCard(tx: Tx, data: Prisma.BankCardUncheckedCreateInput) {
|
||||
return tx.bankCard.create({ data });
|
||||
}
|
||||
|
||||
async updateCard(
|
||||
tx: Tx,
|
||||
userId: string,
|
||||
id: string,
|
||||
version: number,
|
||||
data: Prisma.BankCardUpdateManyMutationInput,
|
||||
) {
|
||||
const changed = await tx.bankCard.updateMany({
|
||||
where: { id, userId, version },
|
||||
data,
|
||||
});
|
||||
if (changed.count !== EXPECTED_UPDATED_CARDS) conflict();
|
||||
return this.card(tx, userId, id);
|
||||
}
|
||||
|
||||
hasOperationsBefore(tx: Tx, userId: string, id: string, openingDate: string) {
|
||||
return tx.bankCardOperation.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
deletedAt: null,
|
||||
date: { lt: openingDate },
|
||||
OR: [{ cardId: id }, { targetCardId: id }],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async categories(userId: string) {
|
||||
return (
|
||||
await this.prisma.expenseCategory.findMany({
|
||||
where: { userId },
|
||||
orderBy: [{ name: 'asc' }, { id: 'asc' }],
|
||||
})
|
||||
).map(({ id, name, seedKey, version }) => ({
|
||||
id,
|
||||
name,
|
||||
isDefault: seedKey === 'other',
|
||||
version,
|
||||
}));
|
||||
}
|
||||
|
||||
createCategory(userId: string, label: string) {
|
||||
return this.write(async (tx) => {
|
||||
await this.seed(tx, userId);
|
||||
const row = await tx.expenseCategory.create({
|
||||
data: {
|
||||
id: randomUUID(),
|
||||
userId,
|
||||
name: label,
|
||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||
},
|
||||
});
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
isDefault: false,
|
||||
version: row.version,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
updateCategory(userId: string, id: string, label: string, version: number) {
|
||||
return this.write(async (tx) => {
|
||||
const row = await tx.expenseCategory.findFirst({ where: { id, userId } });
|
||||
if (!row) missing();
|
||||
if (
|
||||
(
|
||||
await tx.expenseCategory.updateMany({
|
||||
where: { id, userId, version },
|
||||
data: {
|
||||
name: label,
|
||||
nameKey: label.toLocaleLowerCase('ru-RU'),
|
||||
version: { increment: 1 },
|
||||
},
|
||||
})
|
||||
).count !== EXPECTED_UPDATED_CATEGORIES
|
||||
) {
|
||||
conflict();
|
||||
}
|
||||
return {
|
||||
id,
|
||||
name: label,
|
||||
isDefault: row.seedKey === 'other',
|
||||
version: version + VERSION_INCREMENT,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async write<T>(run: (tx: Tx) => Promise<T>): Promise<T> {
|
||||
for (let attempt = INITIAL_RETRY_COUNT; ; attempt++) {
|
||||
try {
|
||||
|
||||
@@ -110,6 +110,7 @@ export class CatalogEnrichmentService {
|
||||
tickers?: Record<string, string>;
|
||||
to: string;
|
||||
},
|
||||
refreshBefore?: Date,
|
||||
) {
|
||||
const { revision } = await this.access.local(userId);
|
||||
const inputs = sourceInputs(instrumentType, uids, kinds, range);
|
||||
@@ -123,6 +124,7 @@ export class CatalogEnrichmentService {
|
||||
false,
|
||||
kinds,
|
||||
range,
|
||||
refreshBefore,
|
||||
);
|
||||
}
|
||||
const work = inputs.length
|
||||
@@ -175,6 +177,7 @@ export class CatalogEnrichmentService {
|
||||
tickers?: Record<string, string>;
|
||||
to: string;
|
||||
},
|
||||
refreshBefore?: Date,
|
||||
) {
|
||||
const inputs = sourceInputs(instrumentType, uids, kinds, range);
|
||||
const reservation = this.reservations.then(async () => {
|
||||
@@ -189,7 +192,9 @@ export class CatalogEnrichmentService {
|
||||
);
|
||||
const policy = sourcePolicy(input.kind);
|
||||
const needsRefresh = force || !row?.fetchedAt ||
|
||||
(policy === 'quote' && tbankSourceNeedsRefresh('quote', row.fetchedAt, new Date()));
|
||||
(policy === 'quote' && tbankSourceNeedsRefresh('quote', row.fetchedAt, new Date())) ||
|
||||
// A walk reads a saved calendar once: later accounts see the new fetchedAt.
|
||||
(policy === 'calendar' && refreshBefore !== undefined && row.fetchedAt < refreshBefore);
|
||||
if (!needsRefresh) {
|
||||
continue;
|
||||
}
|
||||
@@ -665,6 +670,7 @@ function sourcePolicy(kind: CatalogSource['kind']) {
|
||||
) {
|
||||
return 'quote';
|
||||
}
|
||||
if (['bond-events', 'dividends'].includes(kind)) return 'calendar';
|
||||
return 'stable';
|
||||
}
|
||||
function producerKey(input: CatalogSource) {
|
||||
|
||||
@@ -3,9 +3,9 @@ import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
|
||||
import type { Prisma } from '../../../../../generated/prisma/client';
|
||||
import type { TbankBond, TbankShare, TbankSyncAttempt } from '../../../../integrations/tbank/tbank.api';
|
||||
|
||||
import { TbankErrorCode } from '../../../../integrations/tbank/tbank-error-code';
|
||||
import { isJoinableRunningAttempt, type TbankBond, type TbankShare, type TbankSyncAttempt } from '../../../../integrations/tbank/tbank.api';
|
||||
import { PrismaService } from '../../../../prisma/prisma.service';
|
||||
|
||||
const UNCHANGED_REVISION_INCREMENT = 0;
|
||||
@@ -293,11 +293,7 @@ export class CatalogDiscoveryRepository {
|
||||
const previous = await tx.tbankSyncWork.findUnique({
|
||||
where: { userId_revision_scopeKey: scope },
|
||||
});
|
||||
if (
|
||||
previous?.state === 'running' &&
|
||||
previous.processRunId === runId &&
|
||||
active.has(previous.attemptId)
|
||||
) {
|
||||
if (isJoinableRunningAttempt(previous, runId, active)) {
|
||||
return { work: previous, launch: false };
|
||||
}
|
||||
const data = {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { TbankAccessService } from '../../../integrations/tbank/tbank-access.service';
|
||||
import { TbankModule } from '../../../integrations/tbank/tbank.module';
|
||||
import { AuthModule } from '../../auth/auth.module';
|
||||
import { PortfolioModule } from '../portfolio/portfolio.module';
|
||||
@@ -21,7 +20,6 @@ import { StockController } from './stocks/presentation/stock.controller';
|
||||
controllers: [StockController, BondController],
|
||||
exports: [StockIncomeService, BondIncomeService],
|
||||
providers: [
|
||||
{ provide: 'TBANK_ACCESS', useExisting: TbankAccessService },
|
||||
BondIncomeService,
|
||||
BondMarketService,
|
||||
GetStockCompanyUseCase,
|
||||
|
||||
+5
-1
@@ -1,3 +1,7 @@
|
||||
jest.mock('../../../../../integrations/tbank/tbank.api', () => ({
|
||||
TbankAccessService: class {},
|
||||
}));
|
||||
|
||||
import { NotFoundException, ServiceUnavailableException } from '@nestjs/common';
|
||||
|
||||
import type { TbankShare } from '../../../../../integrations/tbank/tbank.api';
|
||||
@@ -36,7 +40,7 @@ describe('StockScreenerService', () => {
|
||||
client.getAllShares.mockResolvedValue(
|
||||
Array.from({ length: pageSize + 1 }, (_, index) => share(index)),
|
||||
);
|
||||
service = new StockScreenerService(access, client as never, logger as never);
|
||||
service = new StockScreenerService(access as never, client as never, logger as never);
|
||||
});
|
||||
|
||||
it('stores the full selected catalog and returns stable non-overlapping pages', async () => {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Inject,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
ServiceUnavailableException,
|
||||
@@ -10,6 +9,7 @@ import { randomUUID } from 'node:crypto';
|
||||
import type { TbankShare } from '../../../../../integrations/tbank/tbank-market.types';
|
||||
|
||||
import { StructuredLogger } from '../../../../../common/logging/structured-logger.service';
|
||||
import { TbankAccessService } from '../../../../../integrations/tbank/tbank.api';
|
||||
import { TbankClient } from '../../../../../integrations/tbank/tbank.client';
|
||||
import {
|
||||
selectStockScreenerInstruments,
|
||||
@@ -47,17 +47,13 @@ type StockScreenerPage = {
|
||||
searchId: string;
|
||||
};
|
||||
type Snapshot = { asOf: string; expiresAt: number; items: StockScreenerItem[]; revision: string; userId: string };
|
||||
type TbankAccess = {
|
||||
local(userId: string): Promise<{ revision: string }>;
|
||||
online<T>(userId: string, run: (connection: { revision: string; token: string }) => Promise<T>): Promise<T>;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class StockScreenerService {
|
||||
private readonly snapshots = new Map<string, Snapshot>();
|
||||
|
||||
constructor(
|
||||
@Inject('TBANK_ACCESS') private readonly access: TbankAccess,
|
||||
private readonly access: TbankAccessService,
|
||||
private readonly client: TbankClient,
|
||||
private readonly logger: StructuredLogger,
|
||||
) {}
|
||||
|
||||
@@ -91,6 +91,7 @@ export class StockController {
|
||||
@Body(new ValidationPipe({ forbidNonWhitelisted: true, forbidUnknownValues: true, whitelist: true }))
|
||||
criteria: StockScreenerCriteriaDto,
|
||||
) {
|
||||
// The global whitelist pipe strips unknown keys before this param pipe runs, so only the raw body can reject them.
|
||||
const allowed = new Set(['countryOfRisk', 'currency', 'maxLot', 'query', 'realExchange', 'sector', 'shareType']);
|
||||
if (Object.keys(request.body as object).some((key) => !allowed.has(key))) {
|
||||
throw new BadRequestException();
|
||||
|
||||
@@ -20,6 +20,7 @@ export class ForecastService {
|
||||
lastAttempt?: InvestmentResourceMetaDto['lastAttempt'];
|
||||
membershipRevision: number;
|
||||
portfolio: InvestmentResourceMetaDto;
|
||||
replacesLatest?: boolean;
|
||||
revision: string;
|
||||
scopeKey: string;
|
||||
sources: {
|
||||
@@ -74,7 +75,7 @@ export class ForecastService {
|
||||
.map((dependency) => dependency.sync)
|
||||
.find((sync) => sync.state === 'failed');
|
||||
return {
|
||||
data: stored ? filterEvents(stored.payload as T, input.scopeKey) : null,
|
||||
data: stored ? filterEvents(stored.payload as T, input.scopeKey, stored.scopeKey) : null,
|
||||
meta: investmentResourceMeta({
|
||||
resourceKey: input.scopeKey,
|
||||
dataRevision: String(stored?.dataRevision ?? MISSING_DATA_REVISION),
|
||||
@@ -95,7 +96,7 @@ export class ForecastService {
|
||||
}
|
||||
}
|
||||
|
||||
function filterEvents<T extends object>(payload: T, scopeKey: string): T {
|
||||
function filterEvents<T extends object>(payload: T, scopeKey: string, savedScopeKey: string): T {
|
||||
if (!scopeKey.startsWith('events/')) return payload;
|
||||
try {
|
||||
const [, from, to] = JSON.parse(scopeKey.slice('events/'.length)) as [string, string, string];
|
||||
@@ -111,8 +112,10 @@ function filterEvents<T extends object>(payload: T, scopeKey: string): T {
|
||||
const current = totals.get(event.projectedAmount.currency) ?? { value: 0n, scale: 0 };
|
||||
totals.set(event.projectedAmount.currency, add(current, decimalFromString(event.projectedAmount.value)));
|
||||
}
|
||||
const [, savedFrom, savedTo] = JSON.parse(savedScopeKey.slice('events/'.length)) as [string, string, string];
|
||||
return {
|
||||
...value,
|
||||
window: { from: savedFrom, to: savedTo },
|
||||
events,
|
||||
incomeTotalsByCurrency: [...totals]
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
|
||||
@@ -218,6 +218,18 @@ describe('persistent portfolio projection', () => {
|
||||
expect(snapshot.structure.currencies[0].totalValue).toBe('121.49');
|
||||
});
|
||||
|
||||
// Test intent: a corrupted Json payload must fail loudly instead of being spread into the API response.
|
||||
it('rejects a stored snapshot payload without the persisted shape', async () => {
|
||||
repository.read.mockResolvedValue({
|
||||
membershipAt,
|
||||
membershipRevision: 1,
|
||||
accounts: [{ accountId: 'a', name: 'A', type: 'BROKERAGE', openedOn: null,
|
||||
portfolio: { payload: { positions: 'broken' }, fetchedAt: membershipAt, dataRevision: 1 } }],
|
||||
work: [],
|
||||
});
|
||||
await expect(service.read('user', 'all')).rejects.toThrow('Corrupted portfolio snapshot payload');
|
||||
});
|
||||
|
||||
it('does not turn a missing account snapshot into aggregate zero; summaries stay independent', async () => {
|
||||
const snapshot: PortfolioDto = {
|
||||
lastSuccessfulAt: membershipAt.toISOString(),
|
||||
|
||||
@@ -4,6 +4,8 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import type { Prisma } from '../../../../../generated/prisma/client';
|
||||
|
||||
import { StructuredLogger } from '../../../../common/logging/structured-logger.service';
|
||||
import { isTbankErrorCode, TbankErrorCode } from '../../../../integrations/tbank/tbank-error-code';
|
||||
import {
|
||||
@@ -26,6 +28,7 @@ import { sumMoneyByCurrency } from '../domain/portfolio-totals';
|
||||
import {
|
||||
portfolioFreshForMs,
|
||||
PortfolioRepository,
|
||||
portfolioSnapshot,
|
||||
portfolioWorkKey,
|
||||
} from '../infrastructure/portfolio.repository';
|
||||
import { mapPortfolio } from '../infrastructure/tbank-portfolio.mapper';
|
||||
@@ -88,18 +91,7 @@ export class PortfolioService {
|
||||
type: account.type,
|
||||
openedOn: account.openedOn,
|
||||
snapshot: account.portfolio
|
||||
? {
|
||||
...(account.portfolio.payload as unknown as PortfolioDto),
|
||||
positions: (account.portfolio.payload as unknown as PortfolioDto).positions.map((position) => ({
|
||||
...position,
|
||||
sector: position.sector ?? null,
|
||||
issuer: position.issuer ?? null,
|
||||
})),
|
||||
lastSuccessfulAt: account.portfolio.fetchedAt.toISOString(),
|
||||
isStale:
|
||||
Date.now() - account.portfolio.fetchedAt.valueOf() >=
|
||||
portfolioFreshForMs,
|
||||
}
|
||||
? savedSnapshot(account.portfolio)
|
||||
: null,
|
||||
meta: investmentResourceMeta({
|
||||
resourceKey: `portfolio/${encodeURIComponent(account.accountId)}`,
|
||||
@@ -326,3 +318,17 @@ export class PortfolioService {
|
||||
return mapPortfolio(upstream, money, savedMetadata, lastSuccessfulAt, classifications);
|
||||
}
|
||||
}
|
||||
|
||||
function savedSnapshot(saved: { fetchedAt: Date; payload: Prisma.JsonValue }): PortfolioDto {
|
||||
const snapshot = portfolioSnapshot(saved.payload);
|
||||
return {
|
||||
...snapshot,
|
||||
positions: snapshot.positions.map((position) => ({
|
||||
...position,
|
||||
sector: position.sector ?? null,
|
||||
issuer: position.issuer ?? null,
|
||||
})),
|
||||
lastSuccessfulAt: saved.fetchedAt.toISOString(),
|
||||
isStale: Date.now() - saved.fetchedAt.valueOf() >= portfolioFreshForMs,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
) {
|
||||
|
||||
@@ -200,3 +200,16 @@ export class PortfolioRepository {
|
||||
export function portfolioWorkKey(accountId: string): string {
|
||||
return `portfolio:${JSON.stringify(accountId)}`;
|
||||
}
|
||||
|
||||
// Json payload is written only by publish(); a shape check turns corruption into an explicit 500.
|
||||
export function portfolioSnapshot(value: Prisma.JsonValue): PortfolioDto {
|
||||
const snapshot = value as null | Partial<PortfolioDto>;
|
||||
if (
|
||||
!Array.isArray(snapshot?.positions) ||
|
||||
!Array.isArray(snapshot.totalsByCurrency) ||
|
||||
!Array.isArray(snapshot.cashBalances)
|
||||
) {
|
||||
throw new Error('Corrupted portfolio snapshot payload');
|
||||
}
|
||||
return snapshot as PortfolioDto;
|
||||
}
|
||||
|
||||
@@ -268,6 +268,7 @@ export class TbankHourlyScheduler implements OnModuleDestroy, OnModuleInit {
|
||||
account.accountId,
|
||||
dispatch,
|
||||
dispatchProblems,
|
||||
walkStartedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -340,9 +341,12 @@ export class TbankHourlyScheduler implements OnModuleDestroy, OnModuleInit {
|
||||
accountId: string,
|
||||
dispatch: DispatchStep,
|
||||
dispatchProblems: HourlySection[],
|
||||
walkStartedAt: Date,
|
||||
) {
|
||||
try {
|
||||
const ids = await this.withBound(this.events.refresh(userId, accountId));
|
||||
const ids = await this.withBound(
|
||||
this.events.refresh(userId, accountId, {}, walkStartedAt),
|
||||
);
|
||||
if (ids !== BOUND_EXPIRED) {
|
||||
for (const id of ids) {
|
||||
await dispatch({ accountId, id, section: 'events' });
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
jest.mock('../../../prisma/prisma.service', () => ({
|
||||
PrismaService: class {},
|
||||
}));
|
||||
|
||||
import { screenIntent } from './tbank-sync.repository';
|
||||
|
||||
describe('screen sync intent', () => {
|
||||
it('restores a persisted intent and rejects a corrupted one', () => {
|
||||
const intent = { now: '2026-11-02T00:00:00.000Z', scope: { screen: 'accounts' } };
|
||||
expect(screenIntent(intent)).toEqual(intent);
|
||||
expect(() => screenIntent({ source: 'hourly' })).toThrow('Corrupted screen sync intent');
|
||||
expect(() => screenIntent(null)).toThrow('Corrupted screen sync intent');
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,15 @@ import type { InvestmentScreenDto } from './tbank-sync.dto';
|
||||
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
export type ScreenIntent = { now: string; scope: InvestmentScreenDto };
|
||||
|
||||
// Json columns are written only by this repository; a shape check turns corruption into an explicit 500.
|
||||
export function screenIntent(value: Prisma.JsonValue): ScreenIntent {
|
||||
const intent = value as null | Partial<ScreenIntent>;
|
||||
if (typeof intent?.now !== 'string' || typeof intent.scope?.screen !== 'string') {
|
||||
throw new Error('Corrupted screen sync intent');
|
||||
}
|
||||
return intent as ScreenIntent;
|
||||
}
|
||||
export type ScreenProgress = {
|
||||
attempts?: Record<string, string>;
|
||||
children: string[];
|
||||
@@ -226,10 +235,8 @@ export class TbankSyncRepository {
|
||||
processRunId: runId,
|
||||
state: 'running',
|
||||
priority: 0,
|
||||
intent: JSON.parse(
|
||||
JSON.stringify({ source: 'hourly' }),
|
||||
) as Prisma.InputJsonObject,
|
||||
progress: { sections: [] } as unknown as Prisma.InputJsonValue,
|
||||
intent: { source: 'hourly' },
|
||||
progress: { sections: [] },
|
||||
errorCode: null,
|
||||
};
|
||||
const work = await tx.tbankSyncWork.upsert({
|
||||
|
||||
@@ -8,10 +8,7 @@ import { randomUUID } from 'node:crypto';
|
||||
import { TbankAccessService } from '../../../integrations/tbank/tbank.api';
|
||||
import { BrokerageOperationsSyncService } from '../operations/operations.api';
|
||||
import { TbankSyncStatusDto } from './tbank-sync.dto';
|
||||
import {
|
||||
type ScreenIntent,
|
||||
TbankSyncRepository,
|
||||
} from './tbank-sync.repository';
|
||||
import { screenIntent, TbankSyncRepository } from './tbank-sync.repository';
|
||||
|
||||
@Injectable()
|
||||
export class TbankSyncService {
|
||||
@@ -35,7 +32,7 @@ export class TbankSyncService {
|
||||
if (!saved.work.scopeKey.startsWith('screen:')) {
|
||||
return this.sourceStatus(userId, saved.work);
|
||||
}
|
||||
const intent = saved.work.intent as unknown as ScreenIntent;
|
||||
const intent = screenIntent(saved.work.intent);
|
||||
await this.access.local(userId, intent.scope.accountId);
|
||||
const children = await Promise.all(
|
||||
saved.children.map((child) =>
|
||||
|
||||
@@ -65,6 +65,14 @@ export class UpcomingEventDto {
|
||||
declare projectedAmount: MoneyDto | null;
|
||||
}
|
||||
|
||||
export class UpcomingEventsWindowDto {
|
||||
@ApiProperty({ format: 'date' })
|
||||
declare from: string;
|
||||
|
||||
@ApiProperty({ format: 'date' })
|
||||
declare to: string;
|
||||
}
|
||||
|
||||
export class UpcomingEventsDto {
|
||||
@ApiProperty()
|
||||
declare accountId: string;
|
||||
@@ -72,6 +80,13 @@ export class UpcomingEventsDto {
|
||||
@ApiProperty({ format: 'date-time' })
|
||||
declare calculatedAt: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: UpcomingEventsWindowDto,
|
||||
description:
|
||||
'Inclusive UTC window the saved forecast was calculated for. Unchanged by the requested from/to filter.',
|
||||
})
|
||||
declare window: UpcomingEventsWindowDto;
|
||||
|
||||
@ApiProperty({ type: UpcomingEventDto, isArray: true })
|
||||
declare events: UpcomingEventDto[];
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ export class UpcomingEventsService {
|
||||
a.type.localeCompare(b.type) ||
|
||||
a.ticker.localeCompare(b.ticker),
|
||||
);
|
||||
const candidate: undefined | UpcomingEventsDto = ready
|
||||
const candidate: Omit<UpcomingEventsDto, 'window'> | undefined = ready
|
||||
? {
|
||||
accountId,
|
||||
calculatedAt: new Date().toISOString(),
|
||||
@@ -163,6 +163,7 @@ export class UpcomingEventsService {
|
||||
revision: connection.revision,
|
||||
membershipRevision: connection.membershipRevision,
|
||||
scopeKey: `events/${JSON.stringify([accountId, window.from, window.to])}`,
|
||||
replacesLatest: query.from === undefined && query.to === undefined,
|
||||
portfolio: portfolio.meta,
|
||||
lastAttempt: hourlyAttempt(
|
||||
hourly,
|
||||
@@ -184,6 +185,7 @@ export class UpcomingEventsService {
|
||||
userId: string,
|
||||
accountId: string,
|
||||
query: UpcomingEventsQueryDto = {},
|
||||
walkStartedAt?: Date,
|
||||
): Promise<string[]> {
|
||||
const window = dateWindow(query);
|
||||
await this.access.local(userId, accountId);
|
||||
@@ -194,6 +196,7 @@ export class UpcomingEventsService {
|
||||
positions,
|
||||
window,
|
||||
false,
|
||||
walkStartedAt,
|
||||
);
|
||||
return launched;
|
||||
}
|
||||
@@ -203,6 +206,7 @@ export class UpcomingEventsService {
|
||||
positions: Position[],
|
||||
window: { from: string; to: string },
|
||||
observe: boolean,
|
||||
refreshBefore?: Date,
|
||||
) {
|
||||
const metadata = await this.metadata.savedMany(positions);
|
||||
const sources: Awaited<ReturnType<CatalogEnrichmentService['readMany']>> =
|
||||
@@ -228,6 +232,7 @@ export class UpcomingEventsService {
|
||||
identities.map((entry) => [entry.uid, entry.ticker]),
|
||||
),
|
||||
},
|
||||
refreshBefore,
|
||||
);
|
||||
sources.push(...batch);
|
||||
for (const source of batch) {
|
||||
|
||||
@@ -102,6 +102,7 @@ test('architecture imports enforce direct boundaries without banning DTOs or pur
|
||||
[controller, 'import { PrismaService } from "../../../prisma/prisma.service";'],
|
||||
[controller, 'import { TbankClient } from "../../../integrations/tbank/tbank.api";'],
|
||||
[useCase, 'import { PrismaService } from "../../../../prisma/prisma.service";'],
|
||||
['src/modules/banking/bank-cards/application/bank-cards.service.ts', 'import { PrismaService } from "../../../../prisma/prisma.service";'],
|
||||
]) {
|
||||
const [result] = await eslint.lintText(code, { filePath });
|
||||
assert.equal(result.fatalErrorCount, 0);
|
||||
@@ -113,7 +114,7 @@ test('architecture imports enforce direct boundaries without banning DTOs or pur
|
||||
[controller, 'import { AuthService } from "../application/auth.service";'],
|
||||
[useCase, 'import { BankCardsRepository } from "../infrastructure/bank-cards.repository";'],
|
||||
[useCase, 'import { BankSummaryQueryDto } from "../presentation/bank-card.dto";'],
|
||||
['src/modules/banking/bank-cards/application/bank-cards.service.ts', 'import { PrismaService } from "../../../../prisma/prisma.service";'],
|
||||
['src/modules/banking/bank-cards/application/bank-cards.service.ts', 'import type { Prisma } from "../../../../../generated/prisma/client";'],
|
||||
]) {
|
||||
const [result] = await eslint.lintText(code, { filePath });
|
||||
assert.equal(result.fatalErrorCount, 0);
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
import { TbankAccessService } from '../src/integrations/tbank/tbank-access.service';
|
||||
import { TbankTokenService } from '../src/integrations/tbank/tbank-token.service';
|
||||
import { PrismaService } from '../src/prisma/prisma.service';
|
||||
|
||||
// Characterizes the membership reserve protocol on real SQLite transactions.
|
||||
// Join by the same process while the attempt is active; launch after it is not.
|
||||
describe('membership reservation protocol (SQLite)', () => {
|
||||
const prisma = new PrismaService(
|
||||
new ConfigService({ DATABASE_URL: process.env.DATABASE_URL }),
|
||||
);
|
||||
const tokens = new TbankTokenService(
|
||||
new ConfigService({
|
||||
TOKEN_ENCRYPTION_KEY: process.env.TOKEN_ENCRYPTION_KEY,
|
||||
}) as never,
|
||||
);
|
||||
const access = new TbankAccessService(prisma, tokens);
|
||||
const userId = 'synthetic-membership-reservation';
|
||||
const revision = `${userId}-revision`;
|
||||
|
||||
beforeAll(async () => {
|
||||
await prisma.$connect();
|
||||
await prisma.tbankSyncWork.deleteMany({ where: { userId } });
|
||||
await prisma.tbankConnection.deleteMany({ where: { userId } });
|
||||
await prisma.user.deleteMany({ where: { id: userId } });
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: userId,
|
||||
email: `${userId}@example.invalid`,
|
||||
passwordHash: 'synthetic',
|
||||
},
|
||||
});
|
||||
await prisma.tbankConnection.create({
|
||||
data: {
|
||||
userId,
|
||||
revision,
|
||||
encryptedToken: tokens.encrypt('synthetic-membership'),
|
||||
connectedAt: new Date(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await prisma.tbankSyncWork.deleteMany({ where: { userId } });
|
||||
await prisma.tbankConnection.deleteMany({ where: { userId } });
|
||||
await prisma.user.deleteMany({ where: { id: userId } });
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
|
||||
it('launches once, joins the active attempt by the same process, and relaunches after it finishes', async () => {
|
||||
const processRunId = 'run-membership-a';
|
||||
const first = await access.reserveMembership(
|
||||
userId,
|
||||
revision,
|
||||
processRunId,
|
||||
new Set(),
|
||||
true,
|
||||
);
|
||||
expect(first?.launch).toBe(true);
|
||||
const attemptId = first?.work.attemptId ?? '';
|
||||
|
||||
const joined = await access.reserveMembership(
|
||||
userId,
|
||||
revision,
|
||||
processRunId,
|
||||
new Set([attemptId]),
|
||||
true,
|
||||
);
|
||||
expect(joined?.launch).toBe(false);
|
||||
expect(joined?.work.id).toBe(first?.work.id);
|
||||
expect(joined?.work.attemptId).toBe(attemptId);
|
||||
|
||||
// The attempt is no longer in the active set: this must not join it.
|
||||
const relaunched = await access.reserveMembership(
|
||||
userId,
|
||||
revision,
|
||||
processRunId,
|
||||
new Set(),
|
||||
true,
|
||||
);
|
||||
expect(relaunched?.launch).toBe(true);
|
||||
expect(relaunched?.work.attemptId).not.toBe(attemptId);
|
||||
});
|
||||
|
||||
it('does not join an attempt started by another process', async () => {
|
||||
const other = await access.reserveMembership(
|
||||
userId,
|
||||
revision,
|
||||
'run-membership-b',
|
||||
new Set(),
|
||||
true,
|
||||
);
|
||||
expect(other?.launch).toBe(true);
|
||||
const attemptId = other?.work.attemptId ?? '';
|
||||
|
||||
const foreign = await access.reserveMembership(
|
||||
userId,
|
||||
revision,
|
||||
'run-membership-c',
|
||||
new Set([attemptId]),
|
||||
true,
|
||||
);
|
||||
expect(foreign?.launch).toBe(true);
|
||||
expect(foreign?.work.attemptId).not.toBe(attemptId);
|
||||
});
|
||||
});
|
||||
@@ -82,7 +82,10 @@ describe('saved payout calendars and complete forecasts (SQLite HTTP)', () => {
|
||||
`brokerage-accounts/${scope}/events?from=${range.from}&to=${range.to}${observe ? '&sync=observe' : ''}`,
|
||||
userId,
|
||||
);
|
||||
const refresh = async (range = window, accountId = 'account') => {
|
||||
const refresh = async (
|
||||
range: { from?: string; to?: string } = window,
|
||||
accountId = 'account',
|
||||
) => {
|
||||
await app.get(UpcomingEventsService).refresh('owner', accountId, range);
|
||||
await settled();
|
||||
};
|
||||
@@ -318,17 +321,23 @@ describe('saved payout calendars and complete forecasts (SQLite HTTP)', () => {
|
||||
expect(upstream.getDividends).toHaveBeenCalledTimes(count);
|
||||
});
|
||||
|
||||
it('never relabels another range or membership snapshot and rejects inaccessible accounts locally', async () => {
|
||||
it('serves a disjoint range as an empty saved result and never relabels a membership snapshot', async () => {
|
||||
await refresh();
|
||||
await settled();
|
||||
await events().expect(200);
|
||||
const saved = (await events().expect(200))
|
||||
.body as UpcomingEventsResourceDto;
|
||||
const newRange = (
|
||||
await events(true, 'account', 'owner', {
|
||||
from: '2099-03-01',
|
||||
to: '2099-03-31',
|
||||
}).expect(200)
|
||||
).body as UpcomingEventsResourceDto;
|
||||
expect(newRange.data).toBeNull();
|
||||
expect(newRange.data).toEqual({
|
||||
...saved.data,
|
||||
events: [],
|
||||
incomeTotalsByCurrency: [],
|
||||
});
|
||||
expect(newRange.data?.window).toEqual(window);
|
||||
await prisma.tbankConnection.update({
|
||||
where: { userId: 'owner' },
|
||||
data: { membershipRevision: { increment: 1 } },
|
||||
@@ -640,6 +649,247 @@ describe('saved payout calendars and complete forecasts (SQLite HTTP)', () => {
|
||||
expect(moex.bondEvents).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps the latest wide forecast when an explicit narrower range has a complete candidate', async () => {
|
||||
await refresh();
|
||||
const full = (await events().expect(200))
|
||||
.body as UpcomingEventsResourceDto;
|
||||
const narrowRange = { from: '2099-02-01', to: '2099-02-10' };
|
||||
await refresh(narrowRange);
|
||||
|
||||
const narrow = (await events(true, 'account', 'owner', narrowRange).expect(
|
||||
200,
|
||||
)).body as UpcomingEventsResourceDto;
|
||||
|
||||
expect(narrow.data?.calculatedAt).toBe(full.data?.calculatedAt);
|
||||
expect(narrow.data?.window).toEqual(window);
|
||||
expect(narrow.data?.events.map((event) => event.date)).toEqual([
|
||||
'2099-02-01',
|
||||
]);
|
||||
expect(await prisma.tbankForecast.count()).toBe(1);
|
||||
});
|
||||
|
||||
describe('daily default window shift', () => {
|
||||
const day0 = '2099-02-01';
|
||||
const day1 = '2099-02-02';
|
||||
const windowOf = (from: string, to: string) => ({ from, to });
|
||||
const w0 = windowOf(day0, '2099-03-03');
|
||||
const w1 = windowOf(day1, '2099-03-04');
|
||||
const dividend = (date: string) => ({
|
||||
recordDate: time(date),
|
||||
dividendNet: { units: '10', nano: 1, currency: 'usd' },
|
||||
});
|
||||
const defaultEvents = async () =>
|
||||
(await get('brokerage-accounts/account/events?sync=observe').expect(200))
|
||||
.body as UpcomingEventsResourceDto;
|
||||
// Only Date is faked: the app and SQLite helpers need real timers.
|
||||
const clock = (date: string) => {
|
||||
jest.useFakeTimers({
|
||||
doNotFake: [
|
||||
'hrtime', 'nextTick', 'performance', 'queueMicrotask',
|
||||
'requestAnimationFrame', 'cancelAnimationFrame',
|
||||
'requestIdleCallback', 'cancelIdleCallback', 'setImmediate',
|
||||
'clearImmediate', 'setInterval', 'clearInterval', 'setTimeout',
|
||||
'clearTimeout',
|
||||
],
|
||||
now: new Date(`${date}T12:00:00Z`),
|
||||
});
|
||||
};
|
||||
afterEach(() => jest.useRealTimers());
|
||||
|
||||
it('publishes the new window as latest and serves it for stale or disjoint explicit ranges', async () => {
|
||||
clock(day0);
|
||||
upstream.getDividends.mockResolvedValue([
|
||||
dividend('2099-02-05'),
|
||||
dividend('2099-03-04'),
|
||||
]);
|
||||
await portfolio([position(shareUid, '2')]);
|
||||
await refresh({});
|
||||
const first = await defaultEvents();
|
||||
expect(first.data?.window).toEqual(w0);
|
||||
expect(first.data?.incomeTotalsByCurrency).toEqual([
|
||||
{ currency: 'USD', value: '20.000000002' },
|
||||
]);
|
||||
|
||||
jest.setSystemTime(new Date(`${day1}T12:00:00Z`));
|
||||
await portfolio([position(shareUid, '5')]);
|
||||
await refresh({});
|
||||
const second = await defaultEvents();
|
||||
|
||||
expect(second.data?.window).toEqual(w1);
|
||||
expect(second.data?.calculatedAt).not.toBe(first.data?.calculatedAt);
|
||||
expect(second.data?.events.map((event) => event.date)).toEqual([
|
||||
'2099-02-05',
|
||||
'2099-03-04',
|
||||
]);
|
||||
expect(second.data?.incomeTotalsByCurrency).toEqual([
|
||||
{ currency: 'USD', value: '100.00000001' },
|
||||
]);
|
||||
const stale = (await events(true, 'account', 'owner', w0).expect(200))
|
||||
.body as UpcomingEventsResourceDto;
|
||||
expect(stale.data?.calculatedAt).toBe(second.data?.calculatedAt);
|
||||
expect(stale.data?.window).toEqual(w1);
|
||||
const disjoint = (
|
||||
await events(true, 'account', 'owner', {
|
||||
from: '2100-01-01',
|
||||
to: '2100-01-31',
|
||||
}).expect(200)
|
||||
).body as UpcomingEventsResourceDto;
|
||||
expect(disjoint.data).toEqual({
|
||||
...second.data,
|
||||
events: [],
|
||||
incomeTotalsByCurrency: [],
|
||||
});
|
||||
expect(await prisma.tbankForecast.count()).toBe(2);
|
||||
});
|
||||
|
||||
it('keeps the previous complete forecast when a holding calendar fails after the shift', async () => {
|
||||
clock(day0);
|
||||
upstream.getDividends.mockResolvedValue([dividend('2099-02-05')]);
|
||||
await refresh({});
|
||||
const before = await defaultEvents();
|
||||
expect(before.data?.window).toEqual(w0);
|
||||
|
||||
jest.setSystemTime(new Date(`${day1}T12:00:00Z`));
|
||||
await portfolio([position(shareUid, '7'), position(newUid, '5')]);
|
||||
upstream.getDividends.mockImplementation((_token: string, uid: string) =>
|
||||
uid === newUid
|
||||
? Promise.reject(new Error('new calendar unavailable'))
|
||||
: Promise.resolve([dividend('2099-02-05')]),
|
||||
);
|
||||
await refresh({});
|
||||
|
||||
expect((await defaultEvents()).data).toEqual(before.data);
|
||||
expect(await prisma.tbankForecast.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('publishes the shifted window even when no source depends on it', async () => {
|
||||
clock(day0);
|
||||
await portfolio([]);
|
||||
await refresh({});
|
||||
expect((await defaultEvents()).data?.window).toEqual(w0);
|
||||
|
||||
jest.setSystemTime(new Date(`${day1}T12:00:00Z`));
|
||||
await refresh({});
|
||||
|
||||
expect((await defaultEvents()).data?.window).toEqual(w1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hourly pass refreshes saved payout calendars', () => {
|
||||
const date = new Date(Date.now() + 7 * 86400000).toISOString().slice(0, 10);
|
||||
const dividend = (units: string, dividendType = 'Regular') => ({
|
||||
recordDate: time(date),
|
||||
dividendType,
|
||||
dividendNet: { units, currency: 'usd' },
|
||||
});
|
||||
// One hourly walk: the scheduler stamps it once and passes it to every account.
|
||||
const startWalk = async () => {
|
||||
await delay(10);
|
||||
return new Date();
|
||||
};
|
||||
const pass = async (walkStartedAt: Date, accountId = 'account') => {
|
||||
await app
|
||||
.get(UpcomingEventsService)
|
||||
.refresh('owner', accountId, {}, walkStartedAt);
|
||||
await settled();
|
||||
};
|
||||
const latest = async () =>
|
||||
(await get('brokerage-accounts/account/events?sync=observe').expect(200))
|
||||
.body as UpcomingEventsResourceDto;
|
||||
const dividendRow = () =>
|
||||
prisma.tbankInstrumentSource.findFirstOrThrow({
|
||||
where: { instrumentUid: shareUid, kind: 'dividends' },
|
||||
});
|
||||
|
||||
it('picks up a changed and then a cancelled payout on the next pass of the same window', async () => {
|
||||
upstream.getDividends.mockResolvedValue([dividend('10')]);
|
||||
await pass(await startWalk());
|
||||
expect((await latest()).data?.incomeTotalsByCurrency).toEqual([
|
||||
{ currency: 'USD', value: '20' },
|
||||
]);
|
||||
const first = await dividendRow();
|
||||
|
||||
upstream.getDividends.mockResolvedValue([dividend('30')]);
|
||||
await pass(await startWalk());
|
||||
expect((await latest()).data?.incomeTotalsByCurrency).toEqual([
|
||||
{ currency: 'USD', value: '60' },
|
||||
]);
|
||||
expect((await dividendRow()).dataRevision).toBe(first.dataRevision + 1);
|
||||
|
||||
upstream.getDividends.mockResolvedValue([dividend('30', 'Cancelled')]);
|
||||
await pass(await startWalk());
|
||||
expect((await latest()).data?.events).toEqual([]);
|
||||
});
|
||||
|
||||
it('keeps the first complete calendar, time and forecast when the next refresh fails', async () => {
|
||||
upstream.getDividends.mockResolvedValue([dividend('10')]);
|
||||
await pass(await startWalk());
|
||||
const before = await latest();
|
||||
const row = await dividendRow();
|
||||
|
||||
upstream.getDividends.mockRejectedValue(new Error('outage'));
|
||||
await pass(await startWalk());
|
||||
const after = await latest();
|
||||
|
||||
expect(after.data).toEqual(before.data);
|
||||
expect(after.meta.lastSuccessfulAt).toBe(before.meta.lastSuccessfulAt);
|
||||
expect(
|
||||
after.meta.dependencies?.some(
|
||||
(dependency) => dependency.lastAttempt.state === 'failed',
|
||||
),
|
||||
).toBe(true);
|
||||
const kept = await dividendRow();
|
||||
expect(kept.dataRevision).toBe(row.dataRevision);
|
||||
expect(kept.fetchedAt).toEqual(row.fetchedAt);
|
||||
});
|
||||
|
||||
it('loads one shared calendar once per walk across accounts and leaves detail, GET and a plain refresh alone', async () => {
|
||||
await prisma.tbankAccount.create({
|
||||
data: {
|
||||
userId: 'owner',
|
||||
revision: 'owner-revision',
|
||||
accountId: 'second',
|
||||
type: 'ACCOUNT_TYPE_TINKOFF',
|
||||
name: 'Second',
|
||||
upstreamOrder: 1,
|
||||
},
|
||||
});
|
||||
await portfolio([position()], 'owner', 'second');
|
||||
upstream.getDividends.mockResolvedValue([dividend('10')]);
|
||||
await pass(await startWalk());
|
||||
const detailCalls = () =>
|
||||
upstream.getShare.mock.calls.length +
|
||||
upstream.getInstrumentByUid.mock.calls.length;
|
||||
const detailBefore = detailCalls();
|
||||
expect(upstream.getDividends).toHaveBeenCalledTimes(1);
|
||||
|
||||
const walk = await startWalk();
|
||||
await pass(walk, 'account');
|
||||
await pass(walk, 'second');
|
||||
expect(upstream.getDividends).toHaveBeenCalledTimes(2);
|
||||
|
||||
await app.get(UpcomingEventsService).refresh('owner', 'account', {});
|
||||
await settled();
|
||||
await latest();
|
||||
await get('brokerage-accounts/all/events').expect(200);
|
||||
expect(upstream.getDividends).toHaveBeenCalledTimes(2);
|
||||
expect(detailCalls()).toBe(detailBefore);
|
||||
});
|
||||
|
||||
it('re-reads the bond calendar whose key never changes, only on a walk pass', async () => {
|
||||
await portfolio([position(bondUid, '3', 'BOND')]);
|
||||
await pass(await startWalk());
|
||||
expect(moex.bondEvents).toHaveBeenCalledTimes(1);
|
||||
|
||||
await app.get(UpcomingEventsService).refresh('owner', 'account', {});
|
||||
await settled();
|
||||
expect(moex.bondEvents).toHaveBeenCalledTimes(1);
|
||||
|
||||
await pass(await startWalk());
|
||||
expect(moex.bondEvents).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
it('discards a late calendar from a replaced connection and prevents access to old private forecasts', async () => {
|
||||
let release: (value: unknown[]) => void = () => {};
|
||||
upstream.getDividends.mockReturnValueOnce(
|
||||
|
||||
Reference in New Issue
Block a user