Add account balance claims board with opt-in module and range settings.

EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-17 21:24:15 +03:30
co-authored by Cursor
parent 634af8a653
commit de23e4d505
16 changed files with 1162 additions and 14 deletions
@@ -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");
+9
View File
@@ -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])
}
@@ -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<AccountBalanceSettingsDto> {
const row = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { accountBalanceSettings: true },
});
return parseAccountBalanceSettings(row?.accountBalanceSettings);
}
async update(
organizationId: string,
dto: UpdateAccountBalanceSettingsRequest,
): Promise<AccountBalanceSettingsDto> {
const current = await this.get(organizationId);
const next: AccountBalanceSettingsDto = {
firstStageName:
dto.firstStageName !== undefined
? this.cleanStageName(dto.firstStageName)
: current.firstStageName,
rial:
dto.rial === undefined
? current.rial
: dto.rial === null
? null
: this.requireRange(dto.rial, 'بازه مالی'),
weights: { ...current.weights },
};
if (dto.weights) {
for (const [key, value] of Object.entries(dto.weights)) {
const cleanKey = key.trim();
if (!cleanKey) continue;
if (value === null) {
delete next.weights[cleanKey];
continue;
}
next.weights[cleanKey] = this.requireRange(value, `بازه ${cleanKey}`);
}
}
await this.prisma.organization.update({
where: { id: organizationId },
data: {
accountBalanceSettings: next as unknown as Prisma.InputJsonValue,
},
});
await this.claims.ensureBoard(organizationId, next.firstStageName);
return next;
}
private cleanStageName(raw: string) {
const name = raw.trim().slice(0, 80);
if (!name) return DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
return name;
}
private requireRange(raw: AccountBalanceRangeDto, label: string): AccountBalanceRangeDto {
const range = parseAccountBalanceRange(raw);
if (!range) throw new BadRequestException(`${label} معتبر نیست.`);
return range;
}
}
@@ -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 };
}
}
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { BillingModule } from '../billing/billing.module';
import { ActivitiesModule } from '../activities/activities.module';
import { TahesabModule } from '../integrations/tahesab/tahesab.module';
import { AccountBalancesController } from './account-balances.controller';
import { AccountBalanceSettingsService } from './account-balance-settings.service';
import { BalanceClaimsScheduler } from './balance-claims.scheduler';
import { BalanceClaimsService } from './balance-claims.service';
@Module({
imports: [AuthModule, BillingModule, ActivitiesModule, TahesabModule],
controllers: [AccountBalancesController],
providers: [AccountBalanceSettingsService, BalanceClaimsService, BalanceClaimsScheduler],
exports: [AccountBalanceSettingsService, BalanceClaimsService],
})
export class AccountBalancesModule {}
@@ -0,0 +1,61 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { BalanceClaimsService } from './balance-claims.service';
import { tehranSyncSlot } from '../integrations/tahesab/customer-sync.scheduler';
@Injectable()
export class BalanceClaimsScheduler {
private readonly logger = new Logger(BalanceClaimsScheduler.name);
private busy = false;
constructor(
private readonly prisma: PrismaService,
private readonly claims: BalanceClaimsService,
) {}
@Cron('0 8,13 * * *', { timeZone: 'Asia/Tehran' })
async tick() {
if (process.env.NODE_ENV === 'test' || this.busy) return;
const { slot } = tehranSyncSlot();
this.busy = true;
try {
const orgs = await this.prisma.organization.findMany({
where: {
isActive: true,
enabledModules: { has: 'account_balances' },
OR: [
{ accountBalanceClaimsLastSlot: null },
{ accountBalanceClaimsLastSlot: { not: slot } },
],
},
select: { id: true, name: true },
});
for (const org of orgs) {
const claimed = await this.prisma.organization.updateMany({
where: {
id: org.id,
OR: [
{ accountBalanceClaimsLastSlot: null },
{ accountBalanceClaimsLastSlot: { not: slot } },
],
},
data: { accountBalanceClaimsLastSlot: slot },
});
if (claimed.count !== 1) continue;
try {
await this.claims.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;
}
}
}
@@ -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<PersonClaimContext[]> {
const links = await this.prisma.personAccountingLink.findMany({
where: {
connection: { organizationId, provider: 'tahesab', enabled: true },
person: { organizationId },
},
select: {
personId: true,
connectionId: true,
linkedAt: true,
connection: { select: { isDefault: true } },
person: {
select: {
id: true,
firstName: true,
lastName: true,
groupLinks: {
select: {
group: {
select: {
name: true,
position: true,
assigneeIds: true,
assignees: { select: { id: true } },
},
},
},
},
},
},
},
});
const out: PersonClaimContext[] = [];
const seen = new Set<string>();
const orderedLinks = [...links].sort((a, b) => {
if (a.personId !== b.personId) return a.personId.localeCompare(b.personId);
if (a.connection.isDefault !== b.connection.isDefault) return a.connection.isDefault ? -1 : 1;
return a.linkedAt.getTime() - b.linkedAt.getTime();
});
for (const link of orderedLinks) {
if (seen.has(link.personId)) continue;
const groups = [...link.person.groupLinks]
.map((g) => g.group)
.sort((a, b) => a.position - b.position || a.name.localeCompare(b.name, 'fa'));
let assigneeId: string | null = null;
for (const group of groups) {
const validAssigneeIds = new Set(group.assignees.map((a) => a.id));
const ordered =
group.assigneeIds.length > 0
? group.assigneeIds.filter((id) => validAssigneeIds.has(id))
: group.assignees.map((a) => a.id);
if (ordered.length) {
assigneeId = ordered[0]!;
break;
}
}
if (!assigneeId) continue;
seen.add(link.personId);
out.push({
personId: link.person.id,
fullName: `${link.person.firstName} ${link.person.lastName}`.trim(),
connectionId: link.connectionId,
assigneeId,
});
}
return out;
}
private async syncPerson(input: {
organizationId: string;
person: PersonClaimContext;
settings: AccountBalanceSettingsDto;
boardId: string;
openStageId: string;
canceledStageId: string;
typeDefId: string;
baseType: 'call' | 'meeting' | 'task' | 'note';
}) {
const assets = await this.balances.getAssets(
input.organizationId,
input.person.personId,
input.person.connectionId,
);
const matched = this.matchesAnyRange(assets, input.settings);
const existing = await this.prisma.activity.findFirst({
where: {
organizationId: input.organizationId,
boardId: input.boardId,
personId: input.person.personId,
tags: { has: ACCOUNT_BALANCE_CLAIMS_TAG },
},
orderBy: { createdAt: 'desc' },
select: {
id: true,
status: true,
assigneeId: true,
},
});
if (matched) {
if (existing) {
await this.prisma.activity.update({
where: { id: existing.id },
data: {
status: 'open',
stageId: input.openStageId,
completedAt: null,
assigneeId: input.person.assigneeId,
assignees: { set: [{ id: input.person.assigneeId }] },
title: `مطالبه: ${input.person.fullName}`,
},
});
return;
}
await this.prisma.activity.create({
data: {
organizationId: input.organizationId,
boardId: input.boardId,
stageId: input.openStageId,
status: 'open',
title: `مطالبه: ${input.person.fullName}`,
type: input.baseType,
typeDefId: input.typeDefId,
personId: input.person.personId,
assigneeId: input.person.assigneeId,
assignees: { connect: [{ id: input.person.assigneeId }] },
tags: [ACCOUNT_BALANCE_CLAIMS_TAG],
editPolicy: 'assignees',
completionMode: 'any',
completedByIds: [],
createdById: input.person.assigneeId,
},
});
return;
}
if (existing && existing.status !== 'canceled') {
await this.prisma.activity.update({
where: { id: existing.id },
data: {
status: 'canceled',
stageId: input.canceledStageId,
completedAt: new Date(),
},
});
}
}
private matchesAnyRange(
assets: {
rialBalance: number | null;
goldBalance: number | null;
mandehFields?: Array<{ key: string; value: string | null }>;
},
settings: AccountBalanceSettingsDto,
): boolean {
if (accountBalanceInRange(assets.rialBalance, settings.rial)) return true;
const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields);
for (const [key, range] of Object.entries(settings.weights)) {
const value =
fieldMap[key] ??
(key === 'MandeyeVazni' ? assets.goldBalance : null) ??
null;
if (accountBalanceInRange(value, range)) return true;
}
return false;
}
}
+35
View File
@@ -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<string, AccountBalanceRangeBody | null>;
}
@@ -10,7 +10,10 @@ import type {
ActivityStageDto,
ActivityStatus,
} from '@mento/shared';
import { ACTIVITY_STAGE_COLORS } from '@mento/shared';
import {
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
ACTIVITY_STAGE_COLORS,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
@@ -39,6 +42,7 @@ type BoardRow = {
name: string;
isDefault: boolean;
position: number;
systemKey: string | null;
members: Array<{ userId: string }>;
};
@@ -49,6 +53,7 @@ function toBoardDto(row: BoardRow): ActivityBoardDto {
isDefault: row.isDefault,
position: row.position,
memberIds: row.members.map((member) => member.userId),
systemKey: row.systemKey,
};
}
@@ -69,6 +74,7 @@ const BOARD_SELECT = {
id: true,
name: true,
isDefault: true,
systemKey: true,
position: true,
members: { select: { userId: true } },
} satisfies Prisma.ActivityBoardSelect;
@@ -142,9 +148,35 @@ export class ActivityStagesService {
});
const boards = rows.map(toBoardDto);
if (!actor || managesAllBoards(actor.role)) return boards;
return boards.filter(
(board) => board.memberIds.length === 0 || board.memberIds.includes(actor.userId),
);
const claimBoardIds = boards
.filter((b) => b.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS)
.map((b) => b.id);
const assignedClaimBoardIds = new Set<string>();
if (claimBoardIds.length) {
const assigned = await this.prisma.activity.findMany({
where: {
organizationId,
boardId: { in: claimBoardIds },
OR: [
{ assigneeId: actor.userId },
{ assignees: { some: { id: actor.userId } } },
],
},
select: { boardId: true },
distinct: ['boardId'],
});
for (const row of assigned) {
if (row.boardId) assignedClaimBoardIds.add(row.boardId);
}
}
return boards.filter((board) => {
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
return assignedClaimBoardIds.has(board.id);
}
return board.memberIds.length === 0 || board.memberIds.includes(actor.userId);
});
}
/** گروه بدون عضو برای همه باز است؛ مالک و مدیر همهٔ گروه‌ها را می‌بینند */
@@ -154,6 +186,25 @@ export class ActivityStagesService {
actor: { userId: string; role: string },
) {
if (managesAllBoards(actor.role)) return;
const board = await this.prisma.activityBoard.findFirst({
where: { id: boardId, organizationId },
select: { systemKey: true },
});
if (!board) throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
const hit = await this.prisma.activity.count({
where: {
organizationId,
boardId,
OR: [
{ assigneeId: actor.userId },
{ assignees: { some: { id: actor.userId } } },
],
},
});
if (hit > 0) return;
throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
}
const members = await this.prisma.activityBoardMember.findMany({
where: { boardId, board: { organizationId } },
select: { userId: true },
@@ -206,7 +257,13 @@ export class ActivityStagesService {
id: string,
dto: { name?: string; memberIds?: string[] },
): Promise<ActivityBoardDto> {
await this.getBoard(organizationId, id);
const board = await this.getBoard(organizationId, id);
if (board.systemKey && dto.name != null) {
throw new BadRequestException('نام این گروه سیستمی قابل تغییر نیست');
}
if (board.systemKey && dto.memberIds !== undefined) {
throw new BadRequestException('اعضای این گروه سیستمی از اینجا قابل تغییر نیست');
}
try {
if (dto.name != null) {
await this.prisma.activityBoard.update({
@@ -255,6 +312,9 @@ export class ActivityStagesService {
if (board.isDefault) {
throw new BadRequestException('گروه پیش‌فرض قابل حذف نیست');
}
if (board.systemKey) {
throw new BadRequestException('گروه سیستمی قابل حذف نیست');
}
await this.prisma.$transaction([
this.prisma.activity.updateMany({
where: { organizationId, boardId: id },
+2
View File
@@ -8,6 +8,7 @@ import { OrganizationsModule } from './organizations/organizations.module';
import { ContactsModule } from './contacts/contacts.module';
import { PipelinesModule } from './pipelines/pipelines.module';
import { ActivitiesModule } from './activities/activities.module';
import { AccountBalancesModule } from './account-balances/account-balances.module';
import { NotesModule } from './notes/notes.module';
import { CustomFieldsModule } from './custom-fields/custom-fields.module';
import { ProductsModule } from './products/products.module';
@@ -67,6 +68,7 @@ import { CustomerGroupsModule } from './customer-groups/customer-groups.module';
PrismaModule,
SmsBillingModule,
CustomerGroupsModule,
AccountBalancesModule,
OutboundSmsModule,
StorageModule,
HealthModule,
@@ -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) {