Report account-balance evaluate results and fall back to cached balances.
EOF Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -34,8 +34,7 @@ export class AccountBalancesController {
|
||||
/** اجرای دستی همان جاب دورهای برای محیط جاری */
|
||||
@Post('evaluate')
|
||||
@Roles('owner', 'admin')
|
||||
async evaluate(@CurrentUser() user: Actor) {
|
||||
await this.claims.evaluateOrganization(user.organizationId);
|
||||
return { ok: true };
|
||||
evaluate(@CurrentUser() user: Actor) {
|
||||
return this.claims.evaluateOrganization(user.organizationId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
|
||||
parseAccountBalanceSettings,
|
||||
parseAccountBalanceWeightFields,
|
||||
type AccountBalanceEvaluateResultDto,
|
||||
type AccountBalanceSettingsDto,
|
||||
} from '@mento/shared';
|
||||
import { Prisma } from '@prisma/client';
|
||||
@@ -69,7 +70,8 @@ export class BalanceClaimsService {
|
||||
}
|
||||
|
||||
async ensureBoard(organizationId: string, firstStageName?: string) {
|
||||
const stageName = (firstStageName ?? DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE).trim() ||
|
||||
const stageName =
|
||||
(firstStageName ?? DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE).trim() ||
|
||||
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
|
||||
|
||||
let board = await this.prisma.activityBoard.findFirst({
|
||||
@@ -109,8 +111,6 @@ export class BalanceClaimsService {
|
||||
}
|
||||
|
||||
await this.ensureStages(organizationId, board.id, stageName);
|
||||
// اعضای خالی = برای همه باز؛ برای مطالبات حداقل یک عضو ساختگی نمیگذاریم —
|
||||
// دسترسی در assertCanAccessBoard با systemKey کنترل میشود.
|
||||
return board;
|
||||
}
|
||||
|
||||
@@ -194,17 +194,34 @@ export class BalanceClaimsService {
|
||||
}
|
||||
}
|
||||
|
||||
async evaluateOrganization(organizationId: string) {
|
||||
async evaluateOrganization(organizationId: string): Promise<AccountBalanceEvaluateResultDto> {
|
||||
const empty = (message: string): AccountBalanceEvaluateResultDto => ({
|
||||
linkedPeople: 0,
|
||||
candidates: 0,
|
||||
skippedNoAssignee: 0,
|
||||
matched: 0,
|
||||
created: 0,
|
||||
reopened: 0,
|
||||
canceled: 0,
|
||||
unchanged: 0,
|
||||
errors: 0,
|
||||
message,
|
||||
});
|
||||
|
||||
const org = await this.prisma.organization.findUnique({
|
||||
where: { id: organizationId },
|
||||
select: { enabledModules: true, accountBalanceSettings: true },
|
||||
});
|
||||
if (!org?.enabledModules.includes('account_balances')) return;
|
||||
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;
|
||||
if (!hasAnyRange) {
|
||||
return empty('هیچ بازهٔ فعالی ذخیره نشده است. ابتدا محدوده را ذخیره کنید.');
|
||||
}
|
||||
|
||||
const board = await this.ensureBoard(organizationId, settings.firstStageName);
|
||||
const typeDef = await this.ensureFollowUpType(organizationId);
|
||||
@@ -215,12 +232,29 @@ export class BalanceClaimsService {
|
||||
});
|
||||
const openStageId = stages.find((s) => s.kind === 'open')?.id;
|
||||
const canceledStageId = stages.find((s) => s.kind === 'canceled')?.id;
|
||||
if (!openStageId || !canceledStageId) return;
|
||||
if (!openStageId || !canceledStageId) {
|
||||
return empty('ستونهای کاریز مطالبات ناقص است.');
|
||||
}
|
||||
|
||||
const { candidates, linkedPeople, skippedNoAssignee } =
|
||||
await this.loadCandidates(organizationId);
|
||||
|
||||
const result: AccountBalanceEvaluateResultDto = {
|
||||
linkedPeople,
|
||||
candidates: candidates.length,
|
||||
skippedNoAssignee,
|
||||
matched: 0,
|
||||
created: 0,
|
||||
reopened: 0,
|
||||
canceled: 0,
|
||||
unchanged: 0,
|
||||
errors: 0,
|
||||
message: '',
|
||||
};
|
||||
|
||||
const candidates = await this.loadCandidates(organizationId);
|
||||
for (const person of candidates) {
|
||||
try {
|
||||
await this.syncPerson({
|
||||
const action = await this.syncPerson({
|
||||
organizationId,
|
||||
person,
|
||||
settings,
|
||||
@@ -230,15 +264,60 @@ export class BalanceClaimsService {
|
||||
typeDefId: typeDef.id,
|
||||
baseType: typeDef.baseType,
|
||||
});
|
||||
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}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
result.message = this.summarize(result);
|
||||
this.logger.log(`مطالبات ${organizationId}: ${result.message}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async loadCandidates(organizationId: string): Promise<PersonClaimContext[]> {
|
||||
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 },
|
||||
@@ -273,30 +352,44 @@ export class BalanceClaimsService {
|
||||
|
||||
const out: PersonClaimContext[] = [];
|
||||
const seen = new Set<string>();
|
||||
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;
|
||||
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 validAssigneeIds = new Set(group.assignees.map((a) => a.id));
|
||||
const ordered =
|
||||
const fromRelation = group.assignees.map((a) => a.id);
|
||||
const valid = new Set(fromRelation);
|
||||
let ordered =
|
||||
group.assigneeIds.length > 0
|
||||
? group.assigneeIds.filter((id) => validAssigneeIds.has(id))
|
||||
: group.assignees.map((a) => a.id);
|
||||
? group.assigneeIds.filter((id) => valid.has(id))
|
||||
: [];
|
||||
// اگر ترتیب ذخیرهشده با M2M همخوان نبود، همان مسئولان رابطه را بگیر
|
||||
if (!ordered.length) ordered = fromRelation;
|
||||
if (ordered.length) {
|
||||
assigneeId = ordered[0]!;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!assigneeId) continue;
|
||||
seen.add(link.personId);
|
||||
|
||||
if (!assigneeId) {
|
||||
skippedNoAssignee += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
out.push({
|
||||
personId: link.person.id,
|
||||
fullName: `${link.person.firstName} ${link.person.lastName}`.trim(),
|
||||
@@ -304,7 +397,12 @@ export class BalanceClaimsService {
|
||||
assigneeId,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
|
||||
return {
|
||||
candidates: out,
|
||||
linkedPeople: seen.size,
|
||||
skippedNoAssignee,
|
||||
};
|
||||
}
|
||||
|
||||
private async syncPerson(input: {
|
||||
@@ -316,12 +414,23 @@ export class BalanceClaimsService {
|
||||
canceledStageId: string;
|
||||
typeDefId: string;
|
||||
baseType: 'call' | 'meeting' | 'task' | 'note';
|
||||
}) {
|
||||
const assets = await this.balances.getAssets(
|
||||
input.organizationId,
|
||||
input.person.personId,
|
||||
input.person.connectionId,
|
||||
);
|
||||
}): 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,
|
||||
);
|
||||
}
|
||||
|
||||
const matched = this.matchesAnyRange(assets, input.settings);
|
||||
|
||||
const existing = await this.prisma.activity.findFirst({
|
||||
@@ -335,12 +444,15 @@ export class BalanceClaimsService {
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
stageId: true,
|
||||
assigneeId: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (matched) {
|
||||
if (existing) {
|
||||
const alreadyOpen =
|
||||
existing.status === 'open' && existing.stageId === input.openStageId;
|
||||
await this.prisma.activity.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
@@ -352,7 +464,9 @@ export class BalanceClaimsService {
|
||||
title: `مطالبه: ${input.person.fullName}`,
|
||||
},
|
||||
});
|
||||
return;
|
||||
return alreadyOpen && existing.assigneeId === input.person.assigneeId
|
||||
? 'matched-unchanged'
|
||||
: 'reopened';
|
||||
}
|
||||
await this.prisma.activity.create({
|
||||
data: {
|
||||
@@ -373,7 +487,7 @@ export class BalanceClaimsService {
|
||||
createdById: input.person.assigneeId,
|
||||
},
|
||||
});
|
||||
return;
|
||||
return 'created';
|
||||
}
|
||||
|
||||
if (existing && existing.status !== 'canceled') {
|
||||
@@ -385,7 +499,9 @@ export class BalanceClaimsService {
|
||||
completedAt: new Date(),
|
||||
},
|
||||
});
|
||||
return 'canceled';
|
||||
}
|
||||
return 'out-unchanged';
|
||||
}
|
||||
|
||||
private matchesAnyRange(
|
||||
|
||||
@@ -5,12 +5,19 @@ import { api } from '@/lib/api';
|
||||
import {
|
||||
ACCOUNT_BALANCE_WEIGHT_KEYS,
|
||||
ACCOUNT_BALANCE_WEIGHT_LABELS,
|
||||
type AccountBalanceEvaluateResultDto,
|
||||
type AccountBalanceRangeDto,
|
||||
type AccountBalanceSettingsDto,
|
||||
type UpdateAccountBalanceSettingsRequest,
|
||||
} from '@mento/shared';
|
||||
import { UiButton, UiCard, UiField, UiInput, UiPageHeader } from '@/components/ui';
|
||||
|
||||
function toLatinDigits(raw: string) {
|
||||
return String(raw ?? '')
|
||||
.replace(/[۰-۹]/g, (d) => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(d)))
|
||||
.replace(/[٠-٩]/g, (d) => String('٠١٢٣٤٥٦٧٨٩'.indexOf(d)));
|
||||
}
|
||||
|
||||
type RangeDraft = { enabled: boolean; min: string; max: string };
|
||||
|
||||
const loading = ref(false);
|
||||
@@ -46,8 +53,8 @@ function toDraft(range: AccountBalanceRangeDto | null | undefined): RangeDraft {
|
||||
|
||||
function parseDraft(draft: RangeDraft): AccountBalanceRangeDto | null {
|
||||
if (!draft.enabled) return null;
|
||||
const min = Number(String(draft.min).replace(/,/g, ''));
|
||||
const max = Number(String(draft.max).replace(/,/g, ''));
|
||||
const min = Number(toLatinDigits(String(draft.min)).replace(/,/g, '').trim());
|
||||
const max = Number(toLatinDigits(String(draft.max)).replace(/,/g, '').trim());
|
||||
if (!Number.isFinite(min) || !Number.isFinite(max)) {
|
||||
throw new Error('بازه نامعتبر');
|
||||
}
|
||||
@@ -121,11 +128,21 @@ async function runEvaluate() {
|
||||
error.value = '';
|
||||
ok.value = '';
|
||||
try {
|
||||
await api.post('/account-balances/evaluate');
|
||||
ok.value = 'بروزرسانی مطالبات اجرا شد.';
|
||||
const { data } = await api.post<AccountBalanceEvaluateResultDto>('/account-balances/evaluate');
|
||||
ok.value = data.message || 'بروزرسانی مطالبات اجرا شد.';
|
||||
if (data.matched === 0 && data.created === 0) {
|
||||
error.value =
|
||||
data.candidates === 0
|
||||
? 'برای ساخت فعالیت، مشتری باید به تهحساب لینک باشد و حداقل در یک گروه با مسئول باشد.'
|
||||
: 'هیچ مشتریای داخل بازههای فعال نبود. علامت بد/بس (منفی/مثبت) و اعداد بازه را با ماندهٔ پروفایل مشتری مقایسه کنید.';
|
||||
}
|
||||
} catch (e) {
|
||||
error.value = axios.isAxiosError(e)
|
||||
? String(e.response?.data?.message || 'اجرای ارزیابی ناموفق بود.')
|
||||
? String(
|
||||
Array.isArray(e.response?.data?.message)
|
||||
? e.response.data.message.join('، ')
|
||||
: e.response?.data?.message || 'اجرای ارزیابی ناموفق بود.',
|
||||
)
|
||||
: 'اجرای ارزیابی ناموفق بود.';
|
||||
} finally {
|
||||
evaluating.value = false;
|
||||
|
||||
Reference in New Issue
Block a user