import { Injectable } from '@nestjs/common'; import { CacheService } from '../../cache/cache.service'; import { isSupportedBrokerAccount, mapAccount } from '../mappers/account.mapper'; import { TBANK_CACHE_KEYS } from '../tbank.config'; import type { BrokerAccount } from '../types/broker.types'; import type { TBankAccountsResponse } from '../types/tbank-proto.types'; import { TBankClientService } from './tbank-client.service'; @Injectable() export class BrokerAccountsService { constructor( private readonly tbankClient: TBankClientService, private readonly cacheService: CacheService, ) {} async findAll(): Promise<{ data: BrokerAccount[]; meta: { fromCache: boolean; cachedAt: string | null }; }> { const result = await this.cacheService.getOrFetch( TBANK_CACHE_KEYS.accounts, ['open-brokerage-iis'], () => this.fetchAccounts(), 'tbankAccountsTtl', ); return { data: result.data, meta: { fromCache: result.fromCache, cachedAt: result.cachedAt }, }; } async findById(accountId: string): Promise { const accounts = await this.findAll(); return accounts.data.find((account) => account.id === accountId) ?? null; } private async fetchAccounts(): Promise { const usersClient = this.tbankClient.getServiceClient('UsersService') as any; const response = await this.tbankClient.callUnary< Record, TBankAccountsResponse >( 'UsersService/GetAccounts', usersClient.getAccounts.bind(usersClient), { status: 'ACCOUNT_STATUS_OPEN', }, 'users', ); return (response.accounts ?? []).filter(isSupportedBrokerAccount).map(mapAccount); } }