merge: bring latest origin/main into dev (design local, logic main)

Keep local template/style for conflicted Vue pages; take main script/API/shared logic.
This commit is contained in:
2026-11-24 12:16:21 +03:30
74 changed files with 8558 additions and 1727 deletions
@@ -0,0 +1,84 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import type {
AccountBalanceRangeDto,
AccountBalanceSettingsDto,
UpdateAccountBalanceSettingsRequest,
} from '@mento/shared';
import {
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
parseAccountBalanceRange,
parseAccountBalanceSettings,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { BalanceClaimsService } from './balance-claims.service';
@Injectable()
export class AccountBalanceSettingsService {
constructor(
private readonly prisma: PrismaService,
private readonly claims: BalanceClaimsService,
) {}
async get(organizationId: string): Promise<AccountBalanceSettingsDto> {
const row = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { accountBalanceSettings: true },
});
return parseAccountBalanceSettings(row?.accountBalanceSettings);
}
async update(
organizationId: string,
dto: UpdateAccountBalanceSettingsRequest,
): Promise<AccountBalanceSettingsDto> {
const current = await this.get(organizationId);
const next: AccountBalanceSettingsDto = {
firstStageName:
dto.firstStageName !== undefined
? this.cleanStageName(dto.firstStageName)
: current.firstStageName,
rial:
dto.rial === undefined
? current.rial
: dto.rial === null
? null
: this.requireRange(dto.rial, 'بازه مالی'),
weights: { ...current.weights },
};
if (dto.weights) {
for (const [key, value] of Object.entries(dto.weights)) {
const cleanKey = key.trim();
if (!cleanKey) continue;
if (value === null) {
delete next.weights[cleanKey];
continue;
}
next.weights[cleanKey] = this.requireRange(value, `بازه ${cleanKey}`);
}
}
await this.prisma.organization.update({
where: { id: organizationId },
data: {
accountBalanceSettings: next as unknown as Prisma.InputJsonValue,
},
});
await this.claims.ensureBoard(organizationId, next.firstStageName);
return next;
}
private cleanStageName(raw: string) {
const name = raw.trim().slice(0, 80);
if (!name) return DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
return name;
}
private requireRange(raw: AccountBalanceRangeDto, label: string): AccountBalanceRangeDto {
const range = parseAccountBalanceRange(raw);
if (!range) throw new BadRequestException(`${label} معتبر نیست.`);
if (range.mode === 'all_debtors') return { mode: 'all_debtors' };
return range;
}
}
@@ -0,0 +1,43 @@
import { Body, Controller, Get, Post, Put, UseGuards } from '@nestjs/common';
import { Roles } from '../auth/roles.decorator';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import type { Actor } from '../common/record-scope';
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 { EvaluateAccountBalancesDto, UpdateAccountBalanceSettingsDto } from './dto';
@Controller('account-balances')
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
@RequireOrgModule('account_balances')
export class AccountBalancesController {
constructor(
private readonly settings: AccountBalanceSettingsService,
private readonly claims: BalanceClaimsService,
) {}
@Get('settings')
@Roles('owner', 'admin')
getSettings(@CurrentUser() user: Actor) {
return this.settings.get(user.organizationId);
}
@Put('settings')
@Roles('owner', 'admin')
updateSettings(@CurrentUser() user: Actor, @Body() dto: UpdateAccountBalanceSettingsDto) {
return this.settings.update(user.organizationId, dto);
}
/** یک تکه از ارزیابی (حداکثر ۲۰۰۰ نفر)؛ کلاینت تکه‌ها را پشت سر هم می‌زند */
@Post('evaluate')
@Roles('owner', 'admin')
evaluate(@CurrentUser() user: Actor, @Body() dto: EvaluateAccountBalancesDto) {
return this.claims.evaluateOrganization(user.organizationId, {
offset: dto.offset,
limit: dto.limit,
});
}
}
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { BillingModule } from '../billing/billing.module';
import { ActivitiesModule } from '../activities/activities.module';
import { TahesabModule } from '../integrations/tahesab/tahesab.module';
import { AccountBalancesController } from './account-balances.controller';
import { AccountBalanceSettingsService } from './account-balance-settings.service';
import { BalanceClaimsScheduler } from './balance-claims.scheduler';
import { BalanceClaimsService } from './balance-claims.service';
@Module({
imports: [AuthModule, BillingModule, ActivitiesModule, TahesabModule],
controllers: [AccountBalancesController],
providers: [AccountBalanceSettingsService, BalanceClaimsService, BalanceClaimsScheduler],
exports: [AccountBalanceSettingsService, BalanceClaimsService],
})
export class AccountBalancesModule {}
@@ -0,0 +1,61 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { BalanceClaimsService } from './balance-claims.service';
import { tehranSyncSlot } from '../integrations/tahesab/customer-sync.scheduler';
@Injectable()
export class BalanceClaimsScheduler {
private readonly logger = new Logger(BalanceClaimsScheduler.name);
private busy = false;
constructor(
private readonly prisma: PrismaService,
private readonly claims: BalanceClaimsService,
) {}
@Cron('0 8,13 * * *', { timeZone: 'Asia/Tehran' })
async tick() {
if (process.env.NODE_ENV === 'test' || this.busy) return;
const { slot } = tehranSyncSlot();
this.busy = true;
try {
const orgs = await this.prisma.organization.findMany({
where: {
isActive: true,
enabledModules: { has: 'account_balances' },
OR: [
{ accountBalanceClaimsLastSlot: null },
{ accountBalanceClaimsLastSlot: { not: slot } },
],
},
select: { id: true, name: true },
});
for (const org of orgs) {
const claimed = await this.prisma.organization.updateMany({
where: {
id: org.id,
OR: [
{ accountBalanceClaimsLastSlot: null },
{ accountBalanceClaimsLastSlot: { not: slot } },
],
},
data: { accountBalanceClaimsLastSlot: slot },
});
if (claimed.count !== 1) continue;
try {
await this.claims.evaluateOrganizationFully(org.id);
this.logger.log(`جاب مطالبات مانده برای «${org.name}» اجرا شد (${slot}).`);
} catch (err) {
this.logger.warn(
`جاب مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
);
}
}
} finally {
this.busy = false;
}
}
}
@@ -0,0 +1,658 @@
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<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,
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<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 'هیچ مشتری لینک‌شده به ته‌حساب پیدا نشد.';
}
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<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;
}
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;
}
}
+59
View File
@@ -0,0 +1,59 @@
import { Type } from 'class-transformer';
import {
IsIn,
IsInt,
IsNumber,
IsObject,
IsOptional,
IsString,
Max,
MaxLength,
Min,
ValidateIf,
ValidateNested,
} from 'class-validator';
export class AccountBalanceRangeBody {
@IsIn(['all_debtors', 'range'])
mode!: 'all_debtors' | 'range';
@ValidateIf((o: AccountBalanceRangeBody) => o.mode === 'range')
@IsNumber()
min?: number;
@ValidateIf((o: AccountBalanceRangeBody) => o.mode === 'range')
@IsNumber()
max?: number;
}
export class UpdateAccountBalanceSettingsDto {
@IsOptional()
@IsString()
@MaxLength(80)
firstStageName?: string;
@IsOptional()
@ValidateIf((_, v) => v !== null)
@ValidateNested()
@Type(() => AccountBalanceRangeBody)
rial?: AccountBalanceRangeBody | null;
@IsOptional()
@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;
}
@@ -400,6 +400,7 @@ export class ActivitiesExcelService {
.join('\n'));
const dueAt = parseJalaliDateTime(row.dueDate, row.dueTime);
const doneAt = parseJalaliDateTime(row.doneDate, row.doneTime);
const createdAt = parseJalaliDateTime(row.createdAt);
const status = parseStatus(row.status);
try {
@@ -452,6 +453,7 @@ export class ActivitiesExcelService {
dealId,
assigneeId,
createdById: creatorId,
...(createdAt ? { createdAt } : {}),
},
select: { id: true },
});
+130 -5
View File
@@ -5,6 +5,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import type {
ActivityAccountBalanceDto,
ActivityDto,
ActivityFieldValues,
ActivityFilter,
@@ -15,6 +16,12 @@ import type {
PaginatedResponse,
UpdateActivityRequest,
} from '@mento/shared';
import {
ACCOUNT_BALANCE_CLAIMS_TAG,
ACCOUNT_BALANCE_WEIGHT_KEYS,
ACCOUNT_BALANCE_WEIGHT_LABELS,
parseAccountBalanceWeightFields,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'node:crypto';
import * as path from 'node:path';
@@ -38,6 +45,7 @@ import { tehranDayKey } from '../routines/routine-dates';
import { buildSearchWhere, ci } from '../common/search';
import { activityPriorWhere } from '../common/prior-archive';
import { leadsDeepWhere } from '../common/data-access';
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
import { ActivityStagesService, type BoardStageContext } from './activity-stages.service';
import {
ActivityTypesService,
@@ -363,10 +371,24 @@ export class ActivitiesService {
]);
const ctx = await this.ctx(organizationId);
const [todayDto, overdueDto, upcomingDto] = await Promise.all([
this.withAccountBalances(
organizationId,
today.map((row) => this.toDto(row, ctx)),
),
this.withAccountBalances(
organizationId,
overdue.map((row) => this.toDto(row, ctx)),
),
this.withAccountBalances(
organizationId,
upcoming.map((row) => this.toDto(row, ctx)),
),
]);
return {
today: today.map((row) => this.toDto(row, ctx)),
overdue: overdue.map((row) => this.toDto(row, ctx)),
upcoming: upcoming.map((row) => this.toDto(row, ctx)),
today: todayDto,
overdue: overdueDto,
upcoming: upcomingDto,
todayCount,
overdueCount,
};
@@ -418,7 +440,10 @@ export class ActivitiesService {
]);
return {
items: rows.map((row) => this.toDto(row, ctx)),
items: await this.withAccountBalances(
organizationId,
rows.map((row) => this.toDto(row, ctx)),
),
total,
page,
limit: take,
@@ -689,7 +714,8 @@ export class ActivitiesService {
orderBy: { fullName: 'asc' },
});
}
return dto;
const [enriched] = await this.withAccountBalances(organizationId, [dto]);
return enriched;
}
async create(
@@ -1635,6 +1661,105 @@ export class ActivitiesService {
}
}
/** فقط فعالیت‌های تگ مطالبات؛ مانده از کش ته‌حساب بدون فراخوانی زنده */
private async withAccountBalances(
organizationId: string,
items: ActivityDto[],
): Promise<ActivityDto[]> {
if (!items.length) return items;
const claimItems = items.filter((item) =>
(item.tags ?? []).includes(ACCOUNT_BALANCE_CLAIMS_TAG),
);
if (!claimItems.length) return items;
const personIds = [
...new Set(
claimItems
.map((item) => item.person?.id)
.filter((id): id is string => Boolean(id)),
),
];
const balanceByPerson = new Map<string, ActivityAccountBalanceDto | null>();
if (personIds.length) {
const links = await this.prisma.personAccountingLink.findMany({
where: {
personId: { in: personIds },
person: { organizationId },
},
include: {
balanceCache: true,
connection: { select: { isDefault: true } },
},
orderBy: [{ linkedAt: 'desc' }],
});
const bestByPerson = new Map<string, (typeof links)[number]>();
for (const link of links) {
const prev = bestByPerson.get(link.personId);
if (!prev) {
bestByPerson.set(link.personId, link);
continue;
}
const prevScore =
(prev.balanceCache ? 2 : 0) + (prev.connection.isDefault ? 1 : 0);
const nextScore =
(link.balanceCache ? 2 : 0) + (link.connection.isDefault ? 1 : 0);
if (nextScore > prevScore) bestByPerson.set(link.personId, link);
}
for (const personId of personIds) {
const link = bestByPerson.get(personId);
balanceByPerson.set(
personId,
link?.balanceCache
? this.cacheToAccountBalance(link.balanceCache)
: null,
);
}
}
return items.map((item) => {
if (!(item.tags ?? []).includes(ACCOUNT_BALANCE_CLAIMS_TAG)) return item;
const personId = item.person?.id;
return {
...item,
accountBalance: personId
? (balanceByPerson.get(personId) ?? null)
: null,
};
});
}
private cacheToAccountBalance(cache: {
rialBalance: number | null;
goldBalance: number | null;
rawResponse: unknown;
fetchedAt: Date;
}): ActivityAccountBalanceDto {
const fields = parseAccountBalanceWeightFields(
extractMandehRaw(cache.rawResponse).fields,
);
const weights = ACCOUNT_BALANCE_WEIGHT_KEYS.map((key) => {
const value =
fields[key] ??
(key === 'MandeyeVazni' ? cache.goldBalance : null) ??
null;
if (value == null || !Number.isFinite(value)) return null;
return {
key,
label: ACCOUNT_BALANCE_WEIGHT_LABELS[key] ?? key,
value,
};
}).filter((row): row is NonNullable<typeof row> => row != null);
return {
rialBalance:
cache.rialBalance != null && Number.isFinite(cache.rialBalance)
? cache.rialBalance
: null,
weights,
fetchedAt: cache.fetchedAt.toISOString(),
};
}
private toDto(row: ActivityRow, ctx?: DtoContext): ActivityDto {
const fields =
row.fields && typeof row.fields === 'object' && !Array.isArray(row.fields)
@@ -10,7 +10,10 @@ import type {
ActivityStageDto,
ActivityStatus,
} from '@mento/shared';
import { ACTIVITY_STAGE_COLORS } from '@mento/shared';
import {
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
ACTIVITY_STAGE_COLORS,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
@@ -39,6 +42,7 @@ type BoardRow = {
name: string;
isDefault: boolean;
position: number;
systemKey: string | null;
members: Array<{ userId: string }>;
};
@@ -49,6 +53,7 @@ function toBoardDto(row: BoardRow): ActivityBoardDto {
isDefault: row.isDefault,
position: row.position,
memberIds: row.members.map((member) => member.userId),
systemKey: row.systemKey,
};
}
@@ -69,6 +74,7 @@ const BOARD_SELECT = {
id: true,
name: true,
isDefault: true,
systemKey: true,
position: true,
members: { select: { userId: true } },
} satisfies Prisma.ActivityBoardSelect;
@@ -142,9 +148,35 @@ export class ActivityStagesService {
});
const boards = rows.map(toBoardDto);
if (!actor || managesAllBoards(actor.role)) return boards;
return boards.filter(
(board) => board.memberIds.length === 0 || board.memberIds.includes(actor.userId),
);
const claimBoardIds = boards
.filter((b) => b.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS)
.map((b) => b.id);
const assignedClaimBoardIds = new Set<string>();
if (claimBoardIds.length) {
const assigned = await this.prisma.activity.findMany({
where: {
organizationId,
boardId: { in: claimBoardIds },
OR: [
{ assigneeId: actor.userId },
{ assignees: { some: { id: actor.userId } } },
],
},
select: { boardId: true },
distinct: ['boardId'],
});
for (const row of assigned) {
if (row.boardId) assignedClaimBoardIds.add(row.boardId);
}
}
return boards.filter((board) => {
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
return assignedClaimBoardIds.has(board.id);
}
return board.memberIds.length === 0 || board.memberIds.includes(actor.userId);
});
}
/** گروه بدون عضو برای همه باز است؛ مالک و مدیر همهٔ گروه‌ها را می‌بینند */
@@ -154,6 +186,25 @@ export class ActivityStagesService {
actor: { userId: string; role: string },
) {
if (managesAllBoards(actor.role)) return;
const board = await this.prisma.activityBoard.findFirst({
where: { id: boardId, organizationId },
select: { systemKey: true },
});
if (!board) throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
const hit = await this.prisma.activity.count({
where: {
organizationId,
boardId,
OR: [
{ assigneeId: actor.userId },
{ assignees: { some: { id: actor.userId } } },
],
},
});
if (hit > 0) return;
throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
}
const members = await this.prisma.activityBoardMember.findMany({
where: { boardId, board: { organizationId } },
select: { userId: true },
@@ -206,7 +257,13 @@ export class ActivityStagesService {
id: string,
dto: { name?: string; memberIds?: string[] },
): Promise<ActivityBoardDto> {
await this.getBoard(organizationId, id);
const board = await this.getBoard(organizationId, id);
if (board.systemKey && dto.name != null) {
throw new BadRequestException('نام این گروه سیستمی قابل تغییر نیست');
}
if (board.systemKey && dto.memberIds !== undefined) {
throw new BadRequestException('اعضای این گروه سیستمی از اینجا قابل تغییر نیست');
}
try {
if (dto.name != null) {
await this.prisma.activityBoard.update({
@@ -255,6 +312,9 @@ export class ActivityStagesService {
if (board.isDefault) {
throw new BadRequestException('گروه پیش‌فرض قابل حذف نیست');
}
if (board.systemKey) {
throw new BadRequestException('گروه سیستمی قابل حذف نیست');
}
await this.prisma.$transaction([
this.prisma.activity.updateMany({
where: { organizationId, boardId: id },
+2
View File
@@ -8,6 +8,7 @@ import { OrganizationsModule } from './organizations/organizations.module';
import { ContactsModule } from './contacts/contacts.module';
import { PipelinesModule } from './pipelines/pipelines.module';
import { ActivitiesModule } from './activities/activities.module';
import { AccountBalancesModule } from './account-balances/account-balances.module';
import { NotesModule } from './notes/notes.module';
import { CustomFieldsModule } from './custom-fields/custom-fields.module';
import { ProductsModule } from './products/products.module';
@@ -67,6 +68,7 @@ import { CustomerGroupsModule } from './customer-groups/customer-groups.module';
PrismaModule,
SmsBillingModule,
CustomerGroupsModule,
AccountBalancesModule,
OutboundSmsModule,
StorageModule,
HealthModule,
@@ -416,7 +416,10 @@ export class AutomationsService {
await this.syncLeadAssigneeFromActivity(ctx, type === 'call' ? assigneeId : null);
}
/** سرنخ تازه‌ای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس را می‌گیرد. */
/**
* سرنخ تازه‌ای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس اتوماسیون را می‌گیرد.
* مالک سازمان به‌عنوان fallback ست نمی‌شود — فقط مسئول صریح فعالیت.
*/
private async syncLeadAssigneeFromActivity(
ctx: AutomationContext,
activityAssigneeId: string | null,
@@ -468,6 +471,7 @@ export class AutomationsService {
ctx: AutomationContext,
ref: StepRef,
): Promise<string | null> {
/** مسئول فعلی رکورد؛ هرگز مالک سازمان را به‌صورت ضمنی اضافه نکن */
const fallback = ctx.assigneeId || ctx.ownerId || null;
const mode = config.assignMode ?? (config.assigneeId ? 'user' : 'owner');
@@ -502,6 +506,7 @@ export class AutomationsService {
return pickRoundRobin(valid, cursor.counter) ?? fallback;
}
// mode === 'owner' → مسئول فعلی رکورد؛ اگر نباشد فعالیت بدون مسئول می‌ماند
return fallback;
}
+16
View File
@@ -100,6 +100,12 @@ export class ListQueryDto {
@IsString()
@MaxLength(2000)
groupId?: string;
/** فیلتر سابقه فعالیت؛ چندتایی با کاما */
@IsOptional()
@IsString()
@MaxLength(400)
activityExperience?: string;
}
class CompanyExtraFieldsDto {
@@ -360,6 +366,11 @@ export class CreatePersonDto {
@MaxLength(120)
referrer?: string;
@IsOptional()
@IsString()
@MaxLength(80)
activityExperience?: string | null;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -486,6 +497,11 @@ export class UpdatePersonDto {
@MaxLength(120)
referrer?: string;
@IsOptional()
@IsString()
@MaxLength(80)
activityExperience?: string | null;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -63,6 +63,7 @@ export class PeopleController {
hasMobile,
disc: query.disc,
groupId: query.groupId,
activityExperience: query.activityExperience,
},
);
}
@@ -81,6 +82,7 @@ export class PeopleController {
hasMobile,
disc: query.disc,
groupId: query.groupId,
activityExperience: query.activityExperience,
});
}
+59
View File
@@ -23,6 +23,8 @@ import {
PERSON_MOODS,
applyPersonGenderTitle,
canViewAllRecords,
extractActivityExperienceFromNotes,
normalizeActivityExperience,
splitPersonHonorific,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
@@ -102,6 +104,7 @@ type PersonRow = {
instagram: string | null;
birthDate: Date | null;
referrer: string | null;
activityExperience: string | null;
addresses: unknown;
notes: string | null;
mood: PersonMood;
@@ -174,6 +177,7 @@ export class PeopleService implements OnModuleInit {
hasMobile?: boolean;
disc?: string;
groupId?: string;
activityExperience?: string;
},
): Prisma.PersonWhereInput {
const sources = [...new Set(splitCsv(opts?.importSource).map(normalizePersonImportSource))];
@@ -181,6 +185,13 @@ export class PeopleService implements OnModuleInit {
(PERSON_MOODS as readonly string[]).includes(m),
);
const groupIds = splitCsv(opts?.groupId);
const experiences = [
...new Set(
splitCsv(opts?.activityExperience)
.map((v) => normalizeActivityExperience(v) ?? v)
.filter(Boolean),
),
];
const search = buildSearchWhere<Prisma.PersonWhereInput>(q, (t) => [
{ firstName: ci(t) },
{ lastName: ci(t) },
@@ -231,6 +242,9 @@ export class PeopleService implements OnModuleInit {
if (sources.length) {
facets.push({ importSource: { in: sources } });
}
if (experiences.length) {
facets.push({ activityExperience: { in: experiences } });
}
if (facets.length === 1) and.push(facets[0]!);
else if (facets.length > 1) and.push({ OR: facets });
return {
@@ -258,6 +272,7 @@ export class PeopleService implements OnModuleInit {
hasMobile?: boolean;
disc?: string;
groupId?: string;
activityExperience?: string;
},
): Promise<PaginatedResponse<PersonDto>> {
const seeDisc = await this.behaviorAccess.canView(actor);
@@ -296,6 +311,7 @@ export class PeopleService implements OnModuleInit {
hasMobile?: boolean;
disc?: string;
groupId?: string;
activityExperience?: string;
},
max = FILTERED_IDS_MAX,
): Promise<FilteredIdsResponse> {
@@ -369,6 +385,38 @@ export class PeopleService implements OnModuleInit {
onModuleInit() {
void this.backfillStoredBirthDates();
void this.backfillActivityExperienceFromNotes();
}
/** سابقه فعالیت قدیمی که فقط در یادداشت بود، روی ستون مشتری می‌نشیند. */
async backfillActivityExperienceFromNotes() {
try {
const rows = await this.prisma.person.findMany({
where: {
activityExperience: null,
notes: { contains: 'سابقه' },
},
select: { id: true, notes: true },
take: 20000,
});
let filled = 0;
for (const row of rows) {
const value = extractActivityExperienceFromNotes(row.notes);
if (!value) continue;
const updated = await this.prisma.person.updateMany({
where: { id: row.id, activityExperience: null },
data: { activityExperience: value },
});
filled += updated.count;
}
if (filled) {
this.logger.log(`سابقه فعالیت ${filled} مشتری از یادداشت پر شد`);
}
} catch (err) {
this.logger.warn(
`پر کردن سابقه فعالیت مشتریان ناموفق بود: ${err instanceof Error ? err.message : err}`,
);
}
}
/** تاریخ تولدی که قبلاً در فیلد اضافی دیدار/اکسل یا پروفایل مونتیفای مانده، روی شخص می‌نشیند. */
@@ -475,6 +523,9 @@ export class PeopleService implements OnModuleInit {
instagram: emptyToNull(dto.instagram),
birthDate: parseBirthDate(dto.birthDate),
referrer: emptyToNull(dto.referrer),
activityExperience:
normalizeActivityExperience(dto.activityExperience) ??
emptyToNull(dto.activityExperience),
addresses: toJsonAddresses(dto.addresses),
notes: emptyToNull(dto.notes),
mood: dto.mood ?? 'newcomer',
@@ -587,6 +638,11 @@ export class PeopleService implements OnModuleInit {
if ('instagram' in dto) data.instagram = emptyToNull(dto.instagram);
if ('birthDate' in dto) data.birthDate = parseBirthDate(dto.birthDate);
if ('referrer' in dto) data.referrer = emptyToNull(dto.referrer);
if ('activityExperience' in dto) {
data.activityExperience =
normalizeActivityExperience(dto.activityExperience) ??
emptyToNull(dto.activityExperience);
}
if ('addresses' in dto) data.addresses = toJsonAddresses(dto.addresses);
if ('notes' in dto) data.notes = emptyToNull(dto.notes);
if (dto.mood !== undefined) data.mood = dto.mood;
@@ -1022,6 +1078,9 @@ export class PeopleService implements OnModuleInit {
instagram: row.instagram,
birthDate: row.birthDate?.toISOString() ?? null,
referrer: row.referrer,
activityExperience:
row.activityExperience ||
extractActivityExperienceFromNotes(row.notes),
addresses: (() => {
const fromCol = asAddresses(row.addresses);
if (fromCol.length) return fromCol;
@@ -51,7 +51,7 @@ export class CustomerGroupsService {
include: {
_count: { select: { people: true, companies: true } },
parent: { select: { name: true } },
assignees: { select: { id: true, fullName: true }, orderBy: { fullName: 'asc' } },
assignees: { select: { id: true, fullName: true } },
},
});
return rows.map((r) => this.toDto(r));
@@ -77,6 +77,7 @@ export class CustomerGroupsService {
name,
color: this.cleanColor(dto.color),
position: (max._max.position ?? -1) + 1,
assigneeIds,
...(assigneeIds.length
? { assignees: { connect: assigneeIds.map((id) => ({ id })) } }
: {}),
@@ -116,7 +117,10 @@ export class CustomerGroupsService {
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
...(parentId !== undefined ? { parentId } : {}),
...(assigneeIds !== undefined
? { assignees: { set: assigneeIds.map((uid) => ({ id: uid })) } }
? {
assigneeIds,
assignees: { set: assigneeIds.map((uid) => ({ id: uid })) },
}
: {}),
},
});
@@ -336,8 +340,15 @@ export class CustomerGroupsService {
parentId: string | null;
parent?: { name: string } | null;
_count: { people: number; companies: number };
assigneeIds: string[];
assignees: Array<{ id: string; fullName: string }>;
}): CustomerGroupDto {
const order = new Map(r.assigneeIds.map((id, index) => [id, index]));
const assignees = [...r.assignees].sort((a, b) => {
const ai = order.get(a.id) ?? Number.MAX_SAFE_INTEGER;
const bi = order.get(b.id) ?? Number.MAX_SAFE_INTEGER;
return ai - bi || a.fullName.localeCompare(b.fullName, 'fa');
});
return {
id: r.id,
name: r.name,
@@ -348,7 +359,8 @@ export class CustomerGroupsService {
companyCount: r._count.companies,
parentId: r.parentId,
parentName: r.parent?.name ?? null,
assignees: r.assignees.map((a) => ({ id: a.id, fullName: a.fullName })),
assigneeIds: assignees.map((a) => a.id),
assignees: assignees.map((a) => ({ id: a.id, fullName: a.fullName })),
};
}
@@ -366,7 +378,8 @@ export class CustomerGroupsService {
if (rows.length !== unique.length) {
throw new BadRequestException('یکی از مسئولان انتخاب‌شده معتبر نیست');
}
return rows.map((r) => r.id);
const found = new Set(rows.map((r) => r.id));
return unique.filter((id) => found.has(id));
}
private async require(organizationId: string, id: string) {
+2
View File
@@ -30,9 +30,11 @@ const MAP_TO = [
'lead.city',
'lead.region',
'lead.trade',
'lead.activityExperience',
'lead.notes',
'lead.source',
'lead.gender',
'person.activityExperience',
'person.gender',
'notes',
'custom',
+51 -12
View File
@@ -13,7 +13,12 @@ import type {
SubmitLeadFormResponse,
UpdateLeadFormRequest,
} from '@mento/shared';
import { isGenderQuestionLabel, parsePersonGenderAnswer } from '@mento/shared';
import {
isActivityExperienceLabel,
isGenderQuestionLabel,
normalizeActivityExperience,
parsePersonGenderAnswer,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { LocalFileStorage } from '../storage/local-file.storage';
@@ -298,14 +303,20 @@ export class LeadFormsService {
mapped.notes = [mapped.notes, utmNote].filter(Boolean).join('\n');
}
const ownerId = await this.nextAssignee(form);
/** فقط از لیست صریح «توزیع نوبتی»؛ بدون fallback به مالک سازمان */
const formAssigneeId = await this.nextAssignee(form);
/** فقط برای createdBy / رویدادها — مسئول لید نمی‌شود */
const actorId =
ownerId ??
formAssigneeId ??
(
await this.prisma.user.findFirst({
where: {
memberships: {
some: { organizationId: form.organizationId, role: 'owner' },
some: {
organizationId: form.organizationId,
role: { in: ['owner', 'admin'] },
isActive: true,
},
},
},
select: { id: true },
@@ -324,7 +335,7 @@ export class LeadFormsService {
let message: string | null = null;
if (form.createLead) {
const result = await this.upsertLead(form, mapped, ownerId ?? actorId, actorId);
const result = await this.upsertLead(form, mapped, formAssigneeId, actorId);
leadId = result.leadId;
status = result.status;
leadCreated = result.created;
@@ -344,12 +355,12 @@ export class LeadFormsService {
personId = await this.upsertPerson(
form.organizationId,
mapped,
ownerId ?? actorId,
formAssigneeId ?? actorId,
);
}
if (form.createDeal) {
await this.createDeal(form, mapped, personId, actorId, ownerId);
await this.createDeal(form, mapped, personId, actorId, formAssigneeId);
} else if (personId && mapped.notes && !form.createLead) {
await this.prisma.person.update({
where: { id: personId },
@@ -394,7 +405,9 @@ export class LeadFormsService {
entityId: personId ?? leadId ?? form.id,
title,
personId,
ownerId: ownerId ?? actorId,
/** فقط مسئول صریح فرم؛ مالک سازمان به‌عنوان fallback ست نمی‌شود */
ownerId: formAssigneeId,
assigneeId: formAssigneeId,
};
await this.automations.runTrigger('lead_submitted', {
...leadCtx,
@@ -402,7 +415,7 @@ export class LeadFormsService {
sourceId: form.id,
sourceType: 'lead_form',
leadId,
syncLeadAssignee: !ownerId && leadCreated && !!leadId,
syncLeadAssignee: !formAssigneeId && leadCreated && !!leadId,
mobile: mapped.mobile ?? mapped.phone ?? null,
formName: form.name,
formValues: values,
@@ -437,7 +450,7 @@ export class LeadFormsService {
private async upsertLead(
form: FormRow,
mapped: MappedValues,
assigneeId: string,
assigneeId: string | null,
actorId: string,
): Promise<{
leadId: string | null;
@@ -561,6 +574,9 @@ export class LeadFormsService {
region: emptyToNull(mapped.region) ?? existingLead.region,
trade: emptyToNull(mapped.trade) ?? existingLead.trade,
source: source ?? existingLead.source,
activityExperience:
emptyToNull(mapped.activityExperience) ??
existingLead.activityExperience,
notes: emptyToNull(mapped.notes) ?? existingLead.notes,
...(mapped.gender ? { gender: mapped.gender } : {}),
assigneeId: existingLead.assigneeId ?? assigneeId,
@@ -587,7 +603,9 @@ export class LeadFormsService {
};
}
const stages = await this.leadStages.list(form.organizationId);
const stages = await this.leadStages.list(form.organizationId, {
withLeadCounts: false,
});
const stageId =
(form.leadStageId && stages.find((s) => s.id === form.leadStageId)?.id) ||
stages.find((s) => !s.isConverted && !s.isLost && !s.isUnqualified)?.id ||
@@ -610,6 +628,7 @@ export class LeadFormsService {
region: emptyToNull(mapped.region),
trade: emptyToNull(mapped.trade),
source,
activityExperience: emptyToNull(mapped.activityExperience),
notes: emptyToNull(mapped.notes),
gender: mapped.gender ?? 'none',
stageId,
@@ -674,6 +693,8 @@ export class LeadFormsService {
phone: phone ?? existing.phone,
position: emptyToNull(mapped.position) ?? existing.position,
notes: emptyToNull(mapped.notes) ?? existing.notes,
activityExperience:
emptyToNull(mapped.activityExperience) ?? existing.activityExperience,
...(mapped.gender ? { gender: mapped.gender } : {}),
ownerId: existing.ownerId ?? ownerId,
},
@@ -691,6 +712,7 @@ export class LeadFormsService {
phone,
position: emptyToNull(mapped.position),
notes: emptyToNull(mapped.notes),
activityExperience: emptyToNull(mapped.activityExperience),
gender: mapped.gender ?? 'none',
ownerId,
},
@@ -954,6 +976,7 @@ type MappedValues = {
city?: string;
region?: string;
trade?: string;
activityExperience?: string;
leadSource?: string;
gender?: 'male' | 'female' | 'none';
};
@@ -985,6 +1008,15 @@ function mapValues(
if (gender) mapped.gender = gender;
continue;
}
if (
field.mapTo === 'lead.activityExperience' ||
field.mapTo === 'person.activityExperience' ||
isActivityExperienceLabel(field.label)
) {
mapped.activityExperience =
normalizeActivityExperience(raw) ?? raw;
continue;
}
switch (field.mapTo) {
case 'person.fullName': {
const parts = raw.split(/\s+/).filter(Boolean);
@@ -1038,6 +1070,11 @@ function mapValues(
case 'lead.trade':
mapped.trade = raw;
break;
case 'lead.activityExperience':
case 'person.activityExperience':
mapped.activityExperience =
normalizeActivityExperience(raw) ?? raw;
break;
case 'lead.notes':
mapped.notes = raw;
break;
@@ -1108,7 +1145,9 @@ function collectExtras(
for (const field of fields) {
if (field.fieldType === 'heading' || field.mapTo !== 'custom') continue;
const raw = (values?.[field.key] ?? '').toString().trim();
if (!raw || (isGenderQuestionLabel(field.label) && parsePersonGenderAnswer(raw))) continue;
if (!raw) continue;
if (isGenderQuestionLabel(field.label) && parsePersonGenderAnswer(raw)) continue;
if (isActivityExperienceLabel(field.label)) continue;
lines.push(`${field.label}: ${raw}`);
}
return lines.join('\n');
+6
View File
@@ -37,6 +37,7 @@ export class CreateLeadDto {
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
@IsOptional() @IsString() trade?: string;
@IsOptional() @IsString() source?: string;
@IsOptional() @IsString() activityExperience?: string | null;
@IsOptional() @IsString() notes?: string;
@IsOptional() @IsNumber() estimatedValue?: number;
@IsOptional() @IsString() stageId?: string;
@@ -60,9 +61,12 @@ export class UpdateLeadDto {
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
@IsOptional() @IsString() trade?: string | null;
@IsOptional() @IsString() source?: string | null;
@IsOptional() @IsString() activityExperience?: string | null;
@IsOptional() @IsString() notes?: string | null;
@IsOptional() @IsNumber() estimatedValue?: number | null;
@IsOptional() @IsString() stageId?: string;
/** الزامی هنگام تغییر ستون؛ در جدول زمانی لید ثبت می‌شود */
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
@IsOptional() @IsString() assigneeId?: string | null;
@IsOptional() @IsString() nextFollowUpAt?: string | null;
@IsOptional() @IsString() lastContactAt?: string | null;
@@ -71,6 +75,7 @@ export class UpdateLeadDto {
export class MoveLeadDto {
@IsString() stageId!: string;
@IsOptional() @IsNumber() position?: number;
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
}
export class AssignLeadsDto {
@@ -81,6 +86,7 @@ export class AssignLeadsDto {
export class BulkLeadStageDto {
@IsArray() @IsString({ each: true }) leadIds!: string[];
@IsString() stageId!: string;
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
}
export class AutoAssignLeadsDto {
+16 -8
View File
@@ -43,18 +43,26 @@ export class LeadStagesService {
});
}
async list(organizationId: string): Promise<LeadStageDto[]> {
async list(
organizationId: string,
opts: { withLeadCounts?: boolean } = {},
): Promise<LeadStageDto[]> {
const withLeadCounts = opts.withLeadCounts !== false;
await this.ensureDefaults(organizationId);
const rows = await this.prisma.leadStage.findMany({
where: { organizationId },
orderBy: { position: 'asc' },
include: {
_count: {
select: {
leads: { where: { archivedAt: null } },
},
},
},
...(withLeadCounts
? {
include: {
_count: {
select: {
leads: { where: { archivedAt: null } },
},
},
},
}
: {}),
});
return rows.map((r) => this.toDto(r));
}
+3 -1
View File
@@ -181,7 +181,9 @@ export class LeadsImportService {
const job = await this.prisma.leadImportJob.findUnique({ where: { id } });
if (!job) return;
const stages = await this.stages.list(job.organizationId);
const stages = await this.stages.list(job.organizationId, {
withLeadCounts: false,
});
const defaultStageId = stages[0]?.id;
if (!defaultStageId) {
await this.prisma.leadImportJob.update({
+13 -4
View File
@@ -70,8 +70,13 @@ export class LeadsController {
}
@Get('stages')
listStages(@CurrentUser() user: Actor) {
return this.stages.list(user.organizationId);
listStages(
@CurrentUser() user: Actor,
@Query('counts') counts?: string,
) {
return this.stages.list(user.organizationId, {
withLeadCounts: counts !== '0' && counts !== 'false',
});
}
@Post('stages')
@@ -244,6 +249,7 @@ export class LeadsController {
@Query('region') region?: string,
@Query('trade') trade?: string,
@Query('source') source?: string,
@Query('activityExperience') activityExperience?: string,
@Query('unassigned') unassigned?: string,
@Query('archived') archived?: string,
@Query('converted') converted?: string,
@@ -260,6 +266,7 @@ export class LeadsController {
region,
trade,
source,
activityExperience,
unassigned: unassigned === '1' || unassigned === 'true',
archived: archived === '1' || archived === 'true',
converted: converted === '1' || converted === 'true',
@@ -282,6 +289,7 @@ export class LeadsController {
@Query('region') region?: string,
@Query('trade') trade?: string,
@Query('source') source?: string,
@Query('activityExperience') activityExperience?: string,
@Query('unassigned') unassigned?: string,
@Query('archived') archived?: string,
@Query('converted') converted?: string,
@@ -301,6 +309,7 @@ export class LeadsController {
region,
trade,
source,
activityExperience,
unassigned: unassigned === '1' || unassigned === 'true',
archived: archived === '1' || archived === 'true',
converted: converted === '1' || converted === 'true',
@@ -329,7 +338,7 @@ export class LeadsController {
@Roles('owner', 'admin')
bulkStage(@CurrentUser() user: Actor, @Body() dto: BulkLeadStageDto) {
return this.leads
.bulkStage(user, dto.leadIds, dto.stageId)
.bulkStage(user, dto.leadIds, dto.stageId, dto.reason)
.then((count) => ({ count }));
}
@@ -393,7 +402,7 @@ export class LeadsController {
@Param('id') id: string,
@Body() dto: MoveLeadDto,
) {
return this.leads.move(user, id, dto.stageId, dto.position);
return this.leads.move(user, id, dto.stageId, dto.position, dto.reason);
}
@Get(':id/sms-history')
+296 -34
View File
@@ -2,8 +2,10 @@ import {
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
ServiceUnavailableException,
type OnModuleInit,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { parseBirthDate } from '../common/excel';
@@ -20,7 +22,12 @@ import type {
PaginatedResponse,
} from '@mento/shared';
import { FILTERED_IDS_MAX } from '@mento/shared';
import { applyLeadGenderName, applyPersonGenderTitle } from '@mento/shared';
import {
applyLeadGenderName,
applyPersonGenderTitle,
extractActivityExperienceFromNotes,
normalizeActivityExperience,
} from '@mento/shared';
import { PrismaService } from '../prisma/prisma.service';
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
import { renderSmsText } from '../common/sms-text';
@@ -104,10 +111,44 @@ const leadInclude = {
assignee: { select: { id: true, fullName: true } },
} as const;
/** فیلدهای لازم برای کارت مسیر لیدها — بدون notes/addresses حجیم و بدون join مرحله */
const boardLeadSelect = {
id: true,
title: true,
contactName: true,
gender: true,
showGenderInName: true,
mobile: true,
phone: true,
city: true,
region: true,
instagram: true,
birthDate: true,
trade: true,
source: true,
activityExperience: true,
logoStorageKey: true,
estimatedValue: true,
stageId: true,
position: true,
assigneeId: true,
lastContactAt: true,
nextFollowUpAt: true,
convertedPersonId: true,
convertedAt: true,
archivedAt: true,
createdAt: true,
updatedAt: true,
assignee: { select: { id: true, fullName: true } },
} as const;
type LeadRow = Prisma.LeadGetPayload<{ include: typeof leadInclude }>;
type BoardLeadRow = Prisma.LeadGetPayload<{ select: typeof boardLeadSelect }>;
@Injectable()
export class LeadsService {
export class LeadsService implements OnModuleInit {
private readonly logger = new Logger(LeadsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly stages: LeadStagesService,
@@ -118,6 +159,41 @@ export class LeadsService {
private readonly outboundSms: OutboundSmsLogService,
) {}
onModuleInit() {
void this.backfillActivityExperienceFromNotes();
}
/** سابقه فعالیت قدیمی که فقط در یادداشت فرم بود، روی ستون لید می‌نشیند. */
async backfillActivityExperienceFromNotes() {
try {
const rows = await this.prisma.lead.findMany({
where: {
activityExperience: null,
notes: { contains: 'سابقه' },
},
select: { id: true, notes: true },
take: 20000,
});
let filled = 0;
for (const row of rows) {
const value = extractActivityExperienceFromNotes(row.notes);
if (!value) continue;
const updated = await this.prisma.lead.updateMany({
where: { id: row.id, activityExperience: null },
data: { activityExperience: value },
});
filled += updated.count;
}
if (filled) {
this.logger.log(`سابقه فعالیت ${filled} لید از یادداشت فرم پر شد`);
}
} catch (err) {
this.logger.warn(
`پر کردن سابقه فعالیت لیدها ناموفق بود: ${err instanceof Error ? err.message : err}`,
);
}
}
private gameEvent(
actor: Actor,
event: Parameters<GamificationService['emit']>[0]['event'],
@@ -146,6 +222,7 @@ export class LeadsService {
region?: string;
trade?: string;
source?: string;
activityExperience?: string;
unassigned?: boolean;
archived?: boolean;
converted?: boolean;
@@ -165,6 +242,7 @@ export class LeadsService {
{ trade: ci(t) },
{ instagram: ci(t) },
{ source: ci(t) },
{ activityExperience: ci(t) },
]);
const and: Prisma.LeadWhereInput[] = [];
if (search) and.push(search);
@@ -191,6 +269,13 @@ export class LeadsService {
...(opts.source
? { source: { contains: opts.source, mode: 'insensitive' } }
: {}),
...(opts.activityExperience
? {
activityExperience:
normalizeActivityExperience(opts.activityExperience) ??
opts.activityExperience,
}
: {}),
},
...(opts.unassigned ? [{ assigneeId: null }] : []),
...(opts.assigneeId && !opts.unassigned ? [{ assigneeId: opts.assigneeId }] : []),
@@ -257,6 +342,7 @@ export class LeadsService {
region?: string;
trade?: string;
source?: string;
activityExperience?: string;
unassigned?: boolean;
archived?: boolean;
converted?: boolean;
@@ -310,6 +396,7 @@ export class LeadsService {
region?: string;
trade?: string;
source?: string;
activityExperience?: string;
unassigned?: boolean;
archived?: boolean;
converted?: boolean;
@@ -338,33 +425,56 @@ export class LeadsService {
}
async board(actor: Actor): Promise<LeadBoardColumnDto[]> {
const stages = await this.stages.list(actor.organizationId);
// بدون شمارش لید روی هر مرحله — شمارش را یک‌بار با groupBy می‌گیریم
const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const boardStages = stages.filter((s) => s.showOnBoard);
const whereBase = {
if (!boardStages.length) return [];
const access = leadAccessWhere(actor);
const stageIds = boardStages.map((s) => s.id);
const whereBase: Prisma.LeadWhereInput = {
organizationId: actor.organizationId,
...leadAccessWhere(actor),
...access,
archivedAt: null,
stageId: { in: stageIds },
};
const perColumn = 120;
return Promise.all(
boardStages.map(async (stage) => {
const where = { ...whereBase, stageId: stage.id };
const [total, rows] = await Promise.all([
this.prisma.lead.count({ where }),
this.prisma.lead.findMany({
where,
include: leadInclude,
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
take: perColumn,
}),
]);
return {
stage,
total,
leads: rows.map((row) => this.toDto(row)),
};
const [counts, ...columnRows] = await Promise.all([
this.prisma.lead.groupBy({
by: ['stageId'],
where: whereBase,
_count: { _all: true },
}),
...boardStages.map((stage) =>
this.prisma.lead.findMany({
where: {
organizationId: actor.organizationId,
...access,
archivedAt: null,
stageId: stage.id,
},
// کارت بورد به join مرحله نیاز ندارد؛ اسم مرحله را از ستون می‌گذاریم
select: boardLeadSelect,
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
take: perColumn,
}),
),
]);
const totalByStage = new Map(
counts.map((row) => [row.stageId, row._count._all]),
);
return boardStages.map((stage, index) => ({
stage,
total: totalByStage.get(stage.id) ?? 0,
leads: (columnRows[index] ?? []).map((row) =>
this.toBoardDto(row, stage.name),
),
}));
}
async get(actor: Actor, id: string): Promise<LeadDto & { events: LeadEventDto[] }> {
@@ -438,6 +548,7 @@ export class LeadsService {
addresses?: string[];
trade?: string | null;
source?: string | null;
activityExperience?: string | null;
notes?: string | null;
estimatedValue?: number | null;
stageId?: string;
@@ -459,7 +570,9 @@ export class LeadsService {
);
}
const stages = await this.stages.list(actor.organizationId);
const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const stageId = dto.stageId || stages[0]?.id;
if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده');
@@ -497,6 +610,9 @@ export class LeadsService {
addresses: toJsonAddresses(dto.addresses),
trade: emptyToNull(dto.trade),
source: emptyToNull(dto.source),
activityExperience:
normalizeActivityExperience(dto.activityExperience) ??
emptyToNull(dto.activityExperience),
notes: emptyToNull(dto.notes),
estimatedValue:
dto.estimatedValue != null
@@ -515,7 +631,10 @@ export class LeadsService {
include: leadInclude,
});
await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null);
await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null, {
stageId: row.stageId,
stageName: row.stage.name,
});
if (assigneeId) {
await this.addEvent(
actor,
@@ -625,6 +744,13 @@ export class LeadsService {
...(dto.source !== undefined
? { source: emptyToNull(dto.source as string) }
: {}),
...(dto.activityExperience !== undefined
? {
activityExperience:
normalizeActivityExperience(dto.activityExperience as string | null) ??
emptyToNull(dto.activityExperience as string),
}
: {}),
...(dto.notes !== undefined
? { notes: emptyToNull(dto.notes as string) }
: {}),
@@ -670,11 +796,22 @@ export class LeadsService {
});
if (typeof dto.stageId === 'string' && dto.stageId !== existing.stageId) {
const reason = this.requireStageReason(
typeof dto.reason === 'string' ? dto.reason : null,
);
await this.addEvent(
actor,
id,
'stage_changed',
`وضعیت به «${row.stage.name}» تغییر کرد`,
reason,
{
fromStageId: existing.stageId,
fromStageName: existing.stage?.name ?? null,
toStageId: row.stageId,
toStageName: row.stage.name,
reason,
},
);
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
eventKey: `${id}:${row.stageId}`,
@@ -689,6 +826,7 @@ export class LeadsService {
id: string,
stageId: string,
position?: number,
reasonRaw?: string | null,
): Promise<LeadDto> {
const before = await this.findAccessible(actor, id);
const stage = await this.prisma.leadStage.findFirst({
@@ -696,6 +834,9 @@ export class LeadsService {
});
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
const stageChanged = before.stageId !== stageId;
const reason = stageChanged ? this.requireStageReason(reasonRaw) : null;
let placedIds: string[] | null = null;
let nextPosition = position ?? 0;
if (position != null) {
@@ -726,12 +867,20 @@ export class LeadsService {
this.prisma.lead.update({ where: { id: leadId }, data: { position: leadPosition } }),
);
}
if (before.stageId !== stageId) {
if (stageChanged && reason) {
await this.addEvent(
actor,
id,
'stage_changed',
`به مرحله «${stage.name}» منتقل شد`,
reason,
{
fromStageId: before.stageId,
fromStageName: before.stage?.name ?? null,
toStageId: stageId,
toStageName: stage.name,
reason,
},
);
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
eventKey: `${id}:${stageId}`,
@@ -782,7 +931,9 @@ export class LeadsService {
actor: Actor,
leadIds: string[],
stageId: string,
reasonRaw?: string | null,
): Promise<number> {
const reason = this.requireStageReason(reasonRaw);
if (!elevated(actor.role)) {
throw new BadRequestException('فقط مدیر می‌تواند وضعیت گروهی تغییر دهد');
}
@@ -790,6 +941,18 @@ export class LeadsService {
where: { id: stageId, organizationId: actor.organizationId },
});
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
const beforeRows = await this.prisma.lead.findMany({
where: {
organizationId: actor.organizationId,
id: { in: leadIds },
archivedAt: null,
},
select: {
id: true,
stageId: true,
stage: { select: { name: true } },
},
});
const result = await this.prisma.lead.updateMany({
where: {
organizationId: actor.organizationId,
@@ -798,12 +961,21 @@ export class LeadsService {
},
data: { stageId },
});
for (const leadId of leadIds) {
for (const lead of beforeRows) {
if (lead.stageId === stageId) continue;
await this.addEvent(
actor,
leadId,
lead.id,
'stage_changed',
`وضعیت گروهی به «${stage.name}»`,
reason,
{
fromStageId: lead.stageId,
fromStageName: lead.stage.name,
toStageId: stageId,
toStageName: stage.name,
reason,
},
);
}
return result.count;
@@ -1089,6 +1261,7 @@ export class LeadsService {
]
.filter(Boolean)
.join('\n'),
activityExperience: lead.activityExperience,
ownerId: lead.assigneeId ?? actor.userId,
createdAt: lead.createdAt,
importSource: 'lead_form',
@@ -1096,11 +1269,23 @@ export class LeadsService {
},
});
createdPerson = true;
} else if (!person.birthDate && lead.birthDate) {
await this.prisma.person.update({
where: { id: person.id },
data: { birthDate: lead.birthDate },
});
} else {
const personPatch: {
birthDate?: Date | null;
activityExperience?: string | null;
} = {};
if (!person.birthDate && lead.birthDate) {
personPatch.birthDate = lead.birthDate;
}
if (!person.activityExperience && lead.activityExperience) {
personPatch.activityExperience = lead.activityExperience;
}
if (Object.keys(personPatch).length) {
await this.prisma.person.update({
where: { id: person.id },
data: personPatch,
});
}
}
const convertedStage = await this.prisma.leadStage.findFirst({
@@ -1118,6 +1303,22 @@ export class LeadsService {
include: leadInclude,
});
if (convertedStage && convertedStage.id !== lead.stageId) {
await this.addEvent(
actor,
id,
'stage_changed',
`وضعیت به «${convertedStage.name}» تغییر کرد`,
null,
{
fromStageId: lead.stageId,
fromStageName: lead.stage?.name ?? null,
toStageId: convertedStage.id,
toStageName: convertedStage.name,
},
);
}
await this.addEvent(
actor,
id,
@@ -1167,7 +1368,9 @@ export class LeadsService {
...leadAccessWhere(actor),
archivedAt: null,
};
const stages = await this.stages.list(actor.organizationId);
const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
const lostIds = stages.filter((s) => s.isLost).map((s) => s.id);
// همان مقصد فرم و ورود از اکسل: اولین ستون باز، مستقل از اسم «جدید»
@@ -1309,7 +1512,9 @@ export class LeadsService {
}
await this.stages.ensureDefaults(input.organizationId);
const stages = await this.stages.list(input.organizationId);
const stages = await this.stages.list(input.organizationId, {
withLeadCounts: false,
});
const stageId = stages[0]?.id;
if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده');
@@ -1447,6 +1652,17 @@ export class LeadsService {
return row;
}
private requireStageReason(raw: string | null | undefined): string {
const reason = String(raw ?? '').trim();
if (!reason) {
throw new BadRequestException('دلیل تغییر ستون الزامی است.');
}
if (reason.length > 1000) {
throw new BadRequestException('دلیل تغییر ستون نباید بیش از ۱۰۰۰ کاراکتر باشد.');
}
return reason;
}
private async addEvent(
actor: Actor,
leadId: string,
@@ -1490,6 +1706,9 @@ export class LeadsService {
addresses: asAddresses(row.addresses),
trade: row.trade,
source: row.source,
activityExperience:
row.activityExperience ||
extractActivityExperienceFromNotes(row.notes),
notes: row.notes,
estimatedValue:
row.estimatedValue != null ? Number(row.estimatedValue) : null,
@@ -1510,6 +1729,49 @@ export class LeadsService {
};
}
private toBoardDto(row: BoardLeadRow, stageName: string): LeadDto {
const daysInStage = Math.max(
0,
Math.floor(
(Date.now() - row.updatedAt.getTime()) / (24 * 60 * 60 * 1000),
),
);
return {
id: row.id,
title: row.title,
contactName: row.contactName,
gender: row.gender === 'male' || row.gender === 'female' ? row.gender : 'none',
showGenderInName: row.showGenderInName,
mobile: row.mobile,
phone: row.phone,
city: row.city,
region: row.region,
instagram: row.instagram,
birthDate: row.birthDate?.toISOString() ?? null,
addresses: [],
trade: row.trade,
source: row.source,
activityExperience: row.activityExperience,
notes: null,
estimatedValue:
row.estimatedValue != null ? Number(row.estimatedValue) : null,
stageId: row.stageId,
stageName,
position: row.position,
assigneeId: row.assigneeId,
assigneeName: row.assignee?.fullName ?? null,
lastContactAt: row.lastContactAt?.toISOString() ?? null,
nextFollowUpAt: row.nextFollowUpAt?.toISOString() ?? null,
convertedPersonId: row.convertedPersonId,
convertedAt: row.convertedAt?.toISOString() ?? null,
archivedAt: row.archivedAt?.toISOString() ?? null,
daysInStage,
hasLogo: Boolean(row.logoStorageKey),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
async saveLogo(
actor: Actor,
id: string,
@@ -0,0 +1,99 @@
/** بازهٔ ماندن یک لید در یک مرحله */
export type LeadStageStay = {
stageId: string;
fromMs: number;
toMs: number;
};
type StageChangeMeta = {
fromStageId?: string | null;
toStageId?: string | null;
};
function asMeta(raw: unknown): StageChangeMeta {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
const obj = raw as Record<string, unknown>;
return {
fromStageId:
typeof obj.fromStageId === 'string' ? obj.fromStageId : null,
toStageId: typeof obj.toStageId === 'string' ? obj.toStageId : null,
};
}
/**
* از رویدادهای لید، بازه‌های ماندن در هر مرحله را می‌سازد.
* برای دادهٔ قدیمی بدون meta، فقط toStage از meta یا ترتیب رویدادها استفاده می‌شود.
*/
export function buildLeadStageStays(input: {
leadId: string;
currentStageId: string;
createdAt: Date;
convertedAt: Date | null;
archivedAt: Date | null;
events: Array<{ type: string; createdAt: Date; meta: unknown }>;
nowMs?: number;
}): LeadStageStay[] {
const nowMs = input.nowMs ?? Date.now();
const endCap = Math.min(
nowMs,
input.convertedAt?.getTime() ?? Number.POSITIVE_INFINITY,
input.archivedAt?.getTime() ?? Number.POSITIVE_INFINITY,
);
type Point = { at: number; stageId: string | null };
const points: Point[] = [{ at: input.createdAt.getTime(), stageId: null }];
const timeline = [...input.events].sort(
(a, b) => a.createdAt.getTime() - b.createdAt.getTime(),
);
for (const ev of timeline) {
if (ev.type === 'created') {
const meta = asMeta(ev.meta);
const rawStage =
meta.toStageId ||
(ev.meta &&
typeof ev.meta === 'object' &&
!Array.isArray(ev.meta) &&
typeof (ev.meta as { stageId?: unknown }).stageId === 'string'
? String((ev.meta as { stageId: string }).stageId)
: null);
if (rawStage) {
points[0] = { at: ev.createdAt.getTime(), stageId: rawStage };
}
continue;
}
if (ev.type !== 'stage_changed') continue;
const meta = asMeta(ev.meta);
const toStageId = meta.toStageId;
if (!toStageId) continue;
points.push({ at: ev.createdAt.getTime(), stageId: toStageId });
}
// اگر نقطهٔ اول stage نداشت، از اولین stage_changed یا مرحلهٔ فعلی استفاده کن
if (!points[0]?.stageId) {
const firstKnown = points.find((p) => p.stageId);
points[0]!.stageId = firstKnown?.stageId ?? input.currentStageId;
}
// آخرین مرحله تا endCap ادامه دارد
const last = points[points.length - 1]!;
if (last.stageId !== input.currentStageId && !input.convertedAt && !input.archivedAt) {
// مرحلهٔ فعلی ممکن است بدون رویداد باشد (دادهٔ قدیمی)
points.push({ at: endCap, stageId: input.currentStageId });
}
const stays: LeadStageStay[] = [];
for (let i = 0; i < points.length; i++) {
const cur = points[i]!;
if (!cur.stageId) continue;
const nextAt = points[i + 1]?.at ?? endCap;
const toMs = Math.min(nextAt, endCap);
if (toMs <= cur.at) continue;
stays.push({ stageId: cur.stageId, fromMs: cur.at, toMs });
}
return stays;
}
export function hoursBetween(fromMs: number, toMs: number): number {
return Math.max(0, (toMs - fromMs) / (1000 * 60 * 60));
}
@@ -97,6 +97,15 @@ export class ReportsController {
});
}
/** قیف لید، تبدیل بین‌مرحله‌ای و میانگین ماندن در ستون‌ها */
@Get('leads')
leads(@CurrentUser() user: Actor, @Query() query: ReportsQueryDto) {
return this.reportsService.leadsAnalytics(user, {
from: query.from,
to: query.to,
});
}
/** داشبورد صفحهٔ خانه برای همه باز است */
@Get('home')
@RequirePermission('reports', { reads: false })
+444 -15
View File
@@ -10,19 +10,22 @@ import type {
ReportsDrillKind,
ReportsDrilldownDto,
ReportsFunnelStageDto,
ReportsLeadsAnalyticsDto,
ReportsPeriodCompareRowDto,
} from '@mento/shared';
import {
isReportsLeadBuilderMetric,
REPORTS_BUILDER_DIMENSION_LABELS,
REPORTS_BUILDER_METRIC_LABELS,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { customersPersonWhere } from '../common/data-access';
import { customersPersonWhere, leadsDeepWhere } from '../common/data-access';
import {
type Actor,
assigneeWhere,
elevated,
forScope,
ownerWhere,
ticketAccessWhere,
} from '../common/record-scope';
@@ -38,6 +41,10 @@ import {
jalaliMonthName,
startOfJalaliMonth,
} from '../common/jalali';
import {
buildLeadStageStays,
hoursBetween,
} from './leads-analytics.util';
const DRILL_LIMIT = 50;
@@ -1205,6 +1212,230 @@ export class ReportsService {
};
}
async leadsAnalytics(
actor: Actor,
opts: { from?: string; to?: string },
): Promise<ReportsLeadsAnalyticsDto> {
const { start, end } = resolveRange(opts.from, opts.to);
const orgId = actor.organizationId;
const access = this.leadAccessWhere(actor);
const stages = await this.prisma.leadStage.findMany({
where: { organizationId: orgId },
orderBy: { position: 'asc' },
select: {
id: true,
name: true,
position: true,
isConverted: true,
isLost: true,
isUnqualified: true,
},
});
const stageName = new Map(stages.map((s) => [s.id, s.name]));
const lostIds = new Set(
stages.filter((s) => s.isLost || s.isUnqualified).map((s) => s.id),
);
const convertedIds = new Set(
stages.filter((s) => s.isConverted).map((s) => s.id),
);
const [created, converted, lost, activeLeads, stageEvents] =
await Promise.all([
this.prisma.lead.count({
where: {
organizationId: orgId,
...access,
createdAt: { gte: start, lte: end },
},
}),
this.prisma.lead.count({
where: {
organizationId: orgId,
...access,
convertedAt: { gte: start, lte: end },
},
}),
this.prisma.lead.count({
where: {
organizationId: orgId,
...access,
archivedAt: null,
stageId: { in: [...lostIds] },
updatedAt: { gte: start, lte: end },
},
}),
this.prisma.lead.findMany({
where: {
organizationId: orgId,
...access,
archivedAt: null,
convertedAt: null,
stageId: { notIn: [...lostIds, ...convertedIds] },
},
select: { id: true, stageId: true },
}),
this.prisma.leadEvent.findMany({
where: {
organizationId: orgId,
type: { in: ['created', 'stage_changed'] },
createdAt: { gte: start, lte: end },
lead: { ...access },
},
select: {
leadId: true,
type: true,
createdAt: true,
meta: true,
},
orderBy: { createdAt: 'asc' },
}),
]);
const active = activeLeads.length;
const byStageCount = new Map<string, number>();
for (const lead of activeLeads) {
byStageCount.set(lead.stageId, (byStageCount.get(lead.stageId) ?? 0) + 1);
}
const funnelTotal = active || 1;
let prevCount: number | null = null;
// ماندگاری و انتقال‌ها از رویدادها + وضعیت فعلی لیدهای درگیر
const leadIds = [
...new Set([
...stageEvents.map((e) => e.leadId),
...activeLeads.map((l) => l.id),
]),
];
const leadsForDwell = leadIds.length
? await this.prisma.lead.findMany({
where: { id: { in: leadIds }, organizationId: orgId, ...access },
select: {
id: true,
stageId: true,
createdAt: true,
convertedAt: true,
archivedAt: true,
events: {
where: { type: { in: ['created', 'stage_changed'] } },
select: { type: true, createdAt: true, meta: true },
orderBy: { createdAt: 'asc' },
},
},
})
: [];
const dwellSum = new Map<string, { hours: number; n: number }>();
const transitionCount = new Map<string, number>();
const leftFromCount = new Map<string, number>();
for (const lead of leadsForDwell) {
const stays = buildLeadStageStays({
leadId: lead.id,
currentStageId: lead.stageId,
createdAt: lead.createdAt,
convertedAt: lead.convertedAt,
archivedAt: lead.archivedAt,
events: lead.events,
});
for (const stay of stays) {
// فقط بازه‌هایی که با بازهٔ گزارش همپوشانی دارند
const fromMs = Math.max(stay.fromMs, start.getTime());
const toMs = Math.min(stay.toMs, end.getTime());
if (toMs <= fromMs) continue;
const hours = hoursBetween(fromMs, toMs);
const cur = dwellSum.get(stay.stageId) ?? { hours: 0, n: 0 };
cur.hours += hours;
cur.n += 1;
dwellSum.set(stay.stageId, cur);
}
for (const ev of lead.events) {
if (ev.type !== 'stage_changed') continue;
if (ev.createdAt < start || ev.createdAt > end) continue;
const meta =
ev.meta && typeof ev.meta === 'object' && !Array.isArray(ev.meta)
? (ev.meta as Record<string, unknown>)
: {};
const fromId =
typeof meta.fromStageId === 'string' ? meta.fromStageId : null;
const toId = typeof meta.toStageId === 'string' ? meta.toStageId : null;
if (!fromId || !toId || fromId === toId) continue;
const key = `${fromId}→${toId}`;
transitionCount.set(key, (transitionCount.get(key) ?? 0) + 1);
leftFromCount.set(fromId, (leftFromCount.get(fromId) ?? 0) + 1);
}
}
const funnel = stages.map((s) => {
const count = byStageCount.get(s.id) ?? 0;
const conversionFromPrevPercent =
prevCount == null
? null
: prevCount === 0
? count > 0
? 100
: 0
: Math.round((count / prevCount) * 1000) / 10;
prevCount = count;
const dwell = dwellSum.get(s.id);
return {
stageId: s.id,
stageName: s.name,
count,
sharePercent: Math.round((count / funnelTotal) * 1000) / 10,
conversionFromPrevPercent,
avgDwellHours: dwell
? Math.round((dwell.hours / dwell.n) * 10) / 10
: null,
};
});
const transitions = [...transitionCount.entries()]
.map(([key, count]) => {
const [fromStageId, toStageId] = key.split('→');
const left = leftFromCount.get(fromStageId!) ?? 0;
return {
fromStageId: fromStageId!,
fromStageName: stageName.get(fromStageId!) ?? fromStageId!,
toStageId: toStageId!,
toStageName: stageName.get(toStageId!) ?? toStageId!,
count,
conversionPercent:
left > 0 ? Math.round((count / left) * 1000) / 10 : 0,
};
})
.sort((a, b) => b.count - a.count);
const dwellByStage = stages
.map((s) => {
const d = dwellSum.get(s.id);
if (!d || d.n === 0) return null;
return {
stageId: s.id,
stageName: s.name,
avgHours: Math.round((d.hours / d.n) * 10) / 10,
sampleCount: d.n,
};
})
.filter((row): row is NonNullable<typeof row> => row != null);
const closed = converted + lost;
return {
from: start.toISOString(),
to: end.toISOString(),
created,
converted,
lost,
active,
conversionRate:
closed > 0 ? Math.round((converted / closed) * 1000) / 10 : 0,
funnel,
transitions,
dwellByStage,
};
}
async builder(
actor: Actor,
query: ReportsBuilderQuery,
@@ -1226,11 +1457,16 @@ export class ReportsService {
'invoice_amount',
'invoice_count',
]);
const leadMetric = isReportsLeadBuilderMetric(metric);
if (
if (leadMetric) {
if (dimension === 'stage') dimension = 'lead_stage';
if (dimension === 'status') dimension = 'none';
} else if (
!dealMetrics.has(metric) &&
(dimension === 'source' ||
dimension === 'stage' ||
dimension === 'lead_stage' ||
dimension === 'status')
) {
dimension = 'none';
@@ -1246,6 +1482,7 @@ export class ReportsService {
const ownerFilterIds = await this.resolveBuilderOwnerIds(actor, {
userId: query.userId,
teamId: query.teamId,
scope: leadMetric ? 'leads' : 'deals',
});
if (ownerFilterIds && ownerFilterIds.length === 0) {
return emptyBuilderResult(metric, dimension, start, end, rates.baseCurrency, format);
@@ -1310,7 +1547,7 @@ export class ReportsService {
const label = normalizeSource(opts.source);
return { key: label, label };
}
if (dimension === 'stage') {
if (dimension === 'stage' || dimension === 'lead_stage') {
const id = opts.stageId || 'none';
return { key: id, label: opts.stageName || 'بدون مرحله' };
}
@@ -1437,13 +1674,174 @@ export class ReportsService {
add(dim.key, dim.label, amount);
}
}
} else if (leadMetric) {
const leadAccess = this.leadAccessWhere(actor);
const assigneeFilter =
ownerFilterIds == null
? {}
: { assigneeId: { in: ownerFilterIds } };
const stages = await this.prisma.leadStage.findMany({
where: { organizationId: orgId },
select: {
id: true,
name: true,
isConverted: true,
isLost: true,
isUnqualified: true,
},
});
const lostIds = stages
.filter((s) => s.isLost || s.isUnqualified)
.map((s) => s.id);
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
if (metric === 'leads_avg_dwell_hours') {
const leads = await this.prisma.lead.findMany({
where: {
organizationId: orgId,
...leadAccess,
...assigneeFilter,
OR: [
{ createdAt: { gte: start, lte: end } },
{ updatedAt: { gte: start, lte: end } },
{ convertedAt: { gte: start, lte: end } },
],
},
select: {
id: true,
stageId: true,
assigneeId: true,
source: true,
createdAt: true,
convertedAt: true,
archivedAt: true,
events: {
where: { type: { in: ['created', 'stage_changed'] } },
select: { type: true, createdAt: true, meta: true },
orderBy: { createdAt: 'asc' },
},
},
});
const sum = new Map<string, { hours: number; n: number; label: string }>();
for (const lead of leads) {
const stays = buildLeadStageStays({
leadId: lead.id,
currentStageId: lead.stageId,
createdAt: lead.createdAt,
convertedAt: lead.convertedAt,
archivedAt: lead.archivedAt,
events: lead.events,
});
for (const stay of stays) {
const fromMs = Math.max(stay.fromMs, start.getTime());
const toMs = Math.min(stay.toMs, end.getTime());
if (toMs <= fromMs) continue;
const hours = hoursBetween(fromMs, toMs);
if (dimension === 'lead_stage' || dimension === 'stage') {
const name =
stages.find((s) => s.id === stay.stageId)?.name ?? stay.stageId;
const cur = sum.get(stay.stageId) ?? {
hours: 0,
n: 0,
label: name,
};
cur.hours += hours;
cur.n += 1;
sum.set(stay.stageId, cur);
} else {
const dim = await dimKey({
ownerId: lead.assigneeId,
source: lead.source,
stageId: stay.stageId,
stageName:
stages.find((s) => s.id === stay.stageId)?.name ?? null,
at: new Date(stay.fromMs),
});
const cur = sum.get(dim.key) ?? {
hours: 0,
n: 0,
label: dim.label,
};
cur.hours += hours;
cur.n += 1;
sum.set(dim.key, cur);
}
}
}
for (const [key, row] of sum.entries()) {
if (row.n <= 0) continue;
add(key, row.label, Math.round((row.hours / row.n) * 10) / 10);
}
} else {
let where: Prisma.LeadWhereInput = {
organizationId: orgId,
...leadAccess,
...assigneeFilter,
};
if (metric === 'leads_created') {
where = { ...where, createdAt: { gte: start, lte: end } };
} else if (metric === 'leads_converted') {
where = { ...where, convertedAt: { gte: start, lte: end } };
} else if (metric === 'leads_lost') {
where = {
...where,
archivedAt: null,
stageId: { in: lostIds.length ? lostIds : ['__none__'] },
updatedAt: { gte: start, lte: end },
};
} else {
// leads_active
where = {
...where,
archivedAt: null,
convertedAt: null,
stageId: {
notIn: [...lostIds, ...convertedIds],
},
};
}
const leads = await this.prisma.lead.findMany({
where,
select: {
assigneeId: true,
source: true,
stageId: true,
stage: { select: { name: true } },
createdAt: true,
updatedAt: true,
convertedAt: true,
},
});
for (const lead of leads) {
const at =
metric === 'leads_converted'
? lead.convertedAt ?? lead.updatedAt
: metric === 'leads_created'
? lead.createdAt
: lead.updatedAt;
const dim = await dimKey({
ownerId: lead.assigneeId,
source: lead.source,
stageId: lead.stageId,
stageName: lead.stage?.name,
at,
});
add(dim.key, dim.label, 1);
}
}
}
const rows: ReportsBuilderRowDto[] = [...buckets.entries()]
.map(([key, row]) => ({
key,
label: row.label,
value: Math.round(row.value * (format === 'money' ? 1 : 1)),
value:
metric === 'leads_avg_dwell_hours'
? Math.round(row.value * 10) / 10
: Math.round(row.value * (format === 'money' ? 1 : 1)),
}))
.sort((a, b) => b.value - a.value);
@@ -1471,21 +1869,52 @@ export class ReportsService {
};
}
private leadAccessWhere(actor: Actor): Prisma.LeadWhereInput {
if (actor.leadsAccess !== undefined) {
return leadsDeepWhere(actor);
}
const scoped = forScope(actor, 'leads');
if (elevated(scoped.role)) return {};
if (scoped.dataVisibility === 'org') return {};
if (
scoped.dataVisibility === 'team' &&
scoped.visibleUserIds &&
scoped.visibleUserIds.length
) {
return { assigneeId: { in: scoped.visibleUserIds } };
}
return { assigneeId: scoped.userId };
}
private async resolveBuilderOwnerIds(
actor: Actor,
opts: { userId?: string; teamId?: string },
opts: { userId?: string; teamId?: string; scope?: 'deals' | 'leads' },
): Promise<string[] | null> {
const scope = ownerWhere(actor, 'deals');
let allowed: string[] | null = null;
if ('ownerId' in scope && typeof scope.ownerId === 'string') {
allowed = [scope.ownerId];
} else if (
'ownerId' in scope &&
scope.ownerId &&
typeof scope.ownerId === 'object' &&
'in' in scope.ownerId
) {
allowed = [...scope.ownerId.in];
if (opts.scope === 'leads') {
const scoped = forScope(actor, 'leads');
if (elevated(scoped.role) || scoped.dataVisibility === 'org') {
allowed = null;
} else if (
scoped.dataVisibility === 'team' &&
scoped.visibleUserIds?.length
) {
allowed = [...scoped.visibleUserIds];
} else {
allowed = [scoped.userId];
}
} else {
const scope = ownerWhere(actor, 'deals');
if ('ownerId' in scope && typeof scope.ownerId === 'string') {
allowed = [scope.ownerId];
} else if (
'ownerId' in scope &&
scope.ownerId &&
typeof scope.ownerId === 'object' &&
'in' in scope.ownerId
) {
allowed = [...scope.ownerId.in];
}
}
let ids: string[] | null = null;
@@ -181,6 +181,33 @@ export class TreasuryController {
});
}
@Get('documents/:id')
getDocument(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.treasury.getDocument(user, id);
}
@Patch('documents/:id')
updateDocument(
@CurrentUser() user: Actor,
@Param('id') id: string,
@Body()
body: {
title?: string;
notes?: string | null;
categoryId?: string | null;
method?: string | null;
bookedAt?: string;
amount?: string | number;
},
) {
return this.treasury.updateDocument(user, id, body);
}
@Delete('documents/:id')
deleteDocument(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.treasury.deleteDocument(user, id);
}
@Get('attachments/:id')
async downloadAttachment(@CurrentUser() user: Actor, @Param('id') id: string) {
const file = await this.treasury.openAttachment(user, id);
+123 -21
View File
@@ -4,7 +4,11 @@ import {
Injectable,
NotFoundException,
} from '@nestjs/common';
import { parseUserTreasuryAccess } from '@mento/shared';
import {
canManageTreasuryDocuments,
parseUserTreasuryAccess,
permissionsWithTreasuryOverride,
} from '@mento/shared';
import { randomUUID } from 'node:crypto';
import { Prisma } from '@prisma/client';
import ExcelJS from 'exceljs';
@@ -506,13 +510,87 @@ export class TreasuryService {
}
: {}),
},
include: { category: true, account: true, movements: true, attachments: { select: { id: true, fileName: true } } },
include: {
category: true,
account: true,
movements: true,
attachments: { select: { id: true, fileName: true, mimeType: true } },
},
orderBy: { bookedAt: 'desc' },
take: 200,
});
return rows.map((row) => this.toDocumentDto(row));
}
async getDocument(actor: Actor, id: string): Promise<FinancialDocumentDto> {
const doc = await this.requireScopedDocument(actor, id);
return this.toDocumentDto(doc);
}
async updateDocument(
actor: Actor,
id: string,
input: {
title?: string;
notes?: string | null;
categoryId?: string | null;
method?: string | null;
bookedAt?: string;
amount?: string | number;
},
): Promise<FinancialDocumentDto> {
await this.assertDocumentsManage(actor);
const doc = await this.requireScopedDocument(actor, id);
if (doc.status === 'void' || doc.voidedAt) {
throw new BadRequestException('سند باطل‌شده قابل ویرایش نیست.');
}
const data: Prisma.FinancialDocumentUncheckedUpdateInput = {};
if (input.title !== undefined) {
const title = input.title.trim();
if (title.length < 2) throw new BadRequestException('عنوان را وارد کنید.');
data.title = title;
}
if (input.notes !== undefined) data.notes = input.notes?.trim() || null;
if (input.categoryId !== undefined) data.categoryId = input.categoryId || null;
if (input.method !== undefined) data.method = input.method || null;
if (input.bookedAt !== undefined) {
const bookedAt = startOfDay(input.bookedAt);
if (!bookedAt) throw new BadRequestException('تاریخ نامعتبر است.');
data.bookedAt = bookedAt;
}
if (input.amount !== undefined) {
const active = doc.movements.filter((row) => !row.voidedAt);
if (active.length > 0 || doc.status !== 'open') {
throw new BadRequestException('مبلغ فقط برای سند باز بدون دریافت/پرداخت قابل تغییر است.');
}
const amount = dec(input.amount);
if (!amount.greaterThan(0)) throw new BadRequestException('مبلغ باید بزرگ‌تر از صفر باشد.');
data.amount = amount;
}
await this.prisma.financialDocument.update({ where: { id: doc.id }, data });
return this.getDocument(actor, id);
}
async deleteDocument(actor: Actor, id: string): Promise<{ ok: true }> {
await this.assertDocumentsManage(actor);
const doc = await this.requireScopedDocument(actor, id);
const active = doc.movements.filter((row) => !row.voidedAt);
if (doc.status !== 'void' && active.length > 0) {
throw new BadRequestException('ابتدا سند را ابطال کنید، سپس حذف کنید.');
}
const attachments = await this.prisma.financialAttachment.findMany({
where: { documentId: doc.id, organizationId: actor.organizationId },
select: { id: true, storageKey: true },
});
for (const file of attachments) {
const bytes = await this.files.sizeOf(file.storageKey);
await this.files.remove(file.storageKey);
if (bytes) await this.storage.addLocal(actor.organizationId, -bytes);
}
await this.prisma.financialDocument.delete({ where: { id: doc.id } });
return { ok: true };
}
async createDocument(
actor: Actor,
input: {
@@ -557,12 +635,6 @@ export class TreasuryService {
if (input.accountId) {
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
if (input.kind === 'expense' && settle.greaterThan(0)) {
const balance = await this.accountBalance(account.id);
if (balance.lessThan(settle)) {
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
}
}
}
const bookedAt = startOfDay(input.bookedAt) ?? new Date();
const settlement = input.settlement === true;
@@ -905,12 +977,6 @@ export class TreasuryService {
if (amount.greaterThan(available)) {
throw new BadRequestException('مبلغ از ماندهٔ سندهای باز این طرف حساب بیشتر است.');
}
if (input.kind === 'expense') {
const balance = await this.accountBalance(account.id);
if (balance.lessThan(amount)) {
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
}
}
const occurredAt = startOfDay(input.occurredAt) ?? new Date();
let left = amount;
const touched: string[] = [];
@@ -1050,12 +1116,6 @@ export class TreasuryService {
}
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
if (doc.kind === 'expense') {
const balance = await this.accountBalance(account.id);
if (balance.lessThan(amount)) {
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
}
}
const nextSettled = settled.plus(amount);
const status = nextSettled.equals(doc.amount) ? 'settled' : 'partial';
await this.prisma.$transaction([
@@ -1443,6 +1503,47 @@ export class TreasuryService {
);
}
private async actorPermissions(actor: Actor): Promise<string[]> {
const membership = await this.prisma.membership.findFirst({
where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true },
select: {
orgRole: { select: { permissions: true } },
treasuryAccessOverride: true,
},
});
const rolePermissions = Array.isArray(membership?.orgRole?.permissions)
? membership.orgRole.permissions.map(String)
: [];
return permissionsWithTreasuryOverride(
rolePermissions,
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
);
}
private async assertDocumentsManage(actor: Actor) {
if (canManageTreasuryDocuments(actor.role, await this.actorPermissions(actor))) return;
throw new ForbiddenException('اجازه ویرایش یا حذف اسناد را ندارید.');
}
private async requireScopedDocument(actor: Actor, id: string) {
const scope = await this.accountScope(actor);
const doc = await this.prisma.financialDocument.findFirst({
where: {
id,
organizationId: actor.organizationId,
...(scope ? { OR: [{ accountId: null }, { accountId: { in: scope } }] } : {}),
},
include: {
category: true,
account: true,
movements: true,
attachments: { select: { id: true, fileName: true, mimeType: true } },
},
});
if (!doc) throw new NotFoundException('سند پیدا نشد.');
return doc;
}
private async accountScope(actor: Actor): Promise<string[] | null> {
if (actor.role === 'owner' || actor.role === 'admin') return null;
const membership = await this.prisma.membership.findFirst({
@@ -1566,7 +1667,8 @@ export class TreasuryService {
category?: { name: string } | null;
account?: { name: string } | null;
movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>;
attachments?: Array<{ id: string; fileName: string }>;
attachments?: Array<{ id: string; fileName: string; mimeType?: string }>;
voidedAt?: Date | null;
}): FinancialDocumentDto {
const settled = this.settledOf(row.movements);
const rawRemaining = row.amount.minus(settled);