diff --git a/apps/api/prisma/migrations/20261117190000_account_balances/migration.sql b/apps/api/prisma/migrations/20261117190000_account_balances/migration.sql new file mode 100644 index 0000000..97ad697 --- /dev/null +++ b/apps/api/prisma/migrations/20261117190000_account_balances/migration.sql @@ -0,0 +1,22 @@ +-- AlterTable +ALTER TABLE "Organization" ADD COLUMN "accountBalanceSettings" JSONB NOT NULL DEFAULT '{}'; +ALTER TABLE "Organization" ADD COLUMN "accountBalanceClaimsLastSlot" TEXT; + +-- AlterTable +ALTER TABLE "CustomerGroup" ADD COLUMN "assigneeIds" TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[]; + +-- Backfill ordered assignee ids from existing M2M (alphabetical until re-saved) +UPDATE "CustomerGroup" AS g +SET "assigneeIds" = COALESCE(( + SELECT ARRAY_AGG(link."B" ORDER BY u."fullName") + FROM "_CustomerGroupAssignees" AS link + INNER JOIN "User" AS u ON u."id" = link."B" + WHERE link."A" = g."id" +), ARRAY[]::TEXT[]) +WHERE COALESCE(cardinality(g."assigneeIds"), 0) = 0; + +-- AlterTable +ALTER TABLE "ActivityBoard" ADD COLUMN "systemKey" TEXT; + +-- CreateIndex (NULLs allowed multiple times in PostgreSQL) +CREATE UNIQUE INDEX "ActivityBoard_organizationId_systemKey_key" ON "ActivityBoard"("organizationId", "systemKey"); diff --git a/apps/api/prisma/migrations/20261119120000_activity_experience/migration.sql b/apps/api/prisma/migrations/20261119120000_activity_experience/migration.sql new file mode 100644 index 0000000..e873acc --- /dev/null +++ b/apps/api/prisma/migrations/20261119120000_activity_experience/migration.sql @@ -0,0 +1,11 @@ +-- AlterTable +ALTER TABLE "Lead" ADD COLUMN "activityExperience" TEXT; + +-- AlterTable +ALTER TABLE "Person" ADD COLUMN "activityExperience" TEXT; + +-- CreateIndex +CREATE INDEX "Lead_organizationId_activityExperience_idx" ON "Lead"("organizationId", "activityExperience"); + +-- CreateIndex +CREATE INDEX "Person_organizationId_activityExperience_idx" ON "Person"("organizationId", "activityExperience"); diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 0750357..2e21b3a 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -164,6 +164,10 @@ model Organization { enabledModules String[] @default([]) /// برچسب/رنگ اولویت فعالیت و روتین (کلیدهای enum ثابت؛ فقط ظاهر) activityPriorities Json @default("{}") + /// تنظیم محدوده مانده حساب برای کاریز مطالبات + accountBalanceSettings Json @default("{}") + /// آخرین اسلات اجرای جاب مطالبات مانده (YYYY-MM-DD-HH تهران) + accountBalanceClaimsLastSlot String? /// قالب‌های آمادهٔ پیامک دستی ([{ id, name, body }, …]) smsTemplates Json @default("[]") /// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخاب‌شده)؛ null = بدون فیلتر @@ -583,6 +587,8 @@ model CustomerGroup { companies CompanyGroupLink[] /// مسئولان گروه — اختیاری؛ اعضای گروه را مثل مشتریان خود می‌بینند assignees User[] @relation("CustomerGroupAssignees") + /// ترتیب انتخاب مسئولان در فرم (اولین = مسئول اصلی مطالبات) + assigneeIds String[] @default([]) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt @@ -650,6 +656,8 @@ model Person { birthDate DateTime? /// نام معرف referrer String? + /// سابقه فعالیت (ندارم | 1 الی 2 سال | 2 الی 5 سال | بیش از 5 سال) + activityExperience String? /// لیست آدرس‌ها (JSON array of strings) addresses Json @default("[]") notes String? @@ -704,6 +712,7 @@ model Person { @@index([ownerId]) @@index([loyaltyTierId]) @@index([organizationId, discLabel]) + @@index([organizationId, activityExperience]) } model Pipeline { @@ -813,6 +822,8 @@ model ActivityBoard { organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) name String isDefault Boolean @default(false) + /// مثلاً balance_claims — گروه سیستمی + systemKey String? position Int @default(0) stages ActivityStage[] activities Activity[] @@ -821,6 +832,7 @@ model ActivityBoard { updatedAt DateTime @updatedAt @@unique([organizationId, name]) + @@unique([organizationId, systemKey]) @@index([organizationId, position]) } @@ -3149,6 +3161,8 @@ model Lead { /// صنف trade String? source String? + /// سابقه فعالیت (ندارم | 1 الی 2 سال | 2 الی 5 سال | بیش از 5 سال) + activityExperience String? notes String? /// لوگوی فروشگاه / شرکت logoStorageKey String? @@ -3186,6 +3200,7 @@ model Lead { @@index([organizationId, city]) @@index([organizationId, trade]) @@index([organizationId, source]) + @@index([organizationId, activityExperience]) } model LeadEvent { diff --git a/apps/api/src/account-balances/account-balance-settings.service.ts b/apps/api/src/account-balances/account-balance-settings.service.ts new file mode 100644 index 0000000..1911f50 --- /dev/null +++ b/apps/api/src/account-balances/account-balance-settings.service.ts @@ -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 { + const row = await this.prisma.organization.findUnique({ + where: { id: organizationId }, + select: { accountBalanceSettings: true }, + }); + return parseAccountBalanceSettings(row?.accountBalanceSettings); + } + + async update( + organizationId: string, + dto: UpdateAccountBalanceSettingsRequest, + ): Promise { + 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; + } +} diff --git a/apps/api/src/account-balances/account-balances.controller.ts b/apps/api/src/account-balances/account-balances.controller.ts new file mode 100644 index 0000000..c96fc8c --- /dev/null +++ b/apps/api/src/account-balances/account-balances.controller.ts @@ -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, + }); + } +} diff --git a/apps/api/src/account-balances/account-balances.module.ts b/apps/api/src/account-balances/account-balances.module.ts new file mode 100644 index 0000000..ca8c74d --- /dev/null +++ b/apps/api/src/account-balances/account-balances.module.ts @@ -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 {} diff --git a/apps/api/src/account-balances/balance-claims.scheduler.ts b/apps/api/src/account-balances/balance-claims.scheduler.ts new file mode 100644 index 0000000..1ff07a2 --- /dev/null +++ b/apps/api/src/account-balances/balance-claims.scheduler.ts @@ -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; + } + } +} diff --git a/apps/api/src/account-balances/balance-claims.service.ts b/apps/api/src/account-balances/balance-claims.service.ts new file mode 100644 index 0000000..2387c11 --- /dev/null +++ b/apps/api/src/account-balances/balance-claims.service.ts @@ -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 { + let offset = 0; + let merged: AccountBalanceEvaluateResultDto | null = null; + for (;;) { + const batch = await this.evaluateOrganization(organizationId, { + offset, + limit: ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE, + }); + merged = merged ? this.mergeResults(merged, batch) : batch; + if (batch.done || batch.nextOffset == null) { + merged.message = this.summarize(merged); + this.logger.log(`مطالبات کامل ${organizationId}: ${merged.message}`); + return merged; + } + offset = batch.nextOffset; + } + } + + async evaluateOrganization( + organizationId: string, + opts?: { offset?: number; limit?: number }, + ): Promise { + const offset = Math.max(0, Math.floor(opts?.offset ?? 0)); + const limit = Math.min( + ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE, + Math.max(1, Math.floor(opts?.limit ?? ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE)), + ); + + const empty = (message: string): AccountBalanceEvaluateResultDto => ({ + linkedPeople: 0, + candidates: 0, + skippedNoAssignee: 0, + matched: 0, + created: 0, + reopened: 0, + canceled: 0, + unchanged: 0, + errors: 0, + message, + offset, + limit, + batchProcessed: 0, + done: true, + nextOffset: null, + }); + + const org = await this.prisma.organization.findUnique({ + where: { id: organizationId }, + select: { enabledModules: true, accountBalanceSettings: true }, + }); + if (!org?.enabledModules.includes('account_balances')) { + return empty('ماژول مانده حساب برای این محیط فعال نیست.'); + } + + const settings = parseAccountBalanceSettings(org.accountBalanceSettings); + const hasAnyRange = + Boolean(settings.rial) || Object.keys(settings.weights).length > 0; + if (!hasAnyRange) { + return empty('هیچ بازهٔ فعالی ذخیره نشده است. ابتدا محدوده را ذخیره کنید.'); + } + + const board = await this.ensureBoard(organizationId, settings.firstStageName); + const typeDef = await this.ensureFollowUpType(organizationId); + const stages = await this.prisma.activityStage.findMany({ + where: { boardId: board.id }, + orderBy: [{ position: 'asc' }, { createdAt: 'asc' }], + select: { id: true, kind: true }, + }); + const openStageId = stages.find((s) => s.kind === 'open')?.id; + const canceledStageId = stages.find((s) => s.kind === 'canceled')?.id; + if (!openStageId || !canceledStageId) { + return empty('ستون‌های کاریز مطالبات ناقص است.'); + } + + const { candidates, linkedPeople, skippedNoAssignee } = + await this.loadCandidates(organizationId); + + const slice = candidates.slice(offset, offset + limit); + const nextOffset = offset + slice.length; + const done = nextOffset >= candidates.length; + + const result: AccountBalanceEvaluateResultDto = { + linkedPeople, + candidates: candidates.length, + skippedNoAssignee, + matched: 0, + created: 0, + reopened: 0, + canceled: 0, + unchanged: 0, + errors: 0, + message: '', + offset, + limit, + batchProcessed: slice.length, + done, + nextOffset: done ? null : nextOffset, + }; + + const actions = await this.mapPool(slice, BATCH_CONCURRENCY, async (person) => { + try { + return await this.syncPerson({ + organizationId, + person, + settings, + boardId: board.id, + openStageId, + canceledStageId, + typeDefId: typeDef.id, + baseType: typeDef.baseType, + preferCache: true, + }); + } catch (err) { + this.logger.warn( + `مانده/مطالبه شخص ${person.personId}: ${err instanceof Error ? err.message : err}`, + ); + return 'error' as const; + } + }); + for (const action of actions) { + if (action === 'created') { + result.matched += 1; + result.created += 1; + } else if (action === 'reopened') { + result.matched += 1; + result.reopened += 1; + } else if (action === 'canceled') { + result.canceled += 1; + } else if (action === 'matched-unchanged') { + result.matched += 1; + result.unchanged += 1; + } else if (action === 'error') { + result.errors += 1; + } else { + result.unchanged += 1; + } + } + + result.message = done + ? this.summarize(result) + : `تکه ${offset + 1} تا ${nextOffset} از ${candidates.length} · ادامه…`; + this.logger.log(`مطالبات ${organizationId}: ${result.message}`); + return result; + } + + private mergeResults( + a: AccountBalanceEvaluateResultDto, + b: AccountBalanceEvaluateResultDto, + ): AccountBalanceEvaluateResultDto { + return { + linkedPeople: Math.max(a.linkedPeople, b.linkedPeople), + candidates: Math.max(a.candidates, b.candidates), + skippedNoAssignee: Math.max(a.skippedNoAssignee, b.skippedNoAssignee), + matched: a.matched + b.matched, + created: a.created + b.created, + reopened: a.reopened + b.reopened, + canceled: a.canceled + b.canceled, + unchanged: a.unchanged + b.unchanged, + errors: a.errors + b.errors, + message: b.message, + offset: a.offset, + limit: a.limit, + batchProcessed: a.batchProcessed + b.batchProcessed, + done: b.done, + nextOffset: b.nextOffset, + }; + } + + private async mapPool( + items: T[], + concurrency: number, + worker: (item: T) => Promise, + ): Promise { + if (!items.length) return []; + const out = new Array(items.length); + let index = 0; + const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => { + while (index < items.length) { + const currentIndex = index++; + out[currentIndex] = await worker(items[currentIndex]!); + } + }); + await Promise.all(runners); + return out; + } + + private summarize(r: AccountBalanceEvaluateResultDto): string { + if (r.linkedPeople === 0) { + return 'هیچ مشتری لینک‌شده به ته‌حساب پیدا نشد.'; + } + if (r.candidates === 0) { + return `از ${r.linkedPeople} مشتری لینک‌شده، هیچ‌کدام گروه با مسئول ندارند (${r.skippedNoAssignee} بدون مسئول گروه).`; + } + if (r.matched === 0 && r.canceled === 0 && r.errors === 0) { + return `بررسی شد: ${r.candidates} نفر واجد شرایط گروه/مسئول؛ هیچ‌کدام داخل بازهٔ ذخیره‌شده نبودند.`; + } + const parts = [ + `${r.candidates} واجد شرایط`, + `${r.matched} داخل بازه`, + `${r.created} ساخته`, + `${r.reopened} بازگشایی`, + `${r.canceled} خارج از بازه`, + ]; + if (r.errors) parts.push(`${r.errors} خطا`); + if (r.skippedNoAssignee) parts.push(`${r.skippedNoAssignee} بدون مسئول گروه`); + return parts.join(' · '); + } + + private async loadCandidates(organizationId: string): Promise<{ + candidates: PersonClaimContext[]; + linkedPeople: number; + skippedNoAssignee: number; + }> { + const links = await this.prisma.personAccountingLink.findMany({ + where: { + connection: { organizationId, provider: 'tahesab', enabled: true }, + person: { organizationId }, + }, + select: { + personId: true, + connectionId: true, + linkedAt: true, + connection: { select: { isDefault: true } }, + person: { + select: { + id: true, + firstName: true, + lastName: true, + groupLinks: { + select: { + group: { + select: { + name: true, + position: true, + assigneeIds: true, + assignees: { select: { id: true } }, + }, + }, + }, + }, + }, + }, + }, + }); + + const out: PersonClaimContext[] = []; + const seen = new Set(); + let skippedNoAssignee = 0; + const orderedLinks = [...links].sort((a, b) => { + if (a.personId !== b.personId) return a.personId.localeCompare(b.personId); + if (a.connection.isDefault !== b.connection.isDefault) { + return a.connection.isDefault ? -1 : 1; + } + return a.linkedAt.getTime() - b.linkedAt.getTime(); + }); + + for (const link of orderedLinks) { + if (seen.has(link.personId)) continue; + seen.add(link.personId); + + const groups = [...link.person.groupLinks] + .map((g) => g.group) + .sort((a, b) => a.position - b.position || a.name.localeCompare(b.name, 'fa')); + + let assigneeId: string | null = null; + for (const group of groups) { + const fromRelation = group.assignees.map((a) => a.id); + const valid = new Set(fromRelation); + let ordered = + group.assigneeIds.length > 0 + ? group.assigneeIds.filter((id) => valid.has(id)) + : []; + // اگر ترتیب ذخیره‌شده با M2M هم‌خوان نبود، همان مسئولان رابطه را بگیر + if (!ordered.length) ordered = fromRelation; + if (ordered.length) { + assigneeId = ordered[0]!; + break; + } + } + + if (!assigneeId) { + skippedNoAssignee += 1; + continue; + } + + out.push({ + personId: link.person.id, + fullName: `${link.person.firstName} ${link.person.lastName}`.trim(), + connectionId: link.connectionId, + assigneeId, + }); + } + + return { + candidates: out, + linkedPeople: seen.size, + skippedNoAssignee, + }; + } + + private async syncPerson(input: { + organizationId: string; + person: PersonClaimContext; + settings: AccountBalanceSettingsDto; + boardId: string; + openStageId: string; + canceledStageId: string; + typeDefId: string; + baseType: 'call' | 'meeting' | 'task' | 'note'; + /** در ارزیابی دسته‌ای اول از کش استفاده کن تا تایم‌اوت نشود */ + preferCache?: boolean; + }): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> { + let assets; + if (input.preferCache) { + try { + assets = await this.balances.getCachedOrFetch( + input.organizationId, + input.person.personId, + input.person.connectionId, + false, + ); + } catch { + assets = await this.balances.getAssets( + input.organizationId, + input.person.personId, + input.person.connectionId, + ); + } + } else { + try { + assets = await this.balances.getAssets( + input.organizationId, + input.person.personId, + input.person.connectionId, + ); + } catch { + assets = await this.balances.getCachedOrFetch( + input.organizationId, + input.person.personId, + input.person.connectionId, + false, + ); + } + } + + const matched = this.matchesAnyRange(assets, input.settings); + + const existing = await this.prisma.activity.findFirst({ + where: { + organizationId: input.organizationId, + boardId: input.boardId, + personId: input.person.personId, + tags: { has: ACCOUNT_BALANCE_CLAIMS_TAG }, + }, + orderBy: { createdAt: 'desc' }, + select: { + id: true, + status: true, + stageId: true, + assigneeId: true, + }, + }); + + const title = `مطالبه: ${input.person.fullName}`; + + if (matched) { + if (!existing) { + await this.prisma.activity.create({ + data: { + organizationId: input.organizationId, + boardId: input.boardId, + stageId: input.openStageId, + status: 'open', + title, + type: input.baseType, + typeDefId: input.typeDefId, + personId: input.person.personId, + assigneeId: input.person.assigneeId, + assignees: { connect: [{ id: input.person.assigneeId }] }, + tags: [ACCOUNT_BALANCE_CLAIMS_TAG], + editPolicy: 'assignees', + completionMode: 'any', + completedByIds: [], + createdById: input.person.assigneeId, + }, + }); + return 'created'; + } + + // فقط بعد از خروج از بازه (لغو) دوباره از ستون اول بیاید؛ + // ستون‌های میانی / انجام‌شده حفظ می‌شوند. + if (existing.status === 'canceled') { + await this.prisma.activity.update({ + where: { id: existing.id }, + data: { + status: 'open', + stageId: input.openStageId, + completedAt: null, + completedByIds: [], + assigneeId: input.person.assigneeId, + assignees: { set: [{ id: input.person.assigneeId }] }, + title, + }, + }); + return 'reopened'; + } + + // هنوز داخل بازه: ستون و وضعیت (در حال انجام / انجام‌شده) حفظ شود + await this.prisma.activity.update({ + where: { id: existing.id }, + data: { + title, + ...(existing.assigneeId !== input.person.assigneeId + ? { + assigneeId: input.person.assigneeId, + assignees: { set: [{ id: input.person.assigneeId }] }, + } + : {}), + }, + }); + return 'matched-unchanged'; + } + + if (existing && existing.status !== 'canceled') { + await this.prisma.activity.update({ + where: { id: existing.id }, + data: { + status: 'canceled', + stageId: input.canceledStageId, + completedAt: new Date(), + }, + }); + return 'canceled'; + } + return 'out-unchanged'; + } + + private matchesAnyRange( + assets: { + rialBalance: number | null; + goldBalance: number | null; + mandehFields?: Array<{ key: string; value: string | null }>; + }, + settings: AccountBalanceSettingsDto, + ): boolean { + if (accountBalanceMatchesCriterion(assets.rialBalance, settings.rial)) return true; + + const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields); + for (const [key, criterion] of Object.entries(settings.weights)) { + const value = + fieldMap[key] ?? + (key === 'MandeyeVazni' ? assets.goldBalance : null) ?? + null; + if (accountBalanceMatchesCriterion(value, criterion)) return true; + } + return false; + } +} diff --git a/apps/api/src/account-balances/dto.ts b/apps/api/src/account-balances/dto.ts new file mode 100644 index 0000000..2e5cf58 --- /dev/null +++ b/apps/api/src/account-balances/dto.ts @@ -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; +} + +export class EvaluateAccountBalancesDto { + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(0) + offset?: number; + + @IsOptional() + @Type(() => Number) + @IsInt() + @Min(1) + @Max(2000) + limit?: number; +} diff --git a/apps/api/src/activities/activities-excel.service.ts b/apps/api/src/activities/activities-excel.service.ts index 94aa74f..7a7c655 100644 --- a/apps/api/src/activities/activities-excel.service.ts +++ b/apps/api/src/activities/activities-excel.service.ts @@ -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 }, }); diff --git a/apps/api/src/activities/activities.service.ts b/apps/api/src/activities/activities.service.ts index 35207e3..188db41 100644 --- a/apps/api/src/activities/activities.service.ts +++ b/apps/api/src/activities/activities.service.ts @@ -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 { + 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(); + 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(); + 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 => 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) diff --git a/apps/api/src/activities/activity-stages.service.ts b/apps/api/src/activities/activity-stages.service.ts index bef0361..82f27ab 100644 --- a/apps/api/src/activities/activity-stages.service.ts +++ b/apps/api/src/activities/activity-stages.service.ts @@ -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(); + 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 { - 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 }, diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 6898095..187cd55 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -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, diff --git a/apps/api/src/automations/automations.service.ts b/apps/api/src/automations/automations.service.ts index ebbfd36..4d91cba 100644 --- a/apps/api/src/automations/automations.service.ts +++ b/apps/api/src/automations/automations.service.ts @@ -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 { + /** مسئول فعلی رکورد؛ هرگز مالک سازمان را به‌صورت ضمنی اضافه نکن */ 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; } diff --git a/apps/api/src/contacts/dto.ts b/apps/api/src/contacts/dto.ts index 221d9d1..5dd7f71 100644 --- a/apps/api/src/contacts/dto.ts +++ b/apps/api/src/contacts/dto.ts @@ -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 }) diff --git a/apps/api/src/contacts/people.controller.ts b/apps/api/src/contacts/people.controller.ts index b015349..6f67f18 100644 --- a/apps/api/src/contacts/people.controller.ts +++ b/apps/api/src/contacts/people.controller.ts @@ -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, }); } diff --git a/apps/api/src/contacts/people.service.ts b/apps/api/src/contacts/people.service.ts index a82fd00..259a1bc 100644 --- a/apps/api/src/contacts/people.service.ts +++ b/apps/api/src/contacts/people.service.ts @@ -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(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> { 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 { @@ -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; diff --git a/apps/api/src/customer-groups/customer-groups.service.ts b/apps/api/src/customer-groups/customer-groups.service.ts index a77e4ea..6cea8ce 100644 --- a/apps/api/src/customer-groups/customer-groups.service.ts +++ b/apps/api/src/customer-groups/customer-groups.service.ts @@ -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) { diff --git a/apps/api/src/lead-forms/dto.ts b/apps/api/src/lead-forms/dto.ts index 853c0a7..2644253 100644 --- a/apps/api/src/lead-forms/dto.ts +++ b/apps/api/src/lead-forms/dto.ts @@ -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', diff --git a/apps/api/src/lead-forms/lead-forms.service.ts b/apps/api/src/lead-forms/lead-forms.service.ts index 28f9fd6..874a41a 100644 --- a/apps/api/src/lead-forms/lead-forms.service.ts +++ b/apps/api/src/lead-forms/lead-forms.service.ts @@ -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'); diff --git a/apps/api/src/leads/dto.ts b/apps/api/src/leads/dto.ts index ed8fd9a..9404975 100644 --- a/apps/api/src/leads/dto.ts +++ b/apps/api/src/leads/dto.ts @@ -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 { diff --git a/apps/api/src/leads/lead-stages.service.ts b/apps/api/src/leads/lead-stages.service.ts index 055830d..aa930f1 100644 --- a/apps/api/src/leads/lead-stages.service.ts +++ b/apps/api/src/leads/lead-stages.service.ts @@ -43,18 +43,26 @@ export class LeadStagesService { }); } - async list(organizationId: string): Promise { + async list( + organizationId: string, + opts: { withLeadCounts?: boolean } = {}, + ): Promise { + 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)); } diff --git a/apps/api/src/leads/leads-import.service.ts b/apps/api/src/leads/leads-import.service.ts index 6b93ceb..20ea014 100644 --- a/apps/api/src/leads/leads-import.service.ts +++ b/apps/api/src/leads/leads-import.service.ts @@ -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({ diff --git a/apps/api/src/leads/leads.controller.ts b/apps/api/src/leads/leads.controller.ts index ffa4310..a941c50 100644 --- a/apps/api/src/leads/leads.controller.ts +++ b/apps/api/src/leads/leads.controller.ts @@ -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') diff --git a/apps/api/src/leads/leads.service.ts b/apps/api/src/leads/leads.service.ts index c49cc81..932d34a 100644 --- a/apps/api/src/leads/leads.service.ts +++ b/apps/api/src/leads/leads.service.ts @@ -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[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 { - 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 { @@ -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 { 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 { + 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, diff --git a/apps/api/src/reports/leads-analytics.util.ts b/apps/api/src/reports/leads-analytics.util.ts new file mode 100644 index 0000000..eb0e8b6 --- /dev/null +++ b/apps/api/src/reports/leads-analytics.util.ts @@ -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; + 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)); +} diff --git a/apps/api/src/reports/reports.controller.ts b/apps/api/src/reports/reports.controller.ts index 597db8a..12e9fff 100644 --- a/apps/api/src/reports/reports.controller.ts +++ b/apps/api/src/reports/reports.controller.ts @@ -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 }) diff --git a/apps/api/src/reports/reports.service.ts b/apps/api/src/reports/reports.service.ts index 3c550ac..2c4664b 100644 --- a/apps/api/src/reports/reports.service.ts +++ b/apps/api/src/reports/reports.service.ts @@ -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 { + 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(); + 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(); + const transitionCount = new Map(); + const leftFromCount = new Map(); + + 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) + : {}; + 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 => 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(); + 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 { - 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; diff --git a/apps/api/src/treasury/treasury.controller.ts b/apps/api/src/treasury/treasury.controller.ts index 75880d4..f0ec94f 100644 --- a/apps/api/src/treasury/treasury.controller.ts +++ b/apps/api/src/treasury/treasury.controller.ts @@ -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); diff --git a/apps/api/src/treasury/treasury.service.ts b/apps/api/src/treasury/treasury.service.ts index d9cfdc3..0899246 100644 --- a/apps/api/src/treasury/treasury.service.ts +++ b/apps/api/src/treasury/treasury.service.ts @@ -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 { + 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 { + 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 { + 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 { 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); diff --git a/apps/web/src/components/ContactsFilterPanel.vue b/apps/web/src/components/ContactsFilterPanel.vue index 80ec9b4..c7b477b 100644 --- a/apps/web/src/components/ContactsFilterPanel.vue +++ b/apps/web/src/components/ContactsFilterPanel.vue @@ -1,6 +1,7 @@ + + diff --git a/apps/web/src/components/activities/ActivityCommentSheet.vue b/apps/web/src/components/activities/ActivityCommentSheet.vue index 5cd8345..80e9e04 100644 --- a/apps/web/src/components/activities/ActivityCommentSheet.vue +++ b/apps/web/src/components/activities/ActivityCommentSheet.vue @@ -16,7 +16,11 @@ import type { ActivityDto, ActivityType, OrganizationDto, OrgUserDto } from '@me const props = defineProps<{ activity: ActivityDto; saving?: boolean; - save: (payload: { text: string; photoOnly: boolean }) => Promise; + save: (payload: { + text: string; + photoOnly: boolean; + attachmentIds?: string[]; + }) => Promise; /** بالاتر از مودال خلاصهٔ فعالیت */ overlayZIndex?: number; }>(); @@ -233,28 +237,35 @@ async function toggleVoiceNote() { } } -async function uploadQueue(items: Array<{ localId: string; name: string; file: File }>, drop: (localId: string) => void) { +async function uploadQueue( + items: Array<{ localId: string; name: string; file: File }>, + drop: (localId: string) => void, +): Promise { + const ids: string[] = []; for (const item of items) { const form = new FormData(); form.append('file', item.file, item.name); - await api.post(`/activities/${props.activity.id}/images`, form); + const { data } = await api.post<{ id: string }>(`/activities/${props.activity.id}/images`, form); + ids.push(data.id); drop(item.localId); uploadedCount.value += 1; } + return ids; } -async function uploadPendingPhotos() { - await uploadQueue([...pendingPhotos.value], (localId) => { +async function uploadPendingPhotos(): Promise { + const photoIds = await uploadQueue([...pendingPhotos.value], (localId) => { pendingPhotos.value = pendingPhotos.value.filter((item) => item.localId !== localId); }); - await uploadQueue([...pendingVoices.value], (localId) => { + const voiceIds = await uploadQueue([...pendingVoices.value], (localId) => { const voice = pendingVoices.value.find((item) => item.localId === localId); if (voice) URL.revokeObjectURL(voice.url); pendingVoices.value = pendingVoices.value.filter((item) => item.localId !== localId); }); - await uploadQueue([...pendingFiles.value], (localId) => { + const fileIds = await uploadQueue([...pendingFiles.value], (localId) => { pendingFiles.value = pendingFiles.value.filter((item) => item.localId !== localId); }); + return [...photoIds, ...voiceIds, ...fileIds]; } async function submit() { @@ -268,11 +279,15 @@ async function submit() { pendingFiles.value.length > 0 || uploadedCount.value > 0; try { - await uploadPendingPhotos(); - await props.save({ text, photoOnly: hadPhoto && !text }); + const attachmentIds = await uploadPendingPhotos(); + await props.save({ + text, + photoOnly: hadPhoto && !text, + attachmentIds, + }); } catch (error) { photoError.value = - pendingPhotos.value.length > 0 + pendingPhotos.value.length > 0 || pendingFiles.value.length > 0 || pendingVoices.value.length > 0 ? apiMessage(error, 'افزودن فایل ناموفق بود.') : apiMessage(error, 'ثبت نظر ناموفق بود.'); } finally { diff --git a/apps/web/src/components/activities/ActivityQuickView.vue b/apps/web/src/components/activities/ActivityQuickView.vue index 56073a1..9f82ae5 100644 --- a/apps/web/src/components/activities/ActivityQuickView.vue +++ b/apps/web/src/components/activities/ActivityQuickView.vue @@ -31,6 +31,7 @@ import { import { useAuthStore } from '@/stores/auth'; import { canCollaborateOnActivity, canMutateActivity } from '@/lib/activity-access'; import ActivityCommentSheet from '@/components/activities/ActivityCommentSheet.vue'; +import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue'; const props = defineProps<{ @@ -309,17 +310,35 @@ function apiMessage(e: unknown, fallback: string) { return fallback; } +function viewMedia(item: NoteMedia) { + window.open(item.url, '_blank', 'noopener,noreferrer'); +} + +function downloadMedia(item: NoteMedia) { + const link = document.createElement('a'); + link.href = item.url; + link.download = item.name || 'file'; + link.rel = 'noopener'; + document.body.appendChild(link); + link.click(); + link.remove(); +} + async function loadNoteMedia(row: ActivityDto) { clearNoteMedia(); const next: NoteMedia[] = []; for (const image of row.images ?? []) { - const mime = image.mimeType.toLowerCase(); + const mime = (image.mimeType || 'application/octet-stream').toLowerCase(); const kind = mime.startsWith('audio/') ? 'audio' : mime.startsWith('image/') ? 'image' : 'file'; try { const { data } = await api.get(`/activities/${row.id}/images/${image.id}`, { responseType: 'blob', }); - const url = URL.createObjectURL(data); + const blob = + data.type && data.type !== 'application/octet-stream' && !data.type.includes('json') + ? data + : new Blob([data], { type: mime }); + const url = URL.createObjectURL(blob); if (props.activityId !== row.id) { URL.revokeObjectURL(url); continue; @@ -425,7 +444,7 @@ async function runAction() { const { data } = await api.patch(`/activities/${id}/complete`, undefined, { params: undo ? { undo: '1' } : undefined, }); - if (data.status === 'done') { + if (data.status === 'done' || (!undo && data.completionMode === 'all')) { emit('changed'); emit('close'); return; @@ -455,10 +474,14 @@ async function postponeTo(iso: string) { } } -async function submitComment(payload: { text: string; photoOnly: boolean }) { +async function submitComment(payload: { + text: string; + photoOnly: boolean; + attachmentIds?: string[]; +}) { const id = props.activityId; const row = activity.value; - const body = payload.text.trim() || (payload.photoOnly ? 'عکس پیوست شد.' : ''); + const body = payload.text.trim() || (payload.photoOnly ? 'فایل پیوست شد.' : ''); if (!id || !row || !body) return; saving.value = true; error.value = ''; @@ -467,7 +490,9 @@ async function submitComment(payload: { text: string; photoOnly: boolean }) { const now = new Date(); const author = auth.user?.fullName?.trim(); const stamp = `[${formatJalaliNumeric(now)} ساعت ${formatClockFa(now)}${author ? ` — ${author}` : ''}]`; - const entry = `${stamp}\n${body}`; + const ids = [...new Set((payload.attachmentIds ?? []).filter(Boolean))]; + const attachLine = ids.length ? `\n[[attachments:${ids.join(',')}]]` : ''; + const entry = `${stamp}\n${body}${attachLine}`; await api.patch(`/activities/${id}`, { description: prev ? `${prev}\n\n${entry}` : entry }); commentOpen.value = false; await load(id); @@ -531,6 +556,16 @@ function openFull() { +
+ + مانده حساب + + +
+ یادداشت @@ -597,11 +632,60 @@ function openFull() { :preview="{ zIndex: 1300 }" /> + + + + + {{ file.name }} + + مشاهده + دانلود + + +
+
+ + {{ file.name }} + + مشاهده + دانلود + + +
diff --git a/apps/web/src/components/pipeline/DealCard.vue b/apps/web/src/components/pipeline/DealCard.vue index 1ce28c1..16684fe 100644 --- a/apps/web/src/components/pipeline/DealCard.vue +++ b/apps/web/src/components/pipeline/DealCard.vue @@ -20,6 +20,7 @@ import { theme, } from 'ant-design-vue'; import DealQuickActivityPopover from '@/components/pipeline/DealQuickActivityPopover.vue'; +import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue'; import { calendarDaysBetween, formatJalaliNumeric } from '@/lib/jalali'; import { userAvatarSrc } from '@/lib/userAvatars'; import type { PipelineAccent, PipelineDeal, PipelineUiCopy } from '@/lib/pipeline-board'; @@ -244,6 +245,12 @@ const cardStyle = computed(() => ({ > {{ deal.description }} +
diff --git a/apps/web/src/components/treasury/TreasuryDocPhotoField.vue b/apps/web/src/components/treasury/TreasuryDocPhotoField.vue new file mode 100644 index 0000000..d8fb89e --- /dev/null +++ b/apps/web/src/components/treasury/TreasuryDocPhotoField.vue @@ -0,0 +1,89 @@ + + + diff --git a/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue b/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue new file mode 100644 index 0000000..5a1db5f --- /dev/null +++ b/apps/web/src/components/treasury/TreasuryDocumentsPanel.vue @@ -0,0 +1,626 @@ + + + diff --git a/apps/web/src/components/treasury/TreasuryListPagination.vue b/apps/web/src/components/treasury/TreasuryListPagination.vue new file mode 100644 index 0000000..ab99ec7 --- /dev/null +++ b/apps/web/src/components/treasury/TreasuryListPagination.vue @@ -0,0 +1,30 @@ + + + diff --git a/apps/web/src/components/treasury/TreasuryPartyBalanceTable.vue b/apps/web/src/components/treasury/TreasuryPartyBalanceTable.vue index 4afc541..a7599a4 100644 --- a/apps/web/src/components/treasury/TreasuryPartyBalanceTable.vue +++ b/apps/web/src/components/treasury/TreasuryPartyBalanceTable.vue @@ -7,7 +7,9 @@ import { Typography, } from 'ant-design-vue'; import type { TreasuryPartyBalanceDto } from '@mento/shared'; +import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue'; import { toman } from '@/views/treasury/treasury-format'; +import { useTreasuryListPaging } from '@/views/treasury/useTreasuryListPaging'; import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile'; const props = defineProps<{ @@ -19,6 +21,16 @@ const isMobile = useTreasuryMobile(); const { Text: ATypographyText } = Typography; const AListItem = AList.Item; +const { + page, + pageSize, + pageSizeOptions, + total, + pagedRows, + onPageSizeChange, + showTotal, +} = useTreasuryListPaging(() => props.rows, 'treasury.party-balances'); + const kindLabel: Record = { person: 'مشتری', company: 'شرکت', @@ -58,7 +70,7 @@ function kindOf(record: TreasuryPartyBalanceDto) { @@ -1746,7 +1785,11 @@ onUnmounted(() => { @@ -1847,8 +1890,15 @@ onUnmounted(() => { align-items: center; gap: 0.45rem; min-height: 32px; - position: relative; - z-index: 4; + /* زیر هدر دسکتاپ اپ (۱۶ + control + ۱۶) بماند تا با اسکرول در دسترس باشد */ + position: sticky; + top: calc(16px + var(--control-h) + 16px); + z-index: 15; + margin-inline: -16px; + padding: 0.4rem 16px; + background: color-mix(in srgb, var(--bg, #f8fafc) 92%, transparent); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); } .nav h1 { @@ -1998,6 +2048,10 @@ onUnmounted(() => { margin-top: 0.5rem; } +.claim-balances { + margin-top: 0.65rem; +} + .tag { background: #f0fdfa; color: #0f766e; @@ -2677,8 +2731,35 @@ dd { gap: 0.35rem; } -.note-files a { +.note-files li { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.note-file-name { color: #0f766e; + font-weight: 600; + word-break: break-word; +} + +.note-file-actions { + display: inline-flex; + gap: 0.35rem; +} + +.note-file-btn { + border: 1px solid #99f6e4; + background: #fff; + color: #0f766e; + border-radius: 0.45rem; + font: inherit; + font-size: 0.85rem; + font-weight: 700; + padding: 0.2rem 0.55rem; + cursor: pointer; } .dock { @@ -2716,6 +2797,13 @@ dd { cursor: not-allowed; } +@media (max-width: 900px) { + .nav { + /* زیر هدر موبایل اپ (۰٫۷۵rem + control + ۰٫۷۵rem) */ + top: calc(0.75rem + var(--control-h) + 0.75rem); + } +} + @media (max-width: 899px) { .page { padding-bottom: calc(1rem + var(--mobile-tabbar-h)); diff --git a/apps/web/src/views/ActivityFormView.vue b/apps/web/src/views/ActivityFormView.vue index 8810269..5733000 100644 --- a/apps/web/src/views/ActivityFormView.vue +++ b/apps/web/src/views/ActivityFormView.vue @@ -35,6 +35,7 @@ import ActivityFieldsEditor from '@/components/activities/ActivityFieldsEditor.v import { useActivityPriorities } from '@/lib/activity-priorities'; import { typeColorStyle, useActivityTypes } from '@/lib/activity-types'; import type { + ActivityAccountBalanceDto, ActivityBoardDto, ActivityDto, ActivityImageDto, @@ -51,6 +52,7 @@ import type { PipelineBoardDto, TeamDto, } from '@mento/shared'; +import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue'; const props = withDefaults( defineProps<{ @@ -101,6 +103,8 @@ const keepTypeId = ref(''); const priority = ref('medium'); const description = ref(''); const tagsRaw = ref(''); +/** فقط فعالیت‌های کاریز مطالبات از API می‌آید */ +const accountBalance = ref(null); const PHOTO_TOO_LARGE = 'حجم عکس باید زیر 200 کیلوبایت باشد'; const PHOTO_LIMIT = 8; type PendingPhoto = { localId: string; name: string; dataUrl: string; file: File }; @@ -438,6 +442,7 @@ function resetForm() { priority.value = 'medium'; description.value = ''; tagsRaw.value = ''; + accountBalance.value = null; clearPhotos(); createdActivityId.value = ''; defaultDue(); @@ -515,6 +520,7 @@ async function load() { description.value = data.description ?? ''; needsNote.value = Boolean(data.description?.trim()); tagsRaw.value = (data.tags ?? []).join('، '); + accountBalance.value = data.accountBalance ?? null; splitDue(data.dueAt); durationMinutes.value = data.durationMinutes ?? 30; reminderAt.value = data.reminderAt @@ -1641,6 +1647,12 @@ watch([id, isNew], () => void load(), { immediate: true });
مشتری مرتبط
{{ selectedPerson?.fullName || '—' }}
+
+
مانده حساب
+
+ +
+
وضعیت انجام
diff --git a/apps/web/src/views/ContactsView.vue b/apps/web/src/views/ContactsView.vue index 01b784e..bc9acac 100644 --- a/apps/web/src/views/ContactsView.vue +++ b/apps/web/src/views/ContactsView.vue @@ -1,66 +1,30 @@ + diff --git a/apps/web/src/views/LeadBoardView.vue b/apps/web/src/views/LeadBoardView.vue index 87877f8..21cacf6 100644 --- a/apps/web/src/views/LeadBoardView.vue +++ b/apps/web/src/views/LeadBoardView.vue @@ -17,6 +17,7 @@ import { Space as ASpace, Spin as ASpin, Tag as ATag, + Textarea as ATextarea, Typography, theme, } from 'ant-design-vue'; @@ -62,6 +63,17 @@ const addLost = ref(false); const addUnqualified = ref(false); const deleteTarget = ref(null); const moveConfirm = ref<{ stageIds: string[]; message: string } | null>(null); +const pendingLeadMove = ref<{ + leadId: string; + stageId: string; + position: number; + fromStageName: string; + toStageName: string; + prev: LeadBoardColumnDto[]; + nextColumns: LeadBoardColumnDto[]; +} | null>(null); +const stageMoveReason = ref(''); +const stageMoveError = ref(''); const draggingId = ref(null); const insertAt = ref(null); const bodyEls = new Map(); @@ -201,7 +213,8 @@ async function load() { try { const [board, stageRows] = await Promise.all([ api.get('/leads/board'), - api.get('/leads/stages'), + // بدون شمارش لید روی هر مرحله — total ستون‌ها از خود board می‌آید + api.get('/leads/stages', { params: { counts: '0' } }), ]); columns.value = board.data; stages.value = stageRows.data; @@ -521,7 +534,7 @@ async function onDrop(stageId: string, event: DragEvent, index?: number) { draggingId.value = null; dropStageId.value = null; clearDragUi(); - if (!leadId || moving.value) return; + if (!leadId || moving.value || pendingLeadMove.value) return; const fromCol = columns.value.find((c) => c.leads.some((l) => l.id === leadId), @@ -547,7 +560,7 @@ async function onDrop(stageId: string, event: DragEvent, index?: number) { leads: [...c.leads], })); - columns.value = columns.value.map((c) => { + const nextColumns = columns.value.map((c) => { if (same && c.stage.id === stageId) return { ...c, leads: nextLeads }; if (c.stage.id === fromCol.stage.id) { return { @@ -562,13 +575,66 @@ async function onDrop(stageId: string, event: DragEvent, index?: number) { return c; }); + // جابه‌جایی داخل همان ستون: بدون دلیل + if (same) { + columns.value = nextColumns; + moving.value = true; + error.value = ''; + try { + await api.patch(`/leads/${leadId}/move`, { stageId, position: insertIndex }); + } catch { + columns.value = prev; + error.value = 'جابه‌جایی لید ناموفق بود.'; + } finally { + moving.value = false; + } + return; + } + + // تغییر ستون: اول دلیل، بعد اعمال + stageMoveReason.value = ''; + stageMoveError.value = ''; + pendingLeadMove.value = { + leadId, + stageId, + position: insertIndex, + fromStageName: fromCol.stage.name, + toStageName: target.stage.name, + prev, + nextColumns, + }; +} + +function cancelPendingLeadMove() { + pendingLeadMove.value = null; + stageMoveReason.value = ''; + stageMoveError.value = ''; +} + +async function confirmPendingLeadMove() { + const pending = pendingLeadMove.value; + if (!pending || moving.value) return Promise.reject(); + const reason = stageMoveReason.value.trim(); + if (!reason) { + stageMoveError.value = 'دلیل تغییر وضعیت را بنویسید.'; + return Promise.reject(); + } + columns.value = pending.nextColumns; moving.value = true; error.value = ''; + stageMoveError.value = ''; try { - await api.patch(`/leads/${leadId}/move`, { stageId, position: insertIndex }); - } catch { - columns.value = prev; - error.value = 'جابه‌جایی لید ناموفق بود.'; + await api.patch(`/leads/${pending.leadId}/move`, { + stageId: pending.stageId, + position: pending.position, + reason, + }); + cancelPendingLeadMove(); + } catch (e) { + columns.value = pending.prev; + stageMoveError.value = apiMessage(e, 'جابه‌جایی لید ناموفق بود.'); + error.value = stageMoveError.value; + return Promise.reject(e); } finally { moving.value = false; } @@ -981,6 +1047,31 @@ onMounted(load); > + + + + + انتقال از «{{ pendingLeadMove.fromStageName }}» به «{{ pendingLeadMove.toStageName }}» + + + + +
diff --git a/apps/web/src/views/LeadDetailView.vue b/apps/web/src/views/LeadDetailView.vue index f3a130f..04903a1 100644 --- a/apps/web/src/views/LeadDetailView.vue +++ b/apps/web/src/views/LeadDetailView.vue @@ -22,7 +22,7 @@ import { List as AList, ListItem as AListItem, ListItemMeta as AListItemMeta, - Modal, + Modal as AModal, Row as ARow, Select as ASelect, Space as ASpace, @@ -46,7 +46,13 @@ import { UserAddOutlined, } from '@ant-design/icons-vue'; import { api } from '@/lib/api'; -import { isBirthDateAnswer, leadNoteFileIsImage, parseLeadFormNotes } from '@/lib/lead-form-notes'; +import { + isActivityExperienceAnswer, + isBirthDateAnswer, + leadNoteFileIsImage, + parseLeadFormNotes, +} from '@/lib/lead-form-notes'; +import { ACTIVITY_EXPERIENCE_OPTIONS } from '@mento/shared'; import { formatClockFa, formatJalaliNumeric, @@ -87,6 +93,18 @@ const canBehavior = computed(() => canUseBehavior(auth.user)); const copilotOpen = ref(false); const id = computed(() => String(route.params.id)); + +/** برگشت به همان جایی که از آن آمده‌ایم (فهرست یا مسیر/بورد لیدها). */ +function goBack() { + const back = String((window.history.state as { back?: string | null } | null)?.back ?? ''); + const path = back.split('?')[0]; + if (path === '/leads' || path === '/leads/board') { + router.back(); + return; + } + void router.push({ name: 'leads' }); +} + const loading = ref(false); const busy = ref(false); const error = ref(''); @@ -97,6 +115,9 @@ const users = ref([]); const activities = ref([]); const stageId = ref(''); +const stageMoveOpen = ref(false); +const stageMoveReason = ref(''); +const stageMoveError = ref(''); const assigneeId = ref(''); const callOutcome = ref(''); const callBody = ref(''); @@ -125,9 +146,15 @@ const editForm = ref({ instagram: '', birthDate: '', trade: '', + activityExperience: '' as string, notes: '', }); +const activityExperienceOptions = [ + { value: '', label: '—' }, + ...ACTIVITY_EXPERIENCE_OPTIONS.map((value) => ({ value, label: value })), +]; + function formatDate(value: string | null | undefined) { if (!value) return '—'; try { @@ -145,8 +172,18 @@ const shownBirthDate = computed(() => { if (lead.value?.birthDate) return formatDate(lead.value.birthDate); return formBirthDate.value || '—'; }); +const formActivityExperience = computed( + () => + noteView.value.rows.find((row) => isActivityExperienceAnswer(row.label) && !row.file)?.text ?? + '', +); +const shownActivityExperience = computed( + () => lead.value?.activityExperience || formActivityExperience.value || '—', +); const answerRows = computed(() => - noteView.value.rows.filter((row) => !isBirthDateAnswer(row.label)), + noteView.value.rows.filter( + (row) => !isBirthDateAnswer(row.label) && !isActivityExperienceAnswer(row.label), + ), ); const genderOptions = PERSON_GENDERS.map((key) => ({ @@ -231,6 +268,7 @@ function startEdit() { ? formatLocalDateInput(new Date(lead.value.birthDate)) : '', trade: lead.value.trade ?? '', + activityExperience: lead.value.activityExperience ?? '', notes: lead.value.notes ?? '', }; } @@ -257,6 +295,7 @@ async function saveEdit() { instagram: editForm.value.instagram.trim() || null, birthDate: editForm.value.birthDate || null, trade: editForm.value.trade.trim() || null, + activityExperience: editForm.value.activityExperience.trim() || null, notes: editForm.value.notes.trim() || null, }); okMsg.value = 'لید ویرایش شد.'; @@ -270,18 +309,48 @@ async function saveEdit() { } } -async function changeStage() { +function openStageMove() { if (!stageId.value || stageId.value === lead.value?.stageId) return; + stageMoveReason.value = ''; + stageMoveError.value = ''; + stageMoveOpen.value = true; +} + +function cancelStageMove() { + stageMoveOpen.value = false; + stageMoveReason.value = ''; + stageMoveError.value = ''; + if (lead.value) stageId.value = lead.value.stageId; +} + +async function changeStage() { + if (!stageId.value || stageId.value === lead.value?.stageId) { + return Promise.reject(); + } + const reason = stageMoveReason.value.trim(); + if (!reason) { + stageMoveError.value = 'دلیل تغییر وضعیت را بنویسید.'; + return Promise.reject(); + } busy.value = true; error.value = ''; + stageMoveError.value = ''; try { - await api.patch(`/leads/${id.value}/move`, { stageId: stageId.value }); + await api.patch(`/leads/${id.value}/move`, { + stageId: stageId.value, + reason, + }); okMsg.value = 'وضعیت به‌روز شد.'; message.success(okMsg.value); moreOpen.value = false; + stageMoveOpen.value = false; + stageMoveReason.value = ''; await load(); } catch (e) { - error.value = apiError(e, 'تغییر وضعیت ناموفق بود.'); + const msg = apiError(e, 'تغییر وضعیت ناموفق بود.'); + stageMoveError.value = msg; + error.value = msg; + return Promise.reject(e); } finally { busy.value = false; } @@ -378,7 +447,7 @@ async function setFollowUp() { } function convertLead() { - Modal.confirm({ + AModal.confirm({ title: 'این لید به مشتری تبدیل شود؟', okText: 'تبدیل', cancelText: 'انصراف', @@ -407,7 +476,7 @@ function convertLead() { } function archiveLead() { - Modal.confirm({ + AModal.confirm({ title: 'این لید بایگانی شود؟', okText: 'بایگانی', cancelText: 'انصراف', @@ -438,10 +507,15 @@ function openTel() { const feed = computed(() => { const rows: Array<{ key: string; title: string; by: string; at: string }> = []; for (const ev of lead.value?.events ?? []) { + const body = ev.body?.trim(); rows.push({ key: `ev-${ev.id}`, title: ev.title, - by: ev.body?.trim() || 'توسط سیستم', + by: body + ? ev.type === 'stage_changed' + ? `دلیل: ${body}` + : body + : 'توسط سیستم', at: ev.createdAt, }); } @@ -496,11 +570,9 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow)); - - - - - + + +
{{ lead?.title || 'جزئیات لید' }} @@ -662,6 +734,17 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow)); + + + + + narrowMq?.removeEventListener('change', syncNarrow)); {{ lead.instagram || '—' }} {{ lead.trade || '—' }} + + {{ shownActivityExperience }} + {{ lead.source || '—' }} @@ -866,7 +952,7 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
- {{ ev.body }} + {{ ev.body }} @@ -936,7 +1022,12 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow)); :options="stages.map((s) => ({ value: s.id, label: s.name }))" /> - + اعمال وضعیت @@ -1082,7 +1173,13 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow)); :options="stages.map((s) => ({ value: s.id, label: s.name }))" /> - اعمال وضعیت + + اعمال وضعیت + +
+ + + + + انتقال از «{{ lead?.stageName || '—' }}» به «{{ stages.find((s) => s.id === stageId)?.name || '—' }}» + + + + + + + diff --git a/apps/web/src/views/LeadFormBuilderView.vue b/apps/web/src/views/LeadFormBuilderView.vue index 883a745..93bd1d7 100644 --- a/apps/web/src/views/LeadFormBuilderView.vue +++ b/apps/web/src/views/LeadFormBuilderView.vue @@ -1,8 +1,10 @@ @@ -1428,3 +1322,345 @@ onMounted(load); + + diff --git a/apps/web/src/views/LeadsView.vue b/apps/web/src/views/LeadsView.vue index 6ee10ac..f211eaf 100644 --- a/apps/web/src/views/LeadsView.vue +++ b/apps/web/src/views/LeadsView.vue @@ -30,6 +30,7 @@ import { Spin as ASpin, Table as ATable, Tag as ATag, + Textarea as ATextarea, Typography, Upload as AUpload, message, @@ -83,7 +84,13 @@ import type { PersonGender, PaginatedResponse, } from '@mento/shared'; -import { brand, PERSON_GENDERS, PERSON_GENDER_LABELS, splitPersonHonorific } from '@mento/shared'; +import { + ACTIVITY_EXPERIENCE_OPTIONS, + brand, + PERSON_GENDERS, + PERSON_GENDER_LABELS, + splitPersonHonorific, +} from '@mento/shared'; const { Title: ATypographyTitle, Text: ATypographyText, Paragraph: ATypographyParagraph } = Typography; @@ -113,54 +120,13 @@ const FOLLOW_UP_OPTIONS: Array<{ value: FollowUpKey; label: string }> = [ ]; const UNASSIGNED_VALUE = '__unassigned__'; -/** ردیف آمار صفحه لیدها — ترتیب و نام‌ها مطابق طرح */ -const LEAD_STAT_DEFS: Array<{ - label: string; - /** نام وضعیت‌های متناظر در دیتابیس */ - match: string[]; - tint: StageTint; - slot: 'pair' | 'solo'; -}> = [ - { - label: 'جدید', - match: ['جدید'], - tint: 'amber', - slot: 'pair', - }, - { - label: 'در حال پیگیری', - match: ['در حال پیگیری', 'پیگیری مجدد', 'تماس اولیه', 'تماس موفق'], - tint: 'peach', - slot: 'pair', - }, - { - label: 'مذاکره', - match: ['مذاکره'], - tint: 'mint', - slot: 'solo', - }, - { - label: 'آماده خرید', - match: ['آماده خرید'], - tint: 'violet', - slot: 'solo', - }, - { - label: 'عدم پاسخ', - match: ['عدم پاسخ'], - tint: 'rose', - slot: 'solo', - }, -]; - type LeadStatCard = { key: string; label: string; tint: StageTint; count: number; - /** مرحله اصلی برای فیلتر */ + /** شناسهٔ واقعی ستون برای فیلتر */ stageId: string; - slot: 'pair' | 'solo'; }; const route = useRoute(); @@ -198,6 +164,7 @@ const LEAD_COL_LABELS = [ 'شماره تماس', 'شهر / منطقه', 'منبع لید', + 'سابقه فعالیت', 'تاریخ ثبت', 'وضعیت', 'مسئول', @@ -208,6 +175,9 @@ const assignOpen = ref(false); const stageOpen = ref(false); const assignUserId = ref(''); const bulkStageId = ref(''); +const bulkStageReasonOpen = ref(false); +const bulkStageReason = ref(''); +const bulkStageReasonError = ref(''); const importJob = ref(null); const createOpen = ref(false); const createBusy = ref(false); @@ -263,6 +233,9 @@ const regionFilter = computed(() => const tradeFilter = computed(() => typeof route.query.trade === 'string' ? route.query.trade : '', ); +const activityExperienceFilter = computed(() => + typeof route.query.activityExperience === 'string' ? route.query.activityExperience : '', +); const sourceFilter = computed(() => typeof route.query.source === 'string' ? route.query.source : '', ); @@ -307,6 +280,7 @@ const mobileFilterBadgeCount = computed(() => cityFilter.value, regionFilter.value, tradeFilter.value, + activityExperienceFilter.value, sourceFilter.value, createdFromFilter.value, createdToFilter.value, @@ -320,7 +294,15 @@ const filterBtnLabel = computed(() => : 'فیلتر', ); -type LeadFacetKey = 'assignee' | 'stage' | 'source' | 'followUp' | 'city' | 'region' | 'trade'; +type LeadFacetKey = + | 'assignee' + | 'stage' + | 'source' + | 'followUp' + | 'city' + | 'region' + | 'trade' + | 'activityExperience'; const filterSection = ref( null, ); @@ -338,11 +320,12 @@ function toggleFilterSection(name: NonNullable) { const filterAnchor = ref(null); const filterPopoverMaxHeight = ref('min(70vh, 32rem)'); +const filterPanelPos = ref({ top: 0, left: 8 }); const filterPanelStyle = computed(() => ({ - position: 'absolute' as const, - top: 'calc(100% + 6px)', - insetInlineStart: '0', + position: 'fixed' as const, + top: `${filterPanelPos.value.top}px`, + left: `${filterPanelPos.value.left}px`, zIndex: 1050, width: 'min(20rem, calc(100vw - 1.5rem))', maxHeight: filterPopoverMaxHeight.value, @@ -356,13 +339,25 @@ const filterPanelStyle = computed(() => ({ function placeFilterPopover() { const el = filterAnchor.value; if (!el) return; - const space = Math.floor(window.innerHeight - el.getBoundingClientRect().bottom - 12); + const rect = el.getBoundingClientRect(); + const space = Math.floor(window.innerHeight - rect.bottom - 12); filterPopoverMaxHeight.value = `${Math.max(220, space)}px`; + // همان رفتار absolute با inset-inline-end:0 (RTL): لبهٔ چپ پنل = لبهٔ چپ دکمه + const panelW = Math.min(20 * 16, window.innerWidth - 24); + let left = rect.left; + if (left + panelW > window.innerWidth - 8) { + left = window.innerWidth - panelW - 8; + } + filterPanelPos.value = { + top: rect.bottom + 6, + left: Math.max(8, Math.round(left)), + }; } function onFilterDocPointer(event: Event) { const target = event.target; if (!(target instanceof Node)) return; + if (target instanceof Element && target.closest('[data-lead-filter]')) return; if (filterAnchor.value?.contains(target)) return; if (document.getElementById('jalali-picker')?.contains(target)) return; moreFiltersOpen.value = false; @@ -492,6 +487,18 @@ const textFacets = computed(() => [ ...tradeOptions.value.map((item) => ({ value: item, label: item })), ], }, + { + key: 'activityExperience' as const, + label: 'سابقه فعالیت', + value: activityExperienceFilter.value || 'همه', + active: Boolean(activityExperienceFilter.value), + current: activityExperienceFilter.value, + searchable: false, + options: [ + { value: '', label: 'همه' }, + ...ACTIVITY_EXPERIENCE_OPTIONS.map((item) => ({ value: item, label: item })), + ], + }, ]); function visibleFacetOptions(options: Array<{ value: string; label: string }>) { @@ -516,6 +523,7 @@ function pickFacet(key: LeadFacetKey, value: string) { else if (key === 'city') setCityFilter(next); else if (key === 'region') setRegionFilter(next); else if (key === 'trade') setTradeFilter(next); + else if (key === 'activityExperience') setActivityExperienceFilter(next); filterSection.value = null; } @@ -552,23 +560,15 @@ const sortLabels: Record = { last_contact: 'آخرین تماس', }; +/** چیپ‌های فیلتر = ستون‌های واقعی سازمان (نه نام‌های ثابت قدیمی) */ const stageCards = computed((): LeadStatCard[] => { - return LEAD_STAT_DEFS.map((def) => { - const matched = stages.value.filter((s) => - def.match.some((name) => s.name.trim() === name), - ); - const count = matched.reduce((sum, s) => sum + (s.leadCount ?? 0), 0); - const primary = - matched.find((s) => s.name.trim() === def.match[0]) ?? matched[0]; - return { - key: def.label, - label: def.label, - tint: def.tint, - count, - stageId: primary?.id ?? '', - slot: def.slot, - }; - }); + return stages.value.map((s) => ({ + key: s.id, + label: s.name, + tint: stageTint(s.color), + count: s.leadCount ?? 0, + stageId: s.id, + })); }); const totalLeadsCount = computed(() => { @@ -576,22 +576,24 @@ const totalLeadsCount = computed(() => { return stages.value.reduce((sum, s) => sum + (s.leadCount ?? 0), 0) || total.value; }); +/** گزینه‌های سلکت موبایل — برچسب + تعداد */ +const stageFilterOptions = computed(() => [ + { + value: '', + label: `همه لیدها (${formatCount(totalLeadsCount.value)})`, + }, + ...stageCards.value.map((card) => ({ + value: card.stageId, + label: `${card.label} (${formatCount(card.count)})`, + })), +]); + function isStatActive(card: LeadStatCard) { - if (!card.stageId || !stageId.value) return false; - if (stageId.value === card.stageId) return true; - const def = LEAD_STAT_DEFS.find((d) => d.label === card.label); - if (!def) return false; - const matchedIds = stages.value - .filter((s) => def.match.some((name) => s.name.trim() === name)) - .map((s) => s.id); - return matchedIds.includes(stageId.value); + return Boolean(card.stageId && stageId.value === card.stageId); } function selectStatCard(card: LeadStatCard) { - if (!card.stageId) { - setStageFilter(''); - return; - } + if (!card.stageId) return; setStageFilter(isStatActive(card) ? '' : card.stageId); } @@ -838,6 +840,10 @@ function setTradeFilter(value: string) { patchQuery({ trade: value || undefined, page: undefined }); } +function setActivityExperienceFilter(value: string) { + patchQuery({ activityExperience: value || undefined, page: undefined }); +} + function setSourceFilter(value: string) { patchQuery({ source: value || undefined, page: undefined }); } @@ -867,6 +873,7 @@ function clearMoreFilters() { city: undefined, region: undefined, trade: undefined, + activityExperience: undefined, source: undefined, createdFrom: undefined, createdTo: undefined, @@ -994,6 +1001,7 @@ async function load() { city: cityFilter.value || undefined, region: regionFilter.value || undefined, trade: tradeFilter.value || undefined, + activityExperience: activityExperienceFilter.value || undefined, source: sourceFilter.value || undefined, unassigned: unassigned.value ? '1' : undefined, archived: archivedFilter.value ? '1' : undefined, @@ -1306,21 +1314,44 @@ async function assignSelected() { } } -async function bulkStageSelected() { +function openBulkStageReason() { if (!bulkStageId.value || !selectedIds.value.length) return; + bulkStageReason.value = ''; + bulkStageReasonError.value = ''; + bulkStageReasonOpen.value = true; +} + +function cancelBulkStageReason() { + bulkStageReasonOpen.value = false; + bulkStageReason.value = ''; + bulkStageReasonError.value = ''; +} + +async function bulkStageSelected() { + if (!bulkStageId.value || !selectedIds.value.length) return Promise.reject(); + const reason = bulkStageReason.value.trim(); + if (!reason) { + bulkStageReasonError.value = 'دلیل تغییر وضعیت را بنویسید.'; + return Promise.reject(); + } busy.value = true; error.value = ''; + bulkStageReasonError.value = ''; try { await api.post('/leads/bulk-stage', { leadIds: selectedIds.value, stageId: bulkStageId.value, + reason, }); okMsg.value = `وضعیت ${toFaDigits(selectedIds.value.length)} لید به‌روز شد.`; selected.value = new Set(); stageOpen.value = false; + cancelBulkStageReason(); await load(); - } catch { - error.value = 'تغییر وضعیت گروهی ناموفق بود.'; + } catch (e) { + bulkStageReasonError.value = 'تغییر وضعیت گروهی ناموفق بود.'; + error.value = bulkStageReasonError.value; + return Promise.reject(e); } finally { busy.value = false; } @@ -1484,6 +1515,7 @@ watch( route.query.city, route.query.region, route.query.trade, + route.query.activityExperience, route.query.source, route.query.unassigned, route.query.archived, @@ -1528,6 +1560,11 @@ const tableColumns = computed>(() => { { title: 'شماره تماس', key: 'mobile', dataIndex: 'mobile' }, { title: 'شهر / منطقه', key: 'city' }, { title: 'منبع لید', key: 'source', dataIndex: 'source' }, + { + title: 'سابقه فعالیت', + key: 'activityExperience', + dataIndex: 'activityExperience', + }, { title: 'تاریخ ثبت', key: 'createdAt', dataIndex: 'createdAt' }, { title: 'وضعیت', key: 'stage', dataIndex: 'stageName' }, { title: 'مسئول', key: 'assignee', dataIndex: 'assigneeName' }, @@ -1559,14 +1596,36 @@ onBeforeUnmount(() => { بایگانی @@ -2112,7 +2238,10 @@ onBeforeUnmount(() => { :pagination="false" :row-key="(r: LeadDto) => r.id" :scroll="{ x: 1100 }" - :custom-row="(record: LeadDto) => ({ onClick: () => goDetail(record.id) })" + :custom-row="(record: LeadDto) => ({ + onClick: () => goDetail(record.id), + style: { cursor: 'pointer' }, + })" > + + + + + انتقال {{ toFaDigits(selectedIds.length) }} لید به + «{{ stages.find((s) => s.id === bulkStageId)?.name || '—' }}» + + + + + diff --git a/apps/web/src/views/PersonFormView.vue b/apps/web/src/views/PersonFormView.vue index c5651d6..8816764 100644 --- a/apps/web/src/views/PersonFormView.vue +++ b/apps/web/src/views/PersonFormView.vue @@ -36,7 +36,12 @@ import { } from '@ant-design/icons-vue'; import { api } from '@/lib/api'; import type { CompanyDto, CreatePersonRequest, PersonDto, PersonGender, PersonMood } from '@mento/shared'; -import { PERSON_GENDER_LABELS, PERSON_GENDERS, splitPersonHonorific } from '@mento/shared'; +import { + ACTIVITY_EXPERIENCE_OPTIONS, + PERSON_GENDER_LABELS, + PERSON_GENDERS, + splitPersonHonorific, +} from '@mento/shared'; import { PERSON_MOOD_LABELS, PERSON_MOODS } from '@/lib/person-mood'; import { formatLocalDateInput, toFaDigits } from '@/lib/jalali'; import JalaliDateInput from '@/components/JalaliDateInput.vue'; @@ -97,6 +102,7 @@ const website = ref(''); const instagram = ref(''); const birthDate = ref(''); const referrer = ref(''); +const activityExperience = ref(''); const nationalId = ref(''); const city = ref(''); const rasteh = ref(''); @@ -279,6 +285,7 @@ function fill(p: PersonDto) { instagram.value = p.instagram ?? ''; birthDate.value = p.birthDate ? formatLocalDateInput(new Date(p.birthDate)) : ''; referrer.value = p.referrer ?? ''; + activityExperience.value = p.activityExperience ?? ''; addresses.value = p.addresses?.length ? [...p.addresses] : ['']; notes.value = p.notes ?? ''; tagsRaw.value = (p.tags ?? []).join('، '); @@ -382,6 +389,7 @@ function payload(): CreatePersonRequest { instagram: instagram.value || undefined, birthDate: birthDate.value || null, referrer: referrer.value || undefined, + activityExperience: activityExperience.value || null, addresses: addresses.value.map((a) => a.trim()).filter(Boolean), notes: notes.value || undefined, tags: parseTags(tagsRaw.value), @@ -570,6 +578,20 @@ onMounted(load); + + + + + diff --git a/apps/web/src/views/PersonProfileView.vue b/apps/web/src/views/PersonProfileView.vue index 190c090..65aca52 100644 --- a/apps/web/src/views/PersonProfileView.vue +++ b/apps/web/src/views/PersonProfileView.vue @@ -454,6 +454,7 @@ const infoEmpty = computed(() => { !p.position && !p.website && !p.instagram && + !p.activityExperience && !p.birthDate && !p.referrer && !nationalIdLabel.value && @@ -829,6 +830,10 @@ watch(() => route.query.tab, readTab, { immediate: true });
اینستاگرام
{{ person.instagram }}
+
+
سابقه فعالیت
+
{{ person.activityExperience }}
+
آدرس‌ها
@@ -1145,6 +1150,7 @@ watch(() => route.query.tab, readTab, { immediate: true });
نام قبلی
{{ person.previousFullName || '—' }}
وب‌سایت
{{ person.website || '—' }}
اینستاگرام
{{ person.instagram || '—' }}
+
سابقه فعالیت
{{ person.activityExperience || '—' }}
معرف
{{ person.referrer || '—' }}
کد ملی
diff --git a/apps/web/src/views/ReportsView.vue b/apps/web/src/views/ReportsView.vue index e5d1044..8c03712 100644 --- a/apps/web/src/views/ReportsView.vue +++ b/apps/web/src/views/ReportsView.vue @@ -1,10 +1,10 @@