import { Injectable, Logger } from '@nestjs/common'; import { ACCOUNT_BALANCE_CLAIMS_TAG, ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE, ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS, accountBalanceMatchesCriterion, DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE, parseAccountBalanceSettings, parseAccountBalanceWeightFields, type AccountBalanceEvaluateResultDto, 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 = 'پیگیری'; /** همزمانی داخل هر تکه برای ماندن زیر تایم‌اوت */ const BATCH_CONCURRENCY = 20; 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) { const stageName = (firstStageName ?? DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE).trim() || 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 { await this.evaluateOrganizationFully(org.id); } catch (err) { this.logger.warn( `ارزیابی مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`, ); } } } /** همهٔ تکه‌ها پشت سر هم (برای جاب زمان‌بندی‌شده) */ async evaluateOrganizationFully(organizationId: string): Promise { 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 { 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, skippedNoAssignee: 0, matched: 0, created: 0, reopened: 0, canceled: 0, unchanged: 0, errors: 0, message, offset, limit, batchProcessed: 0, done: true, nextOffset: null, }); const org = await this.prisma.organization.findUnique({ where: { id: organizationId }, select: { enabledModules: true, accountBalanceSettings: true }, }); if (!org?.enabledModules.includes('account_balances')) { return empty('ماژول مانده حساب برای این محیط فعال نیست.'); } const settings = parseAccountBalanceSettings(org.accountBalanceSettings); const hasAnyRange = Boolean(settings.rial) || Object.keys(settings.weights).length > 0; if (!hasAnyRange) { return empty('هیچ بازهٔ فعالی ذخیره نشده است. ابتدا محدوده را ذخیره کنید.'); } 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; if (!openStageId || !canceledStageId) { return empty('ستون‌های کاریز مطالبات ناقص است.'); } 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, skippedNoAssignee, matched: 0, created: 0, reopened: 0, canceled: 0, unchanged: 0, errors: 0, message: '', offset, limit, batchProcessed: slice.length, done, nextOffset: done ? null : nextOffset, }; const actions = await this.mapPool(slice, BATCH_CONCURRENCY, async (person) => { try { return await this.syncPerson({ organizationId, person, settings, boardId: board.id, openStageId, canceledStageId, typeDefId: typeDef.id, baseType: typeDef.baseType, preferCache: true, }); } catch (err) { 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 = 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( items: T[], concurrency: number, worker: (item: T) => Promise, ): Promise { if (!items.length) return []; const out = new Array(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 'هیچ مشتری لینک‌شده به ته‌حساب پیدا نشد.'; } 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; }> { 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(); let skippedNoAssignee = 0; const orderedLinks = [...links].sort((a, b) => { if (a.personId !== b.personId) return a.personId.localeCompare(b.personId); if (a.connection.isDefault !== b.connection.isDefault) { return a.connection.isDefault ? -1 : 1; } return a.linkedAt.getTime() - b.linkedAt.getTime(); }); for (const link of orderedLinks) { if (seen.has(link.personId)) continue; seen.add(link.personId); const groups = [...link.person.groupLinks] .map((g) => g.group) .sort((a, b) => a.position - b.position || a.name.localeCompare(b.name, 'fa')); let assigneeId: string | null = null; for (const group of groups) { const fromRelation = group.assignees.map((a) => a.id); const valid = new Set(fromRelation); let ordered = group.assigneeIds.length > 0 ? group.assigneeIds.filter((id) => valid.has(id)) : []; // اگر ترتیب ذخیره‌شده با M2M هم‌خوان نبود، همان مسئولان رابطه را بگیر if (!ordered.length) ordered = fromRelation; if (ordered.length) { assigneeId = ordered[0]!; break; } } if (!assigneeId) { skippedNoAssignee += 1; continue; } out.push({ personId: link.person.id, fullName: `${link.person.firstName} ${link.person.lastName}`.trim(), connectionId: link.connectionId, assigneeId, }); } return { candidates: out, linkedPeople: seen.size, skippedNoAssignee, }; } private async syncPerson(input: { organizationId: string; person: PersonClaimContext; settings: AccountBalanceSettingsDto; boardId: string; openStageId: string; canceledStageId: string; typeDefId: string; baseType: 'call' | 'meeting' | 'task' | 'note'; /** در ارزیابی دسته‌ای اول از کش استفاده کن تا تایم‌اوت نشود */ preferCache?: boolean; }): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> { 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, ); } } 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, stageId: true, assigneeId: true, }, }); const title = `مطالبه: ${input.person.fullName}`; if (matched) { if (!existing) { await this.prisma.activity.create({ data: { organizationId: input.organizationId, boardId: input.boardId, stageId: input.openStageId, status: 'open', title, 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, }, }); return 'created'; } // فقط بعد از خروج از بازه (لغو) دوباره از ستون اول بیاید؛ // ستون‌های میانی / انجام‌شده حفظ می‌شوند. if (existing.status === 'canceled') { await this.prisma.activity.update({ where: { id: existing.id }, data: { status: 'open', stageId: input.openStageId, completedAt: null, completedByIds: [], assigneeId: input.person.assigneeId, assignees: { set: [{ id: input.person.assigneeId }] }, title, }, }); return 'reopened'; } // هنوز داخل بازه: ستون و وضعیت (در حال انجام / انجام‌شده) حفظ شود await this.prisma.activity.update({ where: { id: existing.id }, data: { title, ...(existing.assigneeId !== input.person.assigneeId ? { assigneeId: input.person.assigneeId, assignees: { set: [{ id: input.person.assigneeId }] }, } : {}), }, }); return 'matched-unchanged'; } if (existing && existing.status !== 'canceled') { await this.prisma.activity.update({ where: { id: existing.id }, data: { status: 'canceled', stageId: input.canceledStageId, completedAt: new Date(), }, }); return 'canceled'; } return 'out-unchanged'; } private matchesAnyRange( assets: { rialBalance: number | null; goldBalance: number | null; mandehFields?: Array<{ key: string; value: string | null }>; }, settings: AccountBalanceSettingsDto, ): boolean { if (accountBalanceMatchesCriterion(assets.rialBalance, settings.rial)) return true; const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields); for (const [key, criterion] of Object.entries(settings.weights)) { const value = fieldMap[key] ?? (key === 'MandeyeVazni' ? assets.goldBalance : null) ?? null; if (accountBalanceMatchesCriterion(value, criterion)) return true; } return false; } }