Keep claims kanban balances fresh with a 30-minute Tahesab cache TTL.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-12-01 14:39:09 +03:30
co-authored by Cursor
parent be79441d8f
commit 1c74e26885
5 changed files with 119 additions and 49 deletions
@@ -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);
+8 -1
View File
@@ -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,
+81 -14
View File
@@ -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<DtoContext> {
@@ -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<T>(
items: T[],
concurrency: number,
fn: (item: T) => Promise<void>,
) {
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,
};
}
@@ -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;
+2
View File
@@ -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);