Keep claims kanban balances fresh with a 30-minute Tahesab cache TTL.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -308,7 +308,6 @@ export class BalanceClaimsService {
|
|||||||
canceledStageId,
|
canceledStageId,
|
||||||
typeDefId: typeDef.id,
|
typeDefId: typeDef.id,
|
||||||
baseType: typeDef.baseType,
|
baseType: typeDef.baseType,
|
||||||
preferCache: true,
|
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
@@ -507,11 +506,9 @@ export class BalanceClaimsService {
|
|||||||
canceledStageId: string;
|
canceledStageId: string;
|
||||||
typeDefId: string;
|
typeDefId: string;
|
||||||
baseType: 'call' | 'meeting' | 'task' | 'note';
|
baseType: 'call' | 'meeting' | 'task' | 'note';
|
||||||
/** در ارزیابی دستهای اول از کش استفاده کن تا تایماوت نشود */
|
|
||||||
preferCache?: boolean;
|
|
||||||
}): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> {
|
}): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> {
|
||||||
|
// کش تازه تا TTL؛ در صورت انقضا از تهحساب زنده (بدون preferCache کور)
|
||||||
let assets;
|
let assets;
|
||||||
if (input.preferCache) {
|
|
||||||
try {
|
try {
|
||||||
assets = await this.balances.getCachedOrFetch(
|
assets = await this.balances.getCachedOrFetch(
|
||||||
input.organizationId,
|
input.organizationId,
|
||||||
@@ -526,22 +523,6 @@ export class BalanceClaimsService {
|
|||||||
input.person.connectionId,
|
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,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const matched = this.matchesAnyRange(assets, input.settings);
|
const matched = this.matchesAnyRange(assets, input.settings);
|
||||||
|
|
||||||
|
|||||||
@@ -8,9 +8,16 @@ import { NotificationsModule } from '../notifications/notifications.module';
|
|||||||
import { AutomationsModule } from '../automations/automations.module';
|
import { AutomationsModule } from '../automations/automations.module';
|
||||||
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
|
import { MessageAutomationsModule } from '../message-automations/message-automations.module';
|
||||||
import { StorageModule } from '../storage/storage.module';
|
import { StorageModule } from '../storage/storage.module';
|
||||||
|
import { TahesabModule } from '../integrations/tahesab/tahesab.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [NotificationsModule, AutomationsModule, MessageAutomationsModule, StorageModule],
|
imports: [
|
||||||
|
NotificationsModule,
|
||||||
|
AutomationsModule,
|
||||||
|
MessageAutomationsModule,
|
||||||
|
StorageModule,
|
||||||
|
TahesabModule,
|
||||||
|
],
|
||||||
controllers: [ActivitiesController],
|
controllers: [ActivitiesController],
|
||||||
providers: [
|
providers: [
|
||||||
ActivitiesService,
|
ActivitiesService,
|
||||||
|
|||||||
@@ -46,6 +46,10 @@ import { buildSearchWhere, ci } from '../common/search';
|
|||||||
import { activityPriorWhere } from '../common/prior-archive';
|
import { activityPriorWhere } from '../common/prior-archive';
|
||||||
import { leadsDeepWhere } from '../common/data-access';
|
import { leadsDeepWhere } from '../common/data-access';
|
||||||
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
|
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
|
||||||
|
import {
|
||||||
|
isAccountingBalanceCacheStale,
|
||||||
|
TahesabBalanceService,
|
||||||
|
} from '../integrations/tahesab/balance.service';
|
||||||
import { ActivityStagesService, type BoardStageContext } from './activity-stages.service';
|
import { ActivityStagesService, type BoardStageContext } from './activity-stages.service';
|
||||||
import {
|
import {
|
||||||
ActivityTypesService,
|
ActivityTypesService,
|
||||||
@@ -53,6 +57,9 @@ import {
|
|||||||
type TypeRow,
|
type TypeRow,
|
||||||
} from './activity-types.service';
|
} from './activity-types.service';
|
||||||
|
|
||||||
|
/** همزمانی رفرش مانده هنگام بارگذاری کاریز مطالبات */
|
||||||
|
const CLAIM_BALANCE_REFRESH_CONCURRENCY = 5;
|
||||||
|
|
||||||
type DtoContext = { stages?: BoardStageContext; types?: SystemTypes };
|
type DtoContext = { stages?: BoardStageContext; types?: SystemTypes };
|
||||||
|
|
||||||
type ActivityActor = Pick<
|
type ActivityActor = Pick<
|
||||||
@@ -247,6 +254,7 @@ export class ActivitiesService {
|
|||||||
private readonly game: GamificationService,
|
private readonly game: GamificationService,
|
||||||
private readonly files: LocalFileStorage,
|
private readonly files: LocalFileStorage,
|
||||||
private readonly storage: StorageQuotaService,
|
private readonly storage: StorageQuotaService,
|
||||||
|
private readonly tahesabBalances: TahesabBalanceService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private async ctx(organizationId: string): Promise<DtoContext> {
|
private async ctx(organizationId: string): Promise<DtoContext> {
|
||||||
@@ -1661,7 +1669,7 @@ export class ActivitiesService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** فقط فعالیتهای تگ مطالبات؛ مانده از کش تهحساب بدون فراخوانی زنده */
|
/** فقط فعالیتهای تگ مطالبات؛ کش تازه تا TTL، در غیر این صورت رفرش از تهحساب */
|
||||||
private async withAccountBalances(
|
private async withAccountBalances(
|
||||||
organizationId: string,
|
organizationId: string,
|
||||||
items: ActivityDto[],
|
items: ActivityDto[],
|
||||||
@@ -1705,15 +1713,43 @@ export class ActivitiesService {
|
|||||||
(link.balanceCache ? 2 : 0) + (link.connection.isDefault ? 1 : 0);
|
(link.balanceCache ? 2 : 0) + (link.connection.isDefault ? 1 : 0);
|
||||||
if (nextScore > prevScore) bestByPerson.set(link.personId, link);
|
if (nextScore > prevScore) bestByPerson.set(link.personId, link);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const stalePersonIds: string[] = [];
|
||||||
for (const personId of personIds) {
|
for (const personId of personIds) {
|
||||||
const link = bestByPerson.get(personId);
|
const link = bestByPerson.get(personId);
|
||||||
|
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(
|
balanceByPerson.set(
|
||||||
personId,
|
personId,
|
||||||
link?.balanceCache
|
link.balanceCache
|
||||||
? this.cacheToAccountBalance(link.balanceCache)
|
? this.cacheToAccountBalance(link.balanceCache)
|
||||||
: null,
|
: null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return items.map((item) => {
|
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: {
|
private cacheToAccountBalance(cache: {
|
||||||
rialBalance: number | null;
|
rialBalance: number | null;
|
||||||
goldBalance: number | null;
|
goldBalance: number | null;
|
||||||
rawResponse: unknown;
|
rawResponse: unknown;
|
||||||
fetchedAt: Date;
|
fetchedAt: Date;
|
||||||
}): ActivityAccountBalanceDto {
|
}): ActivityAccountBalanceDto {
|
||||||
const fields = parseAccountBalanceWeightFields(
|
return this.assetsToAccountBalance({
|
||||||
extractMandehRaw(cache.rawResponse).fields,
|
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 weights = ACCOUNT_BALANCE_WEIGHT_KEYS.map((key) => {
|
||||||
const value =
|
const value =
|
||||||
fields[key] ??
|
fields[key] ??
|
||||||
(key === 'MandeyeVazni' ? cache.goldBalance : null) ??
|
(key === 'MandeyeVazni' ? assets.goldBalance : null) ??
|
||||||
null;
|
null;
|
||||||
if (value == null || !Number.isFinite(value)) return null;
|
if (value == null || !Number.isFinite(value)) return null;
|
||||||
return {
|
return {
|
||||||
@@ -1752,11 +1819,11 @@ export class ActivitiesService {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
rialBalance:
|
rialBalance:
|
||||||
cache.rialBalance != null && Number.isFinite(cache.rialBalance)
|
assets.rialBalance != null && Number.isFinite(assets.rialBalance)
|
||||||
? cache.rialBalance
|
? assets.rialBalance
|
||||||
: null,
|
: null,
|
||||||
weights,
|
weights,
|
||||||
fetchedAt: cache.fetchedAt.toISOString(),
|
fetchedAt: assets.fetchedAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,16 @@ import { PrismaService } from '../../prisma/prisma.service';
|
|||||||
import { TahesabConnectionsService } from './connections.service';
|
import { TahesabConnectionsService } from './connections.service';
|
||||||
import { extractMandehRaw, normalizeMandehResponse } from './tahesab-methods';
|
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()
|
@Injectable()
|
||||||
export class TahesabBalanceService {
|
export class TahesabBalanceService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -115,7 +125,10 @@ export class TahesabBalanceService {
|
|||||||
balanceCache: true,
|
balanceCache: true,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
if (!link?.balanceCache) {
|
if (
|
||||||
|
!link?.balanceCache ||
|
||||||
|
isAccountingBalanceCacheStale(link.balanceCache.fetchedAt)
|
||||||
|
) {
|
||||||
return this.getAssets(organizationId, personId, connectionId);
|
return this.getAssets(organizationId, personId, connectionId);
|
||||||
}
|
}
|
||||||
const c = link.balanceCache;
|
const c = link.balanceCache;
|
||||||
|
|||||||
@@ -164,6 +164,7 @@ describe('promote from prior', () => {
|
|||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
|
{} as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
const dto = await service.promoteFromPrior(actor, 'act1');
|
const dto = await service.promoteFromPrior(actor, 'act1');
|
||||||
@@ -195,6 +196,7 @@ describe('promote from prior', () => {
|
|||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
{} as never,
|
{} as never,
|
||||||
|
{} as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
await assert.rejects(service.promoteFromPrior({ ...actor, priorLens: 'off' }, 'act1'), ForbiddenException);
|
await assert.rejects(service.promoteFromPrior({ ...actor, priorLens: 'off' }, 'act1'), ForbiddenException);
|
||||||
|
|||||||
Reference in New Issue
Block a user