diff --git a/apps/api/src/account-balances/balance-claims.service.ts b/apps/api/src/account-balances/balance-claims.service.ts index 2387c11..ebe87b6 100644 --- a/apps/api/src/account-balances/balance-claims.service.ts +++ b/apps/api/src/account-balances/balance-claims.service.ts @@ -308,7 +308,6 @@ export class BalanceClaimsService { canceledStageId, typeDefId: typeDef.id, baseType: typeDef.baseType, - preferCache: true, }); } catch (err) { this.logger.warn( @@ -507,40 +506,22 @@ export class BalanceClaimsService { canceledStageId: string; typeDefId: string; baseType: 'call' | 'meeting' | 'task' | 'note'; - /** در ارزیابی دسته‌ای اول از کش استفاده کن تا تایم‌اوت نشود */ - preferCache?: boolean; }): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> { + // کش تازه تا TTL؛ در صورت انقضا از ته‌حساب زنده (بدون preferCache کور) let assets; - if (input.preferCache) { - try { - assets = await this.balances.getCachedOrFetch( - input.organizationId, - input.person.personId, - input.person.connectionId, - false, - ); - } catch { - assets = await this.balances.getAssets( - input.organizationId, - input.person.personId, - input.person.connectionId, - ); - } - } else { - try { - assets = await this.balances.getAssets( - input.organizationId, - input.person.personId, - input.person.connectionId, - ); - } catch { - assets = await this.balances.getCachedOrFetch( - input.organizationId, - input.person.personId, - input.person.connectionId, - false, - ); - } + try { + assets = await this.balances.getCachedOrFetch( + input.organizationId, + input.person.personId, + input.person.connectionId, + false, + ); + } catch { + assets = await this.balances.getAssets( + input.organizationId, + input.person.personId, + input.person.connectionId, + ); } const matched = this.matchesAnyRange(assets, input.settings); diff --git a/apps/api/src/activities/activities.module.ts b/apps/api/src/activities/activities.module.ts index d825a9d..e18be83 100644 --- a/apps/api/src/activities/activities.module.ts +++ b/apps/api/src/activities/activities.module.ts @@ -8,9 +8,16 @@ import { NotificationsModule } from '../notifications/notifications.module'; import { AutomationsModule } from '../automations/automations.module'; import { MessageAutomationsModule } from '../message-automations/message-automations.module'; import { StorageModule } from '../storage/storage.module'; +import { TahesabModule } from '../integrations/tahesab/tahesab.module'; @Module({ - imports: [NotificationsModule, AutomationsModule, MessageAutomationsModule, StorageModule], + imports: [ + NotificationsModule, + AutomationsModule, + MessageAutomationsModule, + StorageModule, + TahesabModule, + ], controllers: [ActivitiesController], providers: [ ActivitiesService, diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts index 188db41..c122775 100644 --- a/apps/api/src/activities/activities.service.ts +++ b/apps/api/src/activities/activities.service.ts @@ -46,6 +46,10 @@ import { buildSearchWhere, ci } from '../common/search'; import { activityPriorWhere } from '../common/prior-archive'; import { leadsDeepWhere } from '../common/data-access'; import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods'; +import { + isAccountingBalanceCacheStale, + TahesabBalanceService, +} from '../integrations/tahesab/balance.service'; import { ActivityStagesService, type BoardStageContext } from './activity-stages.service'; import { ActivityTypesService, @@ -53,6 +57,9 @@ import { type TypeRow, } from './activity-types.service'; +/** همزمانی رفرش مانده هنگام بارگذاری کاریز مطالبات */ +const CLAIM_BALANCE_REFRESH_CONCURRENCY = 5; + type DtoContext = { stages?: BoardStageContext; types?: SystemTypes }; type ActivityActor = Pick< @@ -247,6 +254,7 @@ export class ActivitiesService { private readonly game: GamificationService, private readonly files: LocalFileStorage, private readonly storage: StorageQuotaService, + private readonly tahesabBalances: TahesabBalanceService, ) {} private async ctx(organizationId: string): Promise { @@ -1661,7 +1669,7 @@ export class ActivitiesService { } } - /** فقط فعالیت‌های تگ مطالبات؛ مانده از کش ته‌حساب بدون فراخوانی زنده */ + /** فقط فعالیت‌های تگ مطالبات؛ کش تازه تا TTL، در غیر این صورت رفرش از ته‌حساب */ private async withAccountBalances( organizationId: string, items: ActivityDto[], @@ -1705,15 +1713,43 @@ export class ActivitiesService { (link.balanceCache ? 2 : 0) + (link.connection.isDefault ? 1 : 0); if (nextScore > prevScore) bestByPerson.set(link.personId, link); } + + const stalePersonIds: string[] = []; for (const personId of personIds) { const link = bestByPerson.get(personId); - balanceByPerson.set( - personId, - link?.balanceCache - ? this.cacheToAccountBalance(link.balanceCache) - : null, - ); + const cache = link?.balanceCache; + if (cache && !isAccountingBalanceCacheStale(cache.fetchedAt)) { + balanceByPerson.set(personId, this.cacheToAccountBalance(cache)); + } else if (link) { + stalePersonIds.push(personId); + } else { + balanceByPerson.set(personId, null); + } } + + await this.mapPool(stalePersonIds, CLAIM_BALANCE_REFRESH_CONCURRENCY, async (personId) => { + const link = bestByPerson.get(personId); + if (!link) { + balanceByPerson.set(personId, null); + return; + } + try { + const assets = await this.tahesabBalances.getCachedOrFetch( + organizationId, + personId, + link.connectionId, + false, + ); + balanceByPerson.set(personId, this.assetsToAccountBalance(assets)); + } catch { + balanceByPerson.set( + personId, + link.balanceCache + ? this.cacheToAccountBalance(link.balanceCache) + : null, + ); + } + }); } return items.map((item) => { @@ -1728,19 +1764,50 @@ export class ActivitiesService { }); } + private async mapPool( + items: T[], + concurrency: number, + fn: (item: T) => Promise, + ) { + if (!items.length) return; + let index = 0; + const runners = Array.from( + { length: Math.min(concurrency, items.length) }, + async () => { + while (index < items.length) { + const current = items[index++]!; + await fn(current); + } + }, + ); + await Promise.all(runners); + } + private cacheToAccountBalance(cache: { rialBalance: number | null; goldBalance: number | null; rawResponse: unknown; fetchedAt: Date; }): ActivityAccountBalanceDto { - const fields = parseAccountBalanceWeightFields( - extractMandehRaw(cache.rawResponse).fields, - ); + return this.assetsToAccountBalance({ + rialBalance: cache.rialBalance, + goldBalance: cache.goldBalance, + mandehFields: extractMandehRaw(cache.rawResponse).fields, + fetchedAt: cache.fetchedAt.toISOString(), + }); + } + + private assetsToAccountBalance(assets: { + rialBalance: number | null; + goldBalance: number | null; + mandehFields?: Array<{ key: string; value: unknown }> | null; + fetchedAt: string; + }): ActivityAccountBalanceDto { + const fields = parseAccountBalanceWeightFields(assets.mandehFields); const weights = ACCOUNT_BALANCE_WEIGHT_KEYS.map((key) => { const value = fields[key] ?? - (key === 'MandeyeVazni' ? cache.goldBalance : null) ?? + (key === 'MandeyeVazni' ? assets.goldBalance : null) ?? null; if (value == null || !Number.isFinite(value)) return null; return { @@ -1752,11 +1819,11 @@ export class ActivitiesService { return { rialBalance: - cache.rialBalance != null && Number.isFinite(cache.rialBalance) - ? cache.rialBalance + assets.rialBalance != null && Number.isFinite(assets.rialBalance) + ? assets.rialBalance : null, weights, - fetchedAt: cache.fetchedAt.toISOString(), + fetchedAt: assets.fetchedAt, }; } diff --git a/apps/api/src/integrations/tahesab/balance.service.ts b/apps/api/src/integrations/tahesab/balance.service.ts index 04c69c7..8e6c207 100644 --- a/apps/api/src/integrations/tahesab/balance.service.ts +++ b/apps/api/src/integrations/tahesab/balance.service.ts @@ -8,6 +8,16 @@ import { PrismaService } from '../../prisma/prisma.service'; import { TahesabConnectionsService } from './connections.service'; import { extractMandehRaw, normalizeMandehResponse } from './tahesab-methods'; +/** حداکثر عمر کش مانده ته‌حساب؛ بعد از آن دوباره از ته‌حساب خوانده می‌شود. */ +export const ACCOUNTING_BALANCE_CACHE_TTL_MS = 30 * 60 * 1000; + +export function isAccountingBalanceCacheStale( + fetchedAt: Date, + now = Date.now(), +): boolean { + return now - fetchedAt.getTime() >= ACCOUNTING_BALANCE_CACHE_TTL_MS; +} + @Injectable() export class TahesabBalanceService { constructor( @@ -115,7 +125,10 @@ export class TahesabBalanceService { balanceCache: true, }, }); - if (!link?.balanceCache) { + if ( + !link?.balanceCache || + isAccountingBalanceCacheStale(link.balanceCache.fetchedAt) + ) { return this.getAssets(organizationId, personId, connectionId); } const c = link.balanceCache; diff --git a/apps/api/test/promote-from-prior.test.ts b/apps/api/test/promote-from-prior.test.ts index aa1ad90..5c63e67 100644 --- a/apps/api/test/promote-from-prior.test.ts +++ b/apps/api/test/promote-from-prior.test.ts @@ -164,6 +164,7 @@ describe('promote from prior', () => { {} as never, {} as never, {} as never, + {} as never, ); const dto = await service.promoteFromPrior(actor, 'act1'); @@ -195,6 +196,7 @@ describe('promote from prior', () => { {} as never, {} as never, {} as never, + {} as never, ); await assert.rejects(service.promoteFromPrior({ ...actor, priorLens: 'off' }, 'act1'), ForbiddenException);