2026-11-17 21:24:15 +03:30
|
|
|
import { Injectable, Logger } from '@nestjs/common';
|
|
|
|
|
import {
|
|
|
|
|
ACCOUNT_BALANCE_CLAIMS_TAG,
|
2026-11-18 13:22:38 +03:30
|
|
|
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
|
2026-11-17 21:24:15 +03:30
|
|
|
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
|
2026-11-18 15:28:08 +03:30
|
|
|
accountBalanceMatchesCriterion,
|
2026-11-17 21:24:15 +03:30
|
|
|
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
|
|
|
|
|
parseAccountBalanceSettings,
|
|
|
|
|
parseAccountBalanceWeightFields,
|
2026-11-17 21:52:57 +03:30
|
|
|
type AccountBalanceEvaluateResultDto,
|
2026-11-17 21:24:15 +03:30
|
|
|
type AccountBalanceSettingsDto,
|
|
|
|
|
} from '@mento/shared';
|
|
|
|
|
import { Prisma } from '@prisma/client';
|
|
|
|
|
import { PrismaService } from '../prisma/prisma.service';
|
|
|
|
|
import { ActivityTypesService } from '../activities/activity-types.service';
|
|
|
|
|
import { TahesabBalanceService } from '../integrations/tahesab/balance.service';
|
|
|
|
|
|
|
|
|
|
const BOARD_NAME = 'مطالبات';
|
|
|
|
|
const FOLLOW_UP_TYPE_NAME = 'پیگیری';
|
2026-11-18 13:22:38 +03:30
|
|
|
/** همزمانی داخل هر تکه برای ماندن زیر تایماوت */
|
|
|
|
|
const BATCH_CONCURRENCY = 20;
|
2026-11-17 21:24:15 +03:30
|
|
|
|
|
|
|
|
type PersonClaimContext = {
|
|
|
|
|
personId: string;
|
|
|
|
|
fullName: string;
|
|
|
|
|
connectionId: string;
|
|
|
|
|
assigneeId: string;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class BalanceClaimsService {
|
|
|
|
|
private readonly logger = new Logger(BalanceClaimsService.name);
|
|
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
|
private readonly prisma: PrismaService,
|
|
|
|
|
private readonly types: ActivityTypesService,
|
|
|
|
|
private readonly balances: TahesabBalanceService,
|
|
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
async ensureFollowUpType(organizationId: string) {
|
|
|
|
|
await this.types.ensureDefaults(organizationId);
|
|
|
|
|
const existing = await this.prisma.activityTypeDef.findFirst({
|
|
|
|
|
where: { organizationId, name: FOLLOW_UP_TYPE_NAME },
|
|
|
|
|
select: { id: true, baseType: true },
|
|
|
|
|
});
|
|
|
|
|
if (existing) return existing;
|
|
|
|
|
const max = await this.prisma.activityTypeDef.aggregate({
|
|
|
|
|
where: { organizationId },
|
|
|
|
|
_max: { position: true },
|
|
|
|
|
});
|
|
|
|
|
return this.prisma.activityTypeDef.create({
|
|
|
|
|
data: {
|
|
|
|
|
organizationId,
|
|
|
|
|
name: FOLLOW_UP_TYPE_NAME,
|
|
|
|
|
baseType: 'call',
|
|
|
|
|
icon: 'bell',
|
|
|
|
|
color: 'orange',
|
|
|
|
|
position: (max._max.position ?? 0) + 1,
|
|
|
|
|
isSystem: false,
|
|
|
|
|
fields: [
|
|
|
|
|
{
|
|
|
|
|
key: 'followup_reason',
|
|
|
|
|
label: 'دلیل پیگیری',
|
|
|
|
|
type: 'select',
|
|
|
|
|
options: ['پیشفاکتور', 'پرداخت', 'ارسال کالا', 'پشتیبانی', 'تمدید قرارداد', 'سایر'],
|
|
|
|
|
},
|
|
|
|
|
{ key: 'followup_result', label: 'نتیجهٔ پیگیری', type: 'textarea' },
|
|
|
|
|
{ key: 'followup_next', label: 'تاریخ پیگیری بعدی', type: 'date' },
|
|
|
|
|
] as Prisma.InputJsonValue,
|
|
|
|
|
},
|
|
|
|
|
select: { id: true, baseType: true },
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async ensureBoard(organizationId: string, firstStageName?: string) {
|
2026-11-17 21:52:57 +03:30
|
|
|
const stageName =
|
|
|
|
|
(firstStageName ?? DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE).trim() ||
|
2026-11-17 21:24:15 +03:30
|
|
|
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
|
|
|
|
|
|
|
|
|
|
let board = await this.prisma.activityBoard.findFirst({
|
|
|
|
|
where: { organizationId, systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS },
|
|
|
|
|
select: { id: true, name: true },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!board) {
|
|
|
|
|
const byName = await this.prisma.activityBoard.findFirst({
|
|
|
|
|
where: { organizationId, name: BOARD_NAME },
|
|
|
|
|
select: { id: true, name: true },
|
|
|
|
|
});
|
|
|
|
|
if (byName) {
|
|
|
|
|
board = await this.prisma.activityBoard.update({
|
|
|
|
|
where: { id: byName.id },
|
|
|
|
|
data: { systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS },
|
|
|
|
|
select: { id: true, name: true },
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!board) {
|
|
|
|
|
const max = await this.prisma.activityBoard.aggregate({
|
|
|
|
|
where: { organizationId },
|
|
|
|
|
_max: { position: true },
|
|
|
|
|
});
|
|
|
|
|
board = await this.prisma.activityBoard.create({
|
|
|
|
|
data: {
|
|
|
|
|
organizationId,
|
|
|
|
|
name: BOARD_NAME,
|
|
|
|
|
systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
|
|
|
|
|
position: (max._max.position ?? 0) + 1,
|
|
|
|
|
isDefault: false,
|
|
|
|
|
},
|
|
|
|
|
select: { id: true, name: true },
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await this.ensureStages(organizationId, board.id, stageName);
|
|
|
|
|
return board;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async ensureStages(organizationId: string, boardId: string, firstStageName: string) {
|
|
|
|
|
const stages = await this.prisma.activityStage.findMany({
|
|
|
|
|
where: { boardId },
|
|
|
|
|
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
|
|
|
|
|
select: { id: true, name: true, kind: true, position: true },
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!stages.length) {
|
|
|
|
|
await this.prisma.activityStage.createMany({
|
|
|
|
|
data: [
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
boardId,
|
|
|
|
|
name: firstStageName,
|
|
|
|
|
color: 'orange',
|
|
|
|
|
kind: 'open',
|
|
|
|
|
position: 0,
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
boardId,
|
|
|
|
|
name: 'در حال انجام',
|
|
|
|
|
color: 'blue',
|
|
|
|
|
kind: 'open',
|
|
|
|
|
position: 1,
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
boardId,
|
|
|
|
|
name: 'انجامشده',
|
|
|
|
|
color: 'green',
|
|
|
|
|
kind: 'done',
|
|
|
|
|
position: 2,
|
|
|
|
|
},
|
|
|
|
|
{
|
|
|
|
|
organizationId,
|
|
|
|
|
boardId,
|
|
|
|
|
name: 'لغو شده',
|
|
|
|
|
color: 'rose',
|
|
|
|
|
kind: 'canceled',
|
|
|
|
|
position: 3,
|
|
|
|
|
},
|
|
|
|
|
],
|
|
|
|
|
skipDuplicates: true,
|
|
|
|
|
});
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const firstOpen = stages.find((s) => s.kind === 'open') ?? stages[0];
|
|
|
|
|
if (firstOpen && firstOpen.name !== firstStageName) {
|
|
|
|
|
const clash = stages.some((s) => s.id !== firstOpen.id && s.name === firstStageName);
|
|
|
|
|
if (!clash) {
|
|
|
|
|
await this.prisma.activityStage.update({
|
|
|
|
|
where: { id: firstOpen.id },
|
|
|
|
|
data: { name: firstStageName },
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async evaluateAll() {
|
|
|
|
|
const orgs = await this.prisma.organization.findMany({
|
|
|
|
|
where: {
|
|
|
|
|
isActive: true,
|
|
|
|
|
enabledModules: { has: 'account_balances' },
|
|
|
|
|
accountingConnections: { some: { provider: 'tahesab', enabled: true } },
|
|
|
|
|
},
|
|
|
|
|
select: { id: true, name: true },
|
|
|
|
|
});
|
|
|
|
|
for (const org of orgs) {
|
|
|
|
|
try {
|
2026-11-18 13:22:38 +03:30
|
|
|
await this.evaluateOrganizationFully(org.id);
|
2026-11-17 21:24:15 +03:30
|
|
|
} catch (err) {
|
|
|
|
|
this.logger.warn(
|
|
|
|
|
`ارزیابی مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 13:22:38 +03:30
|
|
|
/** همهٔ تکهها پشت سر هم (برای جاب زمانبندیشده) */
|
|
|
|
|
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)),
|
|
|
|
|
);
|
|
|
|
|
|
2026-11-17 21:52:57 +03:30
|
|
|
const empty = (message: string): AccountBalanceEvaluateResultDto => ({
|
|
|
|
|
linkedPeople: 0,
|
|
|
|
|
candidates: 0,
|
|
|
|
|
skippedNoAssignee: 0,
|
|
|
|
|
matched: 0,
|
|
|
|
|
created: 0,
|
|
|
|
|
reopened: 0,
|
|
|
|
|
canceled: 0,
|
|
|
|
|
unchanged: 0,
|
|
|
|
|
errors: 0,
|
|
|
|
|
message,
|
2026-11-18 13:22:38 +03:30
|
|
|
offset,
|
|
|
|
|
limit,
|
|
|
|
|
batchProcessed: 0,
|
|
|
|
|
done: true,
|
|
|
|
|
nextOffset: null,
|
2026-11-17 21:52:57 +03:30
|
|
|
});
|
|
|
|
|
|
2026-11-17 21:24:15 +03:30
|
|
|
const org = await this.prisma.organization.findUnique({
|
|
|
|
|
where: { id: organizationId },
|
|
|
|
|
select: { enabledModules: true, accountBalanceSettings: true },
|
|
|
|
|
});
|
2026-11-17 21:52:57 +03:30
|
|
|
if (!org?.enabledModules.includes('account_balances')) {
|
|
|
|
|
return empty('ماژول مانده حساب برای این محیط فعال نیست.');
|
|
|
|
|
}
|
2026-11-17 21:24:15 +03:30
|
|
|
|
|
|
|
|
const settings = parseAccountBalanceSettings(org.accountBalanceSettings);
|
|
|
|
|
const hasAnyRange =
|
|
|
|
|
Boolean(settings.rial) || Object.keys(settings.weights).length > 0;
|
2026-11-17 21:52:57 +03:30
|
|
|
if (!hasAnyRange) {
|
|
|
|
|
return empty('هیچ بازهٔ فعالی ذخیره نشده است. ابتدا محدوده را ذخیره کنید.');
|
|
|
|
|
}
|
2026-11-17 21:24:15 +03:30
|
|
|
|
|
|
|
|
const board = await this.ensureBoard(organizationId, settings.firstStageName);
|
|
|
|
|
const typeDef = await this.ensureFollowUpType(organizationId);
|
|
|
|
|
const stages = await this.prisma.activityStage.findMany({
|
|
|
|
|
where: { boardId: board.id },
|
|
|
|
|
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
|
|
|
|
|
select: { id: true, kind: true },
|
|
|
|
|
});
|
|
|
|
|
const openStageId = stages.find((s) => s.kind === 'open')?.id;
|
|
|
|
|
const canceledStageId = stages.find((s) => s.kind === 'canceled')?.id;
|
2026-11-17 21:52:57 +03:30
|
|
|
if (!openStageId || !canceledStageId) {
|
|
|
|
|
return empty('ستونهای کاریز مطالبات ناقص است.');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const { candidates, linkedPeople, skippedNoAssignee } =
|
|
|
|
|
await this.loadCandidates(organizationId);
|
|
|
|
|
|
2026-11-18 13:22:38 +03:30
|
|
|
const slice = candidates.slice(offset, offset + limit);
|
|
|
|
|
const nextOffset = offset + slice.length;
|
|
|
|
|
const done = nextOffset >= candidates.length;
|
|
|
|
|
|
2026-11-17 21:52:57 +03:30
|
|
|
const result: AccountBalanceEvaluateResultDto = {
|
|
|
|
|
linkedPeople,
|
|
|
|
|
candidates: candidates.length,
|
|
|
|
|
skippedNoAssignee,
|
|
|
|
|
matched: 0,
|
|
|
|
|
created: 0,
|
|
|
|
|
reopened: 0,
|
|
|
|
|
canceled: 0,
|
|
|
|
|
unchanged: 0,
|
|
|
|
|
errors: 0,
|
|
|
|
|
message: '',
|
2026-11-18 13:22:38 +03:30
|
|
|
offset,
|
|
|
|
|
limit,
|
|
|
|
|
batchProcessed: slice.length,
|
|
|
|
|
done,
|
|
|
|
|
nextOffset: done ? null : nextOffset,
|
2026-11-17 21:52:57 +03:30
|
|
|
};
|
2026-11-17 21:24:15 +03:30
|
|
|
|
2026-11-18 13:22:38 +03:30
|
|
|
const actions = await this.mapPool(slice, BATCH_CONCURRENCY, async (person) => {
|
2026-11-17 21:24:15 +03:30
|
|
|
try {
|
2026-11-18 13:22:38 +03:30
|
|
|
return await this.syncPerson({
|
2026-11-17 21:24:15 +03:30
|
|
|
organizationId,
|
|
|
|
|
person,
|
|
|
|
|
settings,
|
|
|
|
|
boardId: board.id,
|
|
|
|
|
openStageId,
|
|
|
|
|
canceledStageId,
|
|
|
|
|
typeDefId: typeDef.id,
|
|
|
|
|
baseType: typeDef.baseType,
|
2026-11-18 13:22:38 +03:30
|
|
|
preferCache: true,
|
2026-11-17 21:24:15 +03:30
|
|
|
});
|
|
|
|
|
} catch (err) {
|
|
|
|
|
this.logger.warn(
|
|
|
|
|
`مانده/مطالبه شخص ${person.personId}: ${err instanceof Error ? err.message : err}`,
|
|
|
|
|
);
|
2026-11-18 13:22:38 +03:30
|
|
|
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;
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
|
|
|
|
}
|
2026-11-17 21:52:57 +03:30
|
|
|
|
2026-11-18 13:22:38 +03:30
|
|
|
result.message = done
|
|
|
|
|
? this.summarize(result)
|
|
|
|
|
: `تکه ${offset + 1} تا ${nextOffset} از ${candidates.length} · ادامه…`;
|
2026-11-17 21:52:57 +03:30
|
|
|
this.logger.log(`مطالبات ${organizationId}: ${result.message}`);
|
|
|
|
|
return result;
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
|
|
|
|
|
2026-11-18 13:22:38 +03:30
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 21:52:57 +03:30
|
|
|
private summarize(r: AccountBalanceEvaluateResultDto): string {
|
|
|
|
|
if (r.linkedPeople === 0) {
|
|
|
|
|
return 'هیچ مشتری لینکشده به تهحساب پیدا نشد.';
|
|
|
|
|
}
|
|
|
|
|
if (r.candidates === 0) {
|
|
|
|
|
return `از ${r.linkedPeople} مشتری لینکشده، هیچکدام گروه با مسئول ندارند (${r.skippedNoAssignee} بدون مسئول گروه).`;
|
|
|
|
|
}
|
|
|
|
|
if (r.matched === 0 && r.canceled === 0 && r.errors === 0) {
|
|
|
|
|
return `بررسی شد: ${r.candidates} نفر واجد شرایط گروه/مسئول؛ هیچکدام داخل بازهٔ ذخیرهشده نبودند.`;
|
|
|
|
|
}
|
|
|
|
|
const parts = [
|
|
|
|
|
`${r.candidates} واجد شرایط`,
|
|
|
|
|
`${r.matched} داخل بازه`,
|
|
|
|
|
`${r.created} ساخته`,
|
|
|
|
|
`${r.reopened} بازگشایی`,
|
|
|
|
|
`${r.canceled} خارج از بازه`,
|
|
|
|
|
];
|
|
|
|
|
if (r.errors) parts.push(`${r.errors} خطا`);
|
|
|
|
|
if (r.skippedNoAssignee) parts.push(`${r.skippedNoAssignee} بدون مسئول گروه`);
|
|
|
|
|
return parts.join(' · ');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async loadCandidates(organizationId: string): Promise<{
|
|
|
|
|
candidates: PersonClaimContext[];
|
|
|
|
|
linkedPeople: number;
|
|
|
|
|
skippedNoAssignee: number;
|
|
|
|
|
}> {
|
2026-11-17 21:24:15 +03:30
|
|
|
const links = await this.prisma.personAccountingLink.findMany({
|
|
|
|
|
where: {
|
|
|
|
|
connection: { organizationId, provider: 'tahesab', enabled: true },
|
|
|
|
|
person: { organizationId },
|
|
|
|
|
},
|
|
|
|
|
select: {
|
|
|
|
|
personId: true,
|
|
|
|
|
connectionId: true,
|
|
|
|
|
linkedAt: true,
|
|
|
|
|
connection: { select: { isDefault: true } },
|
|
|
|
|
person: {
|
|
|
|
|
select: {
|
|
|
|
|
id: true,
|
|
|
|
|
firstName: true,
|
|
|
|
|
lastName: true,
|
|
|
|
|
groupLinks: {
|
|
|
|
|
select: {
|
|
|
|
|
group: {
|
|
|
|
|
select: {
|
|
|
|
|
name: true,
|
|
|
|
|
position: true,
|
|
|
|
|
assigneeIds: true,
|
|
|
|
|
assignees: { select: { id: true } },
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const out: PersonClaimContext[] = [];
|
|
|
|
|
const seen = new Set<string>();
|
2026-11-17 21:52:57 +03:30
|
|
|
let skippedNoAssignee = 0;
|
2026-11-17 21:24:15 +03:30
|
|
|
const orderedLinks = [...links].sort((a, b) => {
|
|
|
|
|
if (a.personId !== b.personId) return a.personId.localeCompare(b.personId);
|
2026-11-17 21:52:57 +03:30
|
|
|
if (a.connection.isDefault !== b.connection.isDefault) {
|
|
|
|
|
return a.connection.isDefault ? -1 : 1;
|
|
|
|
|
}
|
2026-11-17 21:24:15 +03:30
|
|
|
return a.linkedAt.getTime() - b.linkedAt.getTime();
|
|
|
|
|
});
|
2026-11-17 21:52:57 +03:30
|
|
|
|
2026-11-17 21:24:15 +03:30
|
|
|
for (const link of orderedLinks) {
|
|
|
|
|
if (seen.has(link.personId)) continue;
|
2026-11-17 21:52:57 +03:30
|
|
|
seen.add(link.personId);
|
|
|
|
|
|
2026-11-17 21:24:15 +03:30
|
|
|
const groups = [...link.person.groupLinks]
|
|
|
|
|
.map((g) => g.group)
|
|
|
|
|
.sort((a, b) => a.position - b.position || a.name.localeCompare(b.name, 'fa'));
|
2026-11-17 21:52:57 +03:30
|
|
|
|
2026-11-17 21:24:15 +03:30
|
|
|
let assigneeId: string | null = null;
|
|
|
|
|
for (const group of groups) {
|
2026-11-17 21:52:57 +03:30
|
|
|
const fromRelation = group.assignees.map((a) => a.id);
|
|
|
|
|
const valid = new Set(fromRelation);
|
|
|
|
|
let ordered =
|
2026-11-17 21:24:15 +03:30
|
|
|
group.assigneeIds.length > 0
|
2026-11-17 21:52:57 +03:30
|
|
|
? group.assigneeIds.filter((id) => valid.has(id))
|
|
|
|
|
: [];
|
|
|
|
|
// اگر ترتیب ذخیرهشده با M2M همخوان نبود، همان مسئولان رابطه را بگیر
|
|
|
|
|
if (!ordered.length) ordered = fromRelation;
|
2026-11-17 21:24:15 +03:30
|
|
|
if (ordered.length) {
|
|
|
|
|
assigneeId = ordered[0]!;
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-11-17 21:52:57 +03:30
|
|
|
|
|
|
|
|
if (!assigneeId) {
|
|
|
|
|
skippedNoAssignee += 1;
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-17 21:24:15 +03:30
|
|
|
out.push({
|
|
|
|
|
personId: link.person.id,
|
|
|
|
|
fullName: `${link.person.firstName} ${link.person.lastName}`.trim(),
|
|
|
|
|
connectionId: link.connectionId,
|
|
|
|
|
assigneeId,
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-11-17 21:52:57 +03:30
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
candidates: out,
|
|
|
|
|
linkedPeople: seen.size,
|
|
|
|
|
skippedNoAssignee,
|
|
|
|
|
};
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async syncPerson(input: {
|
|
|
|
|
organizationId: string;
|
|
|
|
|
person: PersonClaimContext;
|
|
|
|
|
settings: AccountBalanceSettingsDto;
|
|
|
|
|
boardId: string;
|
|
|
|
|
openStageId: string;
|
|
|
|
|
canceledStageId: string;
|
|
|
|
|
typeDefId: string;
|
|
|
|
|
baseType: 'call' | 'meeting' | 'task' | 'note';
|
2026-11-18 13:22:38 +03:30
|
|
|
/** در ارزیابی دستهای اول از کش استفاده کن تا تایماوت نشود */
|
|
|
|
|
preferCache?: boolean;
|
2026-11-17 21:52:57 +03:30
|
|
|
}): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> {
|
|
|
|
|
let assets;
|
2026-11-18 13:22:38 +03:30
|
|
|
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,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-11-17 21:52:57 +03:30
|
|
|
}
|
|
|
|
|
|
2026-11-17 21:24:15 +03:30
|
|
|
const matched = this.matchesAnyRange(assets, input.settings);
|
|
|
|
|
|
|
|
|
|
const existing = await this.prisma.activity.findFirst({
|
|
|
|
|
where: {
|
|
|
|
|
organizationId: input.organizationId,
|
|
|
|
|
boardId: input.boardId,
|
|
|
|
|
personId: input.person.personId,
|
|
|
|
|
tags: { has: ACCOUNT_BALANCE_CLAIMS_TAG },
|
|
|
|
|
},
|
|
|
|
|
orderBy: { createdAt: 'desc' },
|
|
|
|
|
select: {
|
|
|
|
|
id: true,
|
|
|
|
|
status: true,
|
2026-11-17 21:52:57 +03:30
|
|
|
stageId: true,
|
2026-11-17 21:24:15 +03:30
|
|
|
assigneeId: true,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (matched) {
|
|
|
|
|
if (existing) {
|
2026-11-17 21:52:57 +03:30
|
|
|
const alreadyOpen =
|
|
|
|
|
existing.status === 'open' && existing.stageId === input.openStageId;
|
2026-11-17 21:24:15 +03:30
|
|
|
await this.prisma.activity.update({
|
|
|
|
|
where: { id: existing.id },
|
|
|
|
|
data: {
|
|
|
|
|
status: 'open',
|
|
|
|
|
stageId: input.openStageId,
|
|
|
|
|
completedAt: null,
|
|
|
|
|
assigneeId: input.person.assigneeId,
|
|
|
|
|
assignees: { set: [{ id: input.person.assigneeId }] },
|
|
|
|
|
title: `مطالبه: ${input.person.fullName}`,
|
|
|
|
|
},
|
|
|
|
|
});
|
2026-11-17 21:52:57 +03:30
|
|
|
return alreadyOpen && existing.assigneeId === input.person.assigneeId
|
|
|
|
|
? 'matched-unchanged'
|
|
|
|
|
: 'reopened';
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
|
|
|
|
await this.prisma.activity.create({
|
|
|
|
|
data: {
|
|
|
|
|
organizationId: input.organizationId,
|
|
|
|
|
boardId: input.boardId,
|
|
|
|
|
stageId: input.openStageId,
|
|
|
|
|
status: 'open',
|
|
|
|
|
title: `مطالبه: ${input.person.fullName}`,
|
|
|
|
|
type: input.baseType,
|
|
|
|
|
typeDefId: input.typeDefId,
|
|
|
|
|
personId: input.person.personId,
|
|
|
|
|
assigneeId: input.person.assigneeId,
|
|
|
|
|
assignees: { connect: [{ id: input.person.assigneeId }] },
|
|
|
|
|
tags: [ACCOUNT_BALANCE_CLAIMS_TAG],
|
|
|
|
|
editPolicy: 'assignees',
|
|
|
|
|
completionMode: 'any',
|
|
|
|
|
completedByIds: [],
|
|
|
|
|
createdById: input.person.assigneeId,
|
|
|
|
|
},
|
|
|
|
|
});
|
2026-11-17 21:52:57 +03:30
|
|
|
return 'created';
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (existing && existing.status !== 'canceled') {
|
|
|
|
|
await this.prisma.activity.update({
|
|
|
|
|
where: { id: existing.id },
|
|
|
|
|
data: {
|
|
|
|
|
status: 'canceled',
|
|
|
|
|
stageId: input.canceledStageId,
|
|
|
|
|
completedAt: new Date(),
|
|
|
|
|
},
|
|
|
|
|
});
|
2026-11-17 21:52:57 +03:30
|
|
|
return 'canceled';
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
2026-11-17 21:52:57 +03:30
|
|
|
return 'out-unchanged';
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private matchesAnyRange(
|
|
|
|
|
assets: {
|
|
|
|
|
rialBalance: number | null;
|
|
|
|
|
goldBalance: number | null;
|
|
|
|
|
mandehFields?: Array<{ key: string; value: string | null }>;
|
|
|
|
|
},
|
|
|
|
|
settings: AccountBalanceSettingsDto,
|
|
|
|
|
): boolean {
|
2026-11-18 15:28:08 +03:30
|
|
|
if (accountBalanceMatchesCriterion(assets.rialBalance, settings.rial)) return true;
|
2026-11-17 21:24:15 +03:30
|
|
|
|
|
|
|
|
const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields);
|
2026-11-18 15:28:08 +03:30
|
|
|
for (const [key, criterion] of Object.entries(settings.weights)) {
|
2026-11-17 21:24:15 +03:30
|
|
|
const value =
|
|
|
|
|
fieldMap[key] ??
|
|
|
|
|
(key === 'MandeyeVazni' ? assets.goldBalance : null) ??
|
|
|
|
|
null;
|
2026-11-18 15:28:08 +03:30
|
|
|
if (accountBalanceMatchesCriterion(value, criterion)) return true;
|
2026-11-17 21:24:15 +03:30
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|