Batch account-balance evaluate and format range inputs with separators and gram labels.

EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-18 13:22:38 +03:30
co-authored by Cursor
parent 5fbdb4495f
commit ae61c321a1
6 changed files with 293 additions and 65 deletions
@@ -8,7 +8,7 @@ import { RequireOrgModule } from '../billing/org-module.decorator';
import { OrgModuleGuard } from '../billing/org-module.guard';
import { AccountBalanceSettingsService } from './account-balance-settings.service';
import { BalanceClaimsService } from './balance-claims.service';
import { UpdateAccountBalanceSettingsDto } from './dto';
import { EvaluateAccountBalancesDto, UpdateAccountBalanceSettingsDto } from './dto';
@Controller('account-balances')
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
@@ -31,10 +31,13 @@ export class AccountBalancesController {
return this.settings.update(user.organizationId, dto);
}
/** اجرای دستی همان جاب دوره‌ای برای محیط جاری */
/** یک تکه از ارزیابی (حداکثر ۲۰۰۰ نفر)؛ کلاینت تکه‌ها را پشت سر هم می‌زند */
@Post('evaluate')
@Roles('owner', 'admin')
evaluate(@CurrentUser() user: Actor) {
return this.claims.evaluateOrganization(user.organizationId);
evaluate(@CurrentUser() user: Actor, @Body() dto: EvaluateAccountBalancesDto) {
return this.claims.evaluateOrganization(user.organizationId, {
offset: dto.offset,
limit: dto.limit,
});
}
}
@@ -46,7 +46,7 @@ export class BalanceClaimsScheduler {
});
if (claimed.count !== 1) continue;
try {
await this.claims.evaluateOrganization(org.id);
await this.claims.evaluateOrganizationFully(org.id);
this.logger.log(`جاب مطالبات مانده برای «${org.name}» اجرا شد (${slot}).`);
} catch (err) {
this.logger.warn(
@@ -1,6 +1,7 @@
import { Injectable, Logger } from '@nestjs/common';
import {
ACCOUNT_BALANCE_CLAIMS_TAG,
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
accountBalanceInRange,
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
@@ -16,6 +17,8 @@ import { TahesabBalanceService } from '../integrations/tahesab/balance.service';
const BOARD_NAME = 'مطالبات';
const FOLLOW_UP_TYPE_NAME = 'پیگیری';
/** همزمانی داخل هر تکه برای ماندن زیر تایم‌اوت */
const BATCH_CONCURRENCY = 20;
type PersonClaimContext = {
personId: string;
@@ -185,7 +188,7 @@ export class BalanceClaimsService {
});
for (const org of orgs) {
try {
await this.evaluateOrganization(org.id);
await this.evaluateOrganizationFully(org.id);
} catch (err) {
this.logger.warn(
`ارزیابی مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
@@ -194,7 +197,35 @@ export class BalanceClaimsService {
}
}
async evaluateOrganization(organizationId: string): Promise<AccountBalanceEvaluateResultDto> {
/** همهٔ تکه‌ها پشت سر هم (برای جاب زمان‌بندی‌شده) */
async evaluateOrganizationFully(organizationId: string): Promise<AccountBalanceEvaluateResultDto> {
let offset = 0;
let merged: AccountBalanceEvaluateResultDto | null = null;
for (;;) {
const batch = await this.evaluateOrganization(organizationId, {
offset,
limit: ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
});
merged = merged ? this.mergeResults(merged, batch) : batch;
if (batch.done || batch.nextOffset == null) {
merged.message = this.summarize(merged);
this.logger.log(`مطالبات کامل ${organizationId}: ${merged.message}`);
return merged;
}
offset = batch.nextOffset;
}
}
async evaluateOrganization(
organizationId: string,
opts?: { offset?: number; limit?: number },
): Promise<AccountBalanceEvaluateResultDto> {
const offset = Math.max(0, Math.floor(opts?.offset ?? 0));
const limit = Math.min(
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
Math.max(1, Math.floor(opts?.limit ?? ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE)),
);
const empty = (message: string): AccountBalanceEvaluateResultDto => ({
linkedPeople: 0,
candidates: 0,
@@ -206,6 +237,11 @@ export class BalanceClaimsService {
unchanged: 0,
errors: 0,
message,
offset,
limit,
batchProcessed: 0,
done: true,
nextOffset: null,
});
const org = await this.prisma.organization.findUnique({
@@ -239,6 +275,10 @@ export class BalanceClaimsService {
const { candidates, linkedPeople, skippedNoAssignee } =
await this.loadCandidates(organizationId);
const slice = candidates.slice(offset, offset + limit);
const nextOffset = offset + slice.length;
const done = nextOffset >= candidates.length;
const result: AccountBalanceEvaluateResultDto = {
linkedPeople,
candidates: candidates.length,
@@ -250,11 +290,16 @@ export class BalanceClaimsService {
unchanged: 0,
errors: 0,
message: '',
offset,
limit,
batchProcessed: slice.length,
done,
nextOffset: done ? null : nextOffset,
};
for (const person of candidates) {
const actions = await this.mapPool(slice, BATCH_CONCURRENCY, async (person) => {
try {
const action = await this.syncPerson({
return await this.syncPerson({
organizationId,
person,
settings,
@@ -263,34 +308,82 @@ export class BalanceClaimsService {
canceledStageId,
typeDefId: typeDef.id,
baseType: typeDef.baseType,
preferCache: true,
});
if (action === 'created') {
result.matched += 1;
result.created += 1;
} else if (action === 'reopened') {
result.matched += 1;
result.reopened += 1;
} else if (action === 'canceled') {
result.canceled += 1;
} else if (action === 'matched-unchanged') {
result.matched += 1;
result.unchanged += 1;
} else {
result.unchanged += 1;
}
} catch (err) {
result.errors += 1;
this.logger.warn(
`مانده/مطالبه شخص ${person.personId}: ${err instanceof Error ? err.message : err}`,
);
return 'error' as const;
}
});
for (const action of actions) {
if (action === 'created') {
result.matched += 1;
result.created += 1;
} else if (action === 'reopened') {
result.matched += 1;
result.reopened += 1;
} else if (action === 'canceled') {
result.canceled += 1;
} else if (action === 'matched-unchanged') {
result.matched += 1;
result.unchanged += 1;
} else if (action === 'error') {
result.errors += 1;
} else {
result.unchanged += 1;
}
}
result.message = this.summarize(result);
result.message = done
? this.summarize(result)
: `تکه ${offset + 1} تا ${nextOffset} از ${candidates.length} · ادامه…`;
this.logger.log(`مطالبات ${organizationId}: ${result.message}`);
return result;
}
private mergeResults(
a: AccountBalanceEvaluateResultDto,
b: AccountBalanceEvaluateResultDto,
): AccountBalanceEvaluateResultDto {
return {
linkedPeople: Math.max(a.linkedPeople, b.linkedPeople),
candidates: Math.max(a.candidates, b.candidates),
skippedNoAssignee: Math.max(a.skippedNoAssignee, b.skippedNoAssignee),
matched: a.matched + b.matched,
created: a.created + b.created,
reopened: a.reopened + b.reopened,
canceled: a.canceled + b.canceled,
unchanged: a.unchanged + b.unchanged,
errors: a.errors + b.errors,
message: b.message,
offset: a.offset,
limit: a.limit,
batchProcessed: a.batchProcessed + b.batchProcessed,
done: b.done,
nextOffset: b.nextOffset,
};
}
private async mapPool<T, R>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<R>,
): Promise<R[]> {
if (!items.length) return [];
const out = new Array<R>(items.length);
let index = 0;
const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (index < items.length) {
const currentIndex = index++;
out[currentIndex] = await worker(items[currentIndex]!);
}
});
await Promise.all(runners);
return out;
}
private summarize(r: AccountBalanceEvaluateResultDto): string {
if (r.linkedPeople === 0) {
return 'هیچ مشتری لینک‌شده به ته‌حساب پیدا نشد.';
@@ -414,21 +507,40 @@ export class BalanceClaimsService {
canceledStageId: string;
typeDefId: string;
baseType: 'call' | 'meeting' | 'task' | 'note';
/** در ارزیابی دسته‌ای اول از کش استفاده کن تا تایم‌اوت نشود */
preferCache?: boolean;
}): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> {
let assets;
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,
);
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,
);
}
}
const matched = this.matchesAnyRange(assets, input.settings);
+18
View File
@@ -1,10 +1,13 @@
import { Type } from 'class-transformer';
import {
IsInt,
IsNumber,
IsObject,
IsOptional,
IsString,
Max,
MaxLength,
Min,
ValidateIf,
ValidateNested,
} from 'class-validator';
@@ -33,3 +36,18 @@ export class UpdateAccountBalanceSettingsDto {
@IsObject()
weights?: Record<string, AccountBalanceRangeBody | null>;
}
export class EvaluateAccountBalancesDto {
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
offset?: number;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(2000)
limit?: number;
}