412 lines
13 KiB
TypeScript
412 lines
13 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import {
|
|
ACCOUNT_BALANCE_CLAIMS_TAG,
|
|
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
|
|
accountBalanceInRange,
|
|
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
|
|
parseAccountBalanceSettings,
|
|
parseAccountBalanceWeightFields,
|
|
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 = 'پیگیری';
|
|
|
|
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);
|
|
// اعضای خالی = برای همه باز؛ برای مطالبات حداقل یک عضو ساختگی نمیگذاریم —
|
|
// دسترسی در assertCanAccessBoard با systemKey کنترل میشود.
|
|
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.evaluateOrganization(org.id);
|
|
} catch (err) {
|
|
this.logger.warn(
|
|
`ارزیابی مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
async evaluateOrganization(organizationId: string) {
|
|
const org = await this.prisma.organization.findUnique({
|
|
where: { id: organizationId },
|
|
select: { enabledModules: true, accountBalanceSettings: true },
|
|
});
|
|
if (!org?.enabledModules.includes('account_balances')) return;
|
|
|
|
const settings = parseAccountBalanceSettings(org.accountBalanceSettings);
|
|
const hasAnyRange =
|
|
Boolean(settings.rial) || Object.keys(settings.weights).length > 0;
|
|
if (!hasAnyRange) return;
|
|
|
|
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;
|
|
|
|
const candidates = await this.loadCandidates(organizationId);
|
|
for (const person of candidates) {
|
|
try {
|
|
await this.syncPerson({
|
|
organizationId,
|
|
person,
|
|
settings,
|
|
boardId: board.id,
|
|
openStageId,
|
|
canceledStageId,
|
|
typeDefId: typeDef.id,
|
|
baseType: typeDef.baseType,
|
|
});
|
|
} catch (err) {
|
|
this.logger.warn(
|
|
`مانده/مطالبه شخص ${person.personId}: ${err instanceof Error ? err.message : err}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
private async loadCandidates(organizationId: string): Promise<PersonClaimContext[]> {
|
|
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>();
|
|
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;
|
|
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 validAssigneeIds = new Set(group.assignees.map((a) => a.id));
|
|
const ordered =
|
|
group.assigneeIds.length > 0
|
|
? group.assigneeIds.filter((id) => validAssigneeIds.has(id))
|
|
: group.assignees.map((a) => a.id);
|
|
if (ordered.length) {
|
|
assigneeId = ordered[0]!;
|
|
break;
|
|
}
|
|
}
|
|
if (!assigneeId) continue;
|
|
seen.add(link.personId);
|
|
out.push({
|
|
personId: link.person.id,
|
|
fullName: `${link.person.firstName} ${link.person.lastName}`.trim(),
|
|
connectionId: link.connectionId,
|
|
assigneeId,
|
|
});
|
|
}
|
|
return out;
|
|
}
|
|
|
|
private async syncPerson(input: {
|
|
organizationId: string;
|
|
person: PersonClaimContext;
|
|
settings: AccountBalanceSettingsDto;
|
|
boardId: string;
|
|
openStageId: string;
|
|
canceledStageId: string;
|
|
typeDefId: string;
|
|
baseType: 'call' | 'meeting' | 'task' | 'note';
|
|
}) {
|
|
const assets = await this.balances.getAssets(
|
|
input.organizationId,
|
|
input.person.personId,
|
|
input.person.connectionId,
|
|
);
|
|
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,
|
|
assigneeId: true,
|
|
},
|
|
});
|
|
|
|
if (matched) {
|
|
if (existing) {
|
|
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}`,
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
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,
|
|
},
|
|
});
|
|
return;
|
|
}
|
|
|
|
if (existing && existing.status !== 'canceled') {
|
|
await this.prisma.activity.update({
|
|
where: { id: existing.id },
|
|
data: {
|
|
status: 'canceled',
|
|
stageId: input.canceledStageId,
|
|
completedAt: new Date(),
|
|
},
|
|
});
|
|
}
|
|
}
|
|
|
|
private matchesAnyRange(
|
|
assets: {
|
|
rialBalance: number | null;
|
|
goldBalance: number | null;
|
|
mandehFields?: Array<{ key: string; value: string | null }>;
|
|
},
|
|
settings: AccountBalanceSettingsDto,
|
|
): boolean {
|
|
if (accountBalanceInRange(assets.rialBalance, settings.rial)) return true;
|
|
|
|
const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields);
|
|
for (const [key, range] of Object.entries(settings.weights)) {
|
|
const value =
|
|
fieldMap[key] ??
|
|
(key === 'MandeyeVazni' ? assets.goldBalance : null) ??
|
|
null;
|
|
if (accountBalanceInRange(value, range)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|