From de23e4d50569c5839dc6624ba977c7e2482c773e Mon Sep 17 00:00:00 2001 From: Mahdi Date: Tue, 17 Nov 2026 21:24:15 +0330 Subject: [PATCH] Add account balance claims board with opt-in module and range settings. EOF Co-authored-by: Cursor --- .../migration.sql | 22 + apps/api/prisma/schema.prisma | 9 + .../account-balance-settings.service.ts | 83 ++++ .../account-balances.controller.ts | 41 ++ .../account-balances.module.ts | 17 + .../balance-claims.scheduler.ts | 61 +++ .../balance-claims.service.ts | 411 ++++++++++++++++++ apps/api/src/account-balances/dto.ts | 35 ++ .../src/activities/activity-stages.service.ts | 70 ++- apps/api/src/app.module.ts | 2 + .../customer-groups.service.ts | 21 +- apps/web/src/lib/nav-hubs.ts | 9 + apps/web/src/router/index.ts | 16 + .../src/views/AccountBalanceSettingsView.vue | 252 +++++++++++ apps/web/src/views/ActivitiesView.vue | 11 +- packages/shared/src/index.ts | 116 ++++- 16 files changed, 1162 insertions(+), 14 deletions(-) create mode 100644 apps/api/prisma/migrations/20261117190000_account_balances/migration.sql create mode 100644 apps/api/src/account-balances/account-balance-settings.service.ts create mode 100644 apps/api/src/account-balances/account-balances.controller.ts create mode 100644 apps/api/src/account-balances/account-balances.module.ts create mode 100644 apps/api/src/account-balances/balance-claims.scheduler.ts create mode 100644 apps/api/src/account-balances/balance-claims.service.ts create mode 100644 apps/api/src/account-balances/dto.ts create mode 100644 apps/web/src/views/AccountBalanceSettingsView.vue 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/schema.prisma b/apps/api/prisma/schema.prisma index 0750357..ad4d6f7 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 @@ -813,6 +819,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 +829,7 @@ model ActivityBoard { updatedAt DateTime @updatedAt @@unique([organizationId, name]) + @@unique([organizationId, systemKey]) @@index([organizationId, position]) } 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..b725638 --- /dev/null +++ b/apps/api/src/account-balances/account-balance-settings.service.ts @@ -0,0 +1,83 @@ +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} معتبر نیست.`); + 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..ef2a0a5 --- /dev/null +++ b/apps/api/src/account-balances/account-balances.controller.ts @@ -0,0 +1,41 @@ +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 { 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') + async evaluate(@CurrentUser() user: Actor) { + await this.claims.evaluateOrganization(user.organizationId); + return { ok: true }; + } +} 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..d83ea53 --- /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.evaluateOrganization(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..2c4b10e --- /dev/null +++ b/apps/api/src/account-balances/balance-claims.service.ts @@ -0,0 +1,411 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { + ACCOUNT_BALANCE_CLAIMS_TAG, + ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS, + accountBalanceInRange, + DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE, + parseAccountBalanceSettings, + parseAccountBalanceWeightFields, + type AccountBalanceSettingsDto, +} from '@mento/shared'; +import { Prisma } from '@prisma/client'; +import { PrismaService } from '../prisma/prisma.service'; +import { ActivityTypesService } from '../activities/activity-types.service'; +import { TahesabBalanceService } from '../integrations/tahesab/balance.service'; + +const BOARD_NAME = 'مطالبات'; +const FOLLOW_UP_TYPE_NAME = 'پیگیری'; + +type PersonClaimContext = { + personId: string; + fullName: string; + connectionId: string; + assigneeId: string; +}; + +@Injectable() +export class BalanceClaimsService { + private readonly logger = new Logger(BalanceClaimsService.name); + + constructor( + private readonly prisma: PrismaService, + private readonly types: ActivityTypesService, + private readonly balances: TahesabBalanceService, + ) {} + + async ensureFollowUpType(organizationId: string) { + await this.types.ensureDefaults(organizationId); + const existing = await this.prisma.activityTypeDef.findFirst({ + where: { organizationId, name: FOLLOW_UP_TYPE_NAME }, + select: { id: true, baseType: true }, + }); + if (existing) return existing; + const max = await this.prisma.activityTypeDef.aggregate({ + where: { organizationId }, + _max: { position: true }, + }); + return this.prisma.activityTypeDef.create({ + data: { + organizationId, + name: FOLLOW_UP_TYPE_NAME, + baseType: 'call', + icon: 'bell', + color: 'orange', + position: (max._max.position ?? 0) + 1, + isSystem: false, + fields: [ + { + key: 'followup_reason', + label: 'دلیل پیگیری', + type: 'select', + options: ['پیش‌فاکتور', 'پرداخت', 'ارسال کالا', 'پشتیبانی', 'تمدید قرارداد', 'سایر'], + }, + { key: 'followup_result', label: 'نتیجهٔ پیگیری', type: 'textarea' }, + { key: 'followup_next', label: 'تاریخ پیگیری بعدی', type: 'date' }, + ] as Prisma.InputJsonValue, + }, + select: { id: true, baseType: true }, + }); + } + + async ensureBoard(organizationId: string, firstStageName?: string) { + const stageName = (firstStageName ?? DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE).trim() || + DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE; + + let board = await this.prisma.activityBoard.findFirst({ + where: { organizationId, systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS }, + select: { id: true, name: true }, + }); + + if (!board) { + const byName = await this.prisma.activityBoard.findFirst({ + where: { organizationId, name: BOARD_NAME }, + select: { id: true, name: true }, + }); + if (byName) { + board = await this.prisma.activityBoard.update({ + where: { id: byName.id }, + data: { systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS }, + select: { id: true, name: true }, + }); + } + } + + if (!board) { + const max = await this.prisma.activityBoard.aggregate({ + where: { organizationId }, + _max: { position: true }, + }); + board = await this.prisma.activityBoard.create({ + data: { + organizationId, + name: BOARD_NAME, + systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS, + position: (max._max.position ?? 0) + 1, + isDefault: false, + }, + select: { id: true, name: true }, + }); + } + + await this.ensureStages(organizationId, board.id, stageName); + // اعضای خالی = برای همه باز؛ برای مطالبات حداقل یک عضو ساختگی نمی‌گذاریم — + // دسترسی در assertCanAccessBoard با systemKey کنترل می‌شود. + return board; + } + + private async ensureStages(organizationId: string, boardId: string, firstStageName: string) { + const stages = await this.prisma.activityStage.findMany({ + where: { boardId }, + orderBy: [{ position: 'asc' }, { createdAt: 'asc' }], + select: { id: true, name: true, kind: true, position: true }, + }); + + if (!stages.length) { + await this.prisma.activityStage.createMany({ + data: [ + { + organizationId, + boardId, + name: firstStageName, + color: 'orange', + kind: 'open', + position: 0, + }, + { + organizationId, + boardId, + name: 'در حال انجام', + color: 'blue', + kind: 'open', + position: 1, + }, + { + organizationId, + boardId, + name: 'انجام‌شده', + color: 'green', + kind: 'done', + position: 2, + }, + { + organizationId, + boardId, + name: 'لغو شده', + color: 'rose', + kind: 'canceled', + position: 3, + }, + ], + skipDuplicates: true, + }); + return; + } + + const firstOpen = stages.find((s) => s.kind === 'open') ?? stages[0]; + if (firstOpen && firstOpen.name !== firstStageName) { + const clash = stages.some((s) => s.id !== firstOpen.id && s.name === firstStageName); + if (!clash) { + await this.prisma.activityStage.update({ + where: { id: firstOpen.id }, + data: { name: firstStageName }, + }); + } + } + } + + async evaluateAll() { + const orgs = await this.prisma.organization.findMany({ + where: { + isActive: true, + enabledModules: { has: 'account_balances' }, + accountingConnections: { some: { provider: 'tahesab', enabled: true } }, + }, + select: { id: true, name: true }, + }); + for (const org of orgs) { + try { + await this.evaluateOrganization(org.id); + } catch (err) { + this.logger.warn( + `ارزیابی مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`, + ); + } + } + } + + async evaluateOrganization(organizationId: string) { + const org = await this.prisma.organization.findUnique({ + where: { id: organizationId }, + select: { enabledModules: true, accountBalanceSettings: true }, + }); + if (!org?.enabledModules.includes('account_balances')) return; + + const settings = parseAccountBalanceSettings(org.accountBalanceSettings); + const hasAnyRange = + Boolean(settings.rial) || Object.keys(settings.weights).length > 0; + if (!hasAnyRange) return; + + const board = await this.ensureBoard(organizationId, settings.firstStageName); + const typeDef = await this.ensureFollowUpType(organizationId); + const stages = await this.prisma.activityStage.findMany({ + where: { boardId: board.id }, + orderBy: [{ position: 'asc' }, { createdAt: 'asc' }], + select: { id: true, kind: true }, + }); + const openStageId = stages.find((s) => s.kind === 'open')?.id; + const canceledStageId = stages.find((s) => s.kind === 'canceled')?.id; + if (!openStageId || !canceledStageId) return; + + const candidates = await this.loadCandidates(organizationId); + for (const person of candidates) { + try { + await this.syncPerson({ + organizationId, + person, + settings, + boardId: board.id, + openStageId, + canceledStageId, + typeDefId: typeDef.id, + baseType: typeDef.baseType, + }); + } catch (err) { + this.logger.warn( + `مانده/مطالبه شخص ${person.personId}: ${err instanceof Error ? err.message : err}`, + ); + } + } + } + + private async loadCandidates(organizationId: string): Promise { + 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(); + const orderedLinks = [...links].sort((a, b) => { + if (a.personId !== b.personId) return a.personId.localeCompare(b.personId); + if (a.connection.isDefault !== b.connection.isDefault) return a.connection.isDefault ? -1 : 1; + return a.linkedAt.getTime() - b.linkedAt.getTime(); + }); + for (const link of orderedLinks) { + if (seen.has(link.personId)) continue; + const groups = [...link.person.groupLinks] + .map((g) => g.group) + .sort((a, b) => a.position - b.position || a.name.localeCompare(b.name, 'fa')); + let assigneeId: string | null = null; + for (const group of groups) { + const validAssigneeIds = new Set(group.assignees.map((a) => a.id)); + const ordered = + group.assigneeIds.length > 0 + ? group.assigneeIds.filter((id) => validAssigneeIds.has(id)) + : group.assignees.map((a) => a.id); + if (ordered.length) { + assigneeId = ordered[0]!; + break; + } + } + if (!assigneeId) continue; + seen.add(link.personId); + out.push({ + personId: link.person.id, + fullName: `${link.person.firstName} ${link.person.lastName}`.trim(), + connectionId: link.connectionId, + assigneeId, + }); + } + return out; + } + + private async syncPerson(input: { + organizationId: string; + person: PersonClaimContext; + settings: AccountBalanceSettingsDto; + boardId: string; + openStageId: string; + canceledStageId: string; + typeDefId: string; + baseType: 'call' | 'meeting' | 'task' | 'note'; + }) { + const assets = await this.balances.getAssets( + input.organizationId, + input.person.personId, + input.person.connectionId, + ); + const matched = this.matchesAnyRange(assets, input.settings); + + const existing = await this.prisma.activity.findFirst({ + where: { + organizationId: input.organizationId, + boardId: input.boardId, + personId: input.person.personId, + tags: { has: ACCOUNT_BALANCE_CLAIMS_TAG }, + }, + orderBy: { createdAt: 'desc' }, + select: { + id: true, + status: true, + assigneeId: true, + }, + }); + + if (matched) { + if (existing) { + await this.prisma.activity.update({ + where: { id: existing.id }, + data: { + status: 'open', + stageId: input.openStageId, + completedAt: null, + assigneeId: input.person.assigneeId, + assignees: { set: [{ id: input.person.assigneeId }] }, + title: `مطالبه: ${input.person.fullName}`, + }, + }); + return; + } + await this.prisma.activity.create({ + data: { + organizationId: input.organizationId, + boardId: input.boardId, + stageId: input.openStageId, + status: 'open', + title: `مطالبه: ${input.person.fullName}`, + type: input.baseType, + typeDefId: input.typeDefId, + personId: input.person.personId, + assigneeId: input.person.assigneeId, + assignees: { connect: [{ id: input.person.assigneeId }] }, + tags: [ACCOUNT_BALANCE_CLAIMS_TAG], + editPolicy: 'assignees', + completionMode: 'any', + completedByIds: [], + createdById: input.person.assigneeId, + }, + }); + return; + } + + if (existing && existing.status !== 'canceled') { + await this.prisma.activity.update({ + where: { id: existing.id }, + data: { + status: 'canceled', + stageId: input.canceledStageId, + completedAt: new Date(), + }, + }); + } + } + + private matchesAnyRange( + assets: { + rialBalance: number | null; + goldBalance: number | null; + mandehFields?: Array<{ key: string; value: string | null }>; + }, + settings: AccountBalanceSettingsDto, + ): boolean { + if (accountBalanceInRange(assets.rialBalance, settings.rial)) return true; + + const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields); + for (const [key, range] of Object.entries(settings.weights)) { + const value = + fieldMap[key] ?? + (key === 'MandeyeVazni' ? assets.goldBalance : null) ?? + null; + if (accountBalanceInRange(value, range)) return true; + } + return false; + } +} diff --git a/apps/api/src/account-balances/dto.ts b/apps/api/src/account-balances/dto.ts new file mode 100644 index 0000000..bcabb04 --- /dev/null +++ b/apps/api/src/account-balances/dto.ts @@ -0,0 +1,35 @@ +import { Type } from 'class-transformer'; +import { + IsNumber, + IsObject, + IsOptional, + IsString, + MaxLength, + ValidateIf, + ValidateNested, +} from 'class-validator'; + +export class AccountBalanceRangeBody { + @IsNumber() + min!: number; + + @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; +} 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/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/web/src/lib/nav-hubs.ts b/apps/web/src/lib/nav-hubs.ts index 504026d..14eb809 100644 --- a/apps/web/src/lib/nav-hubs.ts +++ b/apps/web/src/lib/nav-hubs.ts @@ -101,6 +101,15 @@ export const NAV_HUBS: NavHubDef[] = [ tint: 'violet', module: 'customers', }, + { + to: '/settings/account-balances', + title: 'تعیین محدوده مانده', + desc: 'بازه مانده مالی و وزنی برای کاریز مطالبات', + icon: 'dollar', + tint: 'amber', + admin: true, + module: 'account_balances', + }, ], }, { diff --git a/apps/web/src/router/index.ts b/apps/web/src/router/index.ts index 8446b8a..97f365d 100644 --- a/apps/web/src/router/index.ts +++ b/apps/web/src/router/index.ts @@ -575,6 +575,15 @@ export const router = createRouter({ component: () => import('@/views/TahesabSettingsView.vue'), meta: { roles: ['owner', 'admin'] as UserRole[] }, }, + { + path: 'settings/account-balances', + name: 'account-balance-settings', + component: () => import('@/views/AccountBalanceSettingsView.vue'), + meta: { + roles: ['owner', 'admin'] as UserRole[], + module: 'account_balances', + }, + }, { path: 'settings/woocommerce', name: 'woocommerce-settings', @@ -668,6 +677,13 @@ router.beforeEach((to) => { const modules = auth.user?.enabledModules; if (modules && !modules.includes('tahesab')) return { name: 'home' }; } + if ( + to.name === 'account-balance-settings' || + String(to.path).startsWith('/settings/account-balances') + ) { + const modules = auth.user?.enabledModules; + if (modules && !modules.includes('account_balances')) return { name: 'home' }; + } if (!canOpenPath(auth.user?.role, auth.user?.permissions, String(to.path))) { return { name: 'home' }; } diff --git a/apps/web/src/views/AccountBalanceSettingsView.vue b/apps/web/src/views/AccountBalanceSettingsView.vue new file mode 100644 index 0000000..ad60ba5 --- /dev/null +++ b/apps/web/src/views/AccountBalanceSettingsView.vue @@ -0,0 +1,252 @@ + + + + + diff --git a/apps/web/src/views/ActivitiesView.vue b/apps/web/src/views/ActivitiesView.vue index 8f0b7d8..f5d258f 100644 --- a/apps/web/src/views/ActivitiesView.vue +++ b/apps/web/src/views/ActivitiesView.vue @@ -549,7 +549,7 @@ function openCreateBoard() { } function openEditBoard() { - if (!currentBoard.value) return; + if (!currentBoard.value || currentBoard.value.systemKey) return; boardMemberQuery.value = ''; boardModal.value = { mode: 'edit', @@ -1562,7 +1562,12 @@ onUnmounted(() => { گروه جدید - @@ -2111,7 +2116,7 @@ onUnmounted(() => { = { reports: "گزارش‌ها", notes: "یادداشت‌ها", tahesab: "ته‌حساب (اتصال و گزارش فروش)", + account_balances: "مانده حساب", custom_fields: "فیلدهای سفارشی", currencies: "ارزها", team_settings: "تیم و تنظیمات سازمان", @@ -266,7 +269,7 @@ export const ORG_MODULE_GROUPS: Array<{ title: string; keys: OrgModuleKey[]; }> = [ - { title: "مشتریان", keys: ["customers"] }, + { title: "مشتریان", keys: ["customers", "account_balances"] }, { title: "لیدها", keys: ["leads", "lead_forms"] }, { title: "فروش", @@ -329,6 +332,7 @@ export function isOrgModuleKey(value: string): value is OrgModuleKey { export const OPT_IN_ORG_MODULES: OrgModuleKey[] = [ "workflow_automations_advanced", "prior_data_archive", + "account_balances", ]; export function defaultEnabledModules(): OrgModuleKey[] { @@ -1355,8 +1359,10 @@ export interface CustomerGroupDto { /** گروه اصلی؛ خالی یعنی خودش اصلی است */ parentId?: string | null; parentName?: string | null; - /** مسئولان گروه (اختیاری) */ + /** مسئولان گروه به ترتیب انتخاب در فرم */ assignees: CustomerGroupAssigneeDto[]; + /** شناسهٔ مسئولان به همان ترتیب انتخاب (منبع ترتیب) */ + assigneeIds?: string[]; } export interface CreateCustomerGroupRequest { @@ -1979,6 +1985,9 @@ export const ACTIVITY_STAGE_KIND_LABELS: Record = { canceled: "لغو شده", }; +/** کلید سیستمی گروه فعالیت مطالبات مانده حساب */ +export const ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS = "balance_claims"; + /** گروه فعالیت (مثل مسیر فروش): هر گروه ستون‌های خودش را دارد */ export interface ActivityBoardDto { id: string; @@ -1987,6 +1996,8 @@ export interface ActivityBoardDto { position: number; /** خالی = گروه برای همهٔ اعضای محیط باز است */ memberIds: string[]; + /** مثلاً balance_claims — گروه سیستمی غیرقابل حذف/تغییر نام */ + systemKey?: string | null; } export interface CreateActivityBoardRequest { @@ -4819,6 +4830,107 @@ export interface PersonAssetsDto { fetchedAt: string; } +/** تگ فعالیت‌های ساخته‌شده از مانده حساب */ +export const ACCOUNT_BALANCE_CLAIMS_TAG = "balance_claims"; + +export const ACCOUNT_BALANCE_WEIGHT_KEYS = [ + "MandeyeVazni", + "MandeyeVazniNoghre", +] as const; + +export type AccountBalanceWeightKey = (typeof ACCOUNT_BALANCE_WEIGHT_KEYS)[number] | string; + +export const ACCOUNT_BALANCE_WEIGHT_LABELS: Record = { + MandeyeVazni: "مانده وزنی (طلا)", + MandeyeVazniNoghre: "مانده وزنی نقره", +}; + +export interface AccountBalanceRangeDto { + min: number; + max: number; +} + +export interface AccountBalanceSettingsDto { + /** عنوان ستون اول کاریز مطالبات */ + firstStageName: string; + /** بازه مانده مالی؛ null = خاموش */ + rial: AccountBalanceRangeDto | null; + /** بازه به‌ازای هر کلید مانده وزنی؛ نبود کلید = خاموش */ + weights: Record; +} + +export interface UpdateAccountBalanceSettingsRequest { + firstStageName?: string; + rial?: AccountBalanceRangeDto | null; + weights?: Record; +} + +export type UpdateAccountBalanceSettingsDto = UpdateAccountBalanceSettingsRequest; + +export const DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE = "مطالبه مشتریان"; + +export function defaultAccountBalanceSettings(): AccountBalanceSettingsDto { + return { + firstStageName: DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE, + rial: null, + weights: {}, + }; +} + +export function parseAccountBalanceRange(raw: unknown): AccountBalanceRangeDto | null { + if (!raw || typeof raw !== "object") return null; + const min = Number((raw as { min?: unknown }).min); + const max = Number((raw as { max?: unknown }).max); + if (!Number.isFinite(min) || !Number.isFinite(max)) return null; + return { min, max: Math.max(min, max) }; +} + +export function parseAccountBalanceSettings(raw: unknown): AccountBalanceSettingsDto { + const base = defaultAccountBalanceSettings(); + if (!raw || typeof raw !== "object") return base; + const obj = raw as Record; + const firstStageName = + typeof obj.firstStageName === "string" && obj.firstStageName.trim() + ? obj.firstStageName.trim().slice(0, 80) + : base.firstStageName; + const rial = parseAccountBalanceRange(obj.rial); + const weights: Record = {}; + if (obj.weights && typeof obj.weights === "object") { + for (const [key, value] of Object.entries(obj.weights as Record)) { + const range = parseAccountBalanceRange(value); + if (range) weights[key] = range; + } + } + return { firstStageName, rial, weights }; +} + +export function accountBalanceInRange( + value: number | null | undefined, + range: AccountBalanceRangeDto | null | undefined, +): boolean { + if (!range || value == null || !Number.isFinite(value)) return false; + return value >= range.min && value <= range.max; +} + +export function parseAccountBalanceNumber(raw: unknown): number | null { + if (raw == null || raw === "") return null; + const n = Number(String(raw).replace(/,/g, "").trim()); + return Number.isFinite(n) ? n : null; +} + +export function parseAccountBalanceWeightFields( + fields: Array<{ key: string; value: unknown }> | null | undefined, +): Record { + const out: Record = {}; + for (const field of fields ?? []) { + const key = String(field.key ?? "").trim(); + if (!key) continue; + const value = parseAccountBalanceNumber(field.value); + if (value != null) out[key] = value; + } + return out; +} + // —— پیام خودکار (جدا از اتوماسیون گردش کار) —— export type MessageAutomationTrigger =