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([]) enabledModules String[] @default([])
/// برچسب/رنگ اولویت فعالیت و روتین (کلیدهای enum ثابت؛ فقط ظاهر) /// برچسب/رنگ اولویت فعالیت و روتین (کلیدهای enum ثابت؛ فقط ظاهر)
activityPriorities Json @default("{}") activityPriorities Json @default("{}")
/// تنظیم محدوده مانده حساب برای کاریز مطالبات
accountBalanceSettings Json @default("{}")
/// آخرین اسلات اجرای جاب مطالبات مانده (YYYY-MM-DD-HH تهران)
accountBalanceClaimsLastSlot String?
/// قالب‌های آمادهٔ پیامک دستی ([{ id, name, body }, …]) /// قالب‌های آمادهٔ پیامک دستی ([{ id, name, body }, …])
smsTemplates Json @default("[]") smsTemplates Json @default("[]")
/// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخاب‌شده)؛ null = بدون فیلتر /// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخاب‌شده)؛ null = بدون فیلتر
@@ -583,6 +587,8 @@ model CustomerGroup {
companies CompanyGroupLink[] companies CompanyGroupLink[]
/// مسئولان گروه — اختیاری؛ اعضای گروه را مثل مشتریان خود می‌بینند /// مسئولان گروه — اختیاری؛ اعضای گروه را مثل مشتریان خود می‌بینند
assignees User[] @relation("CustomerGroupAssignees") assignees User[] @relation("CustomerGroupAssignees")
/// ترتیب انتخاب مسئولان در فرم (اولین = مسئول اصلی مطالبات)
assigneeIds String[] @default([])
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@ -813,6 +819,8 @@ model ActivityBoard {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
name String name String
isDefault Boolean @default(false) isDefault Boolean @default(false)
/// مثلاً balance_claims — گروه سیستمی
systemKey String?
position Int @default(0) position Int @default(0)
stages ActivityStage[] stages ActivityStage[]
activities Activity[] activities Activity[]
@@ -821,6 +829,7 @@ model ActivityBoard {
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@unique([organizationId, name]) @@unique([organizationId, name])
@@unique([organizationId, systemKey])
@@index([organizationId, position]) @@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, ActivityStageDto,
ActivityStatus, ActivityStatus,
} from '@mento/shared'; } 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 { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
@@ -39,6 +42,7 @@ type BoardRow = {
name: string; name: string;
isDefault: boolean; isDefault: boolean;
position: number; position: number;
systemKey: string | null;
members: Array<{ userId: string }>; members: Array<{ userId: string }>;
}; };
@@ -49,6 +53,7 @@ function toBoardDto(row: BoardRow): ActivityBoardDto {
isDefault: row.isDefault, isDefault: row.isDefault,
position: row.position, position: row.position,
memberIds: row.members.map((member) => member.userId), memberIds: row.members.map((member) => member.userId),
systemKey: row.systemKey,
}; };
} }
@@ -69,6 +74,7 @@ const BOARD_SELECT = {
id: true, id: true,
name: true, name: true,
isDefault: true, isDefault: true,
systemKey: true,
position: true, position: true,
members: { select: { userId: true } }, members: { select: { userId: true } },
} satisfies Prisma.ActivityBoardSelect; } satisfies Prisma.ActivityBoardSelect;
@@ -142,9 +148,35 @@ export class ActivityStagesService {
}); });
const boards = rows.map(toBoardDto); const boards = rows.map(toBoardDto);
if (!actor || managesAllBoards(actor.role)) return boards; 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 }, actor: { userId: string; role: string },
) { ) {
if (managesAllBoards(actor.role)) return; 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({ const members = await this.prisma.activityBoardMember.findMany({
where: { boardId, board: { organizationId } }, where: { boardId, board: { organizationId } },
select: { userId: true }, select: { userId: true },
@@ -206,7 +257,13 @@ export class ActivityStagesService {
id: string, id: string,
dto: { name?: string; memberIds?: string[] }, dto: { name?: string; memberIds?: string[] },
): Promise<ActivityBoardDto> { ): 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 { try {
if (dto.name != null) { if (dto.name != null) {
await this.prisma.activityBoard.update({ await this.prisma.activityBoard.update({
@@ -255,6 +312,9 @@ export class ActivityStagesService {
if (board.isDefault) { if (board.isDefault) {
throw new BadRequestException('گروه پیش‌فرض قابل حذف نیست'); throw new BadRequestException('گروه پیش‌فرض قابل حذف نیست');
} }
if (board.systemKey) {
throw new BadRequestException('گروه سیستمی قابل حذف نیست');
}
await this.prisma.$transaction([ await this.prisma.$transaction([
this.prisma.activity.updateMany({ this.prisma.activity.updateMany({
where: { organizationId, boardId: id }, where: { organizationId, boardId: id },
+2
View File
@@ -8,6 +8,7 @@ import { OrganizationsModule } from './organizations/organizations.module';
import { ContactsModule } from './contacts/contacts.module'; import { ContactsModule } from './contacts/contacts.module';
import { PipelinesModule } from './pipelines/pipelines.module'; import { PipelinesModule } from './pipelines/pipelines.module';
import { ActivitiesModule } from './activities/activities.module'; import { ActivitiesModule } from './activities/activities.module';
import { AccountBalancesModule } from './account-balances/account-balances.module';
import { NotesModule } from './notes/notes.module'; import { NotesModule } from './notes/notes.module';
import { CustomFieldsModule } from './custom-fields/custom-fields.module'; import { CustomFieldsModule } from './custom-fields/custom-fields.module';
import { ProductsModule } from './products/products.module'; import { ProductsModule } from './products/products.module';
@@ -67,6 +68,7 @@ import { CustomerGroupsModule } from './customer-groups/customer-groups.module';
PrismaModule, PrismaModule,
SmsBillingModule, SmsBillingModule,
CustomerGroupsModule, CustomerGroupsModule,
AccountBalancesModule,
OutboundSmsModule, OutboundSmsModule,
StorageModule, StorageModule,
HealthModule, HealthModule,
@@ -51,7 +51,7 @@ export class CustomerGroupsService {
include: { include: {
_count: { select: { people: true, companies: true } }, _count: { select: { people: true, companies: true } },
parent: { select: { name: 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)); return rows.map((r) => this.toDto(r));
@@ -77,6 +77,7 @@ export class CustomerGroupsService {
name, name,
color: this.cleanColor(dto.color), color: this.cleanColor(dto.color),
position: (max._max.position ?? -1) + 1, position: (max._max.position ?? -1) + 1,
assigneeIds,
...(assigneeIds.length ...(assigneeIds.length
? { assignees: { connect: assigneeIds.map((id) => ({ id })) } } ? { assignees: { connect: assigneeIds.map((id) => ({ id })) } }
: {}), : {}),
@@ -116,7 +117,10 @@ export class CustomerGroupsService {
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}), ...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
...(parentId !== undefined ? { parentId } : {}), ...(parentId !== undefined ? { parentId } : {}),
...(assigneeIds !== undefined ...(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; parentId: string | null;
parent?: { name: string } | null; parent?: { name: string } | null;
_count: { people: number; companies: number }; _count: { people: number; companies: number };
assigneeIds: string[];
assignees: Array<{ id: string; fullName: string }>; assignees: Array<{ id: string; fullName: string }>;
}): CustomerGroupDto { }): 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 { return {
id: r.id, id: r.id,
name: r.name, name: r.name,
@@ -348,7 +359,8 @@ export class CustomerGroupsService {
companyCount: r._count.companies, companyCount: r._count.companies,
parentId: r.parentId, parentId: r.parentId,
parentName: r.parent?.name ?? null, 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) { if (rows.length !== unique.length) {
throw new BadRequestException('یکی از مسئولان انتخاب‌شده معتبر نیست'); 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) { private async require(organizationId: string, id: string) {
+9
View File
@@ -101,6 +101,15 @@ export const NAV_HUBS: NavHubDef[] = [
tint: 'violet', tint: 'violet',
module: 'customers', module: 'customers',
}, },
{
to: '/settings/account-balances',
title: 'تعیین محدوده مانده',
desc: 'بازه مانده مالی و وزنی برای کاریز مطالبات',
icon: 'dollar',
tint: 'amber',
admin: true,
module: 'account_balances',
},
], ],
}, },
{ {
+16
View File
@@ -575,6 +575,15 @@ export const router = createRouter({
component: () => import('@/views/TahesabSettingsView.vue'), component: () => import('@/views/TahesabSettingsView.vue'),
meta: { roles: ['owner', 'admin'] as UserRole[] }, 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', path: 'settings/woocommerce',
name: 'woocommerce-settings', name: 'woocommerce-settings',
@@ -668,6 +677,13 @@ router.beforeEach((to) => {
const modules = auth.user?.enabledModules; const modules = auth.user?.enabledModules;
if (modules && !modules.includes('tahesab')) return { name: 'home' }; 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))) { if (!canOpenPath(auth.user?.role, auth.user?.permissions, String(to.path))) {
return { name: 'home' }; return { name: 'home' };
} }
@@ -0,0 +1,252 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import {
ACCOUNT_BALANCE_WEIGHT_KEYS,
ACCOUNT_BALANCE_WEIGHT_LABELS,
type AccountBalanceRangeDto,
type AccountBalanceSettingsDto,
type UpdateAccountBalanceSettingsRequest,
} from '@mento/shared';
import { UiButton, UiCard, UiField, UiInput, UiPageHeader } from '@/components/ui';
type RangeDraft = { enabled: boolean; min: string; max: string };
const loading = ref(false);
const saving = ref(false);
const evaluating = ref(false);
const error = ref('');
const ok = ref('');
const firstStageName = ref('مطالبه مشتریان');
const rial = reactive<RangeDraft>({ enabled: false, min: '', max: '' });
const weights = reactive<Record<string, RangeDraft>>(
Object.fromEntries(
ACCOUNT_BALANCE_WEIGHT_KEYS.map((key) => [
key,
{ enabled: false, min: '', max: '' } satisfies RangeDraft,
]),
),
);
const weightKeys = computed(() =>
[...new Set([...ACCOUNT_BALANCE_WEIGHT_KEYS, ...Object.keys(weights)])].sort((a, b) =>
weightLabel(a).localeCompare(weightLabel(b), 'fa'),
),
);
function weightLabel(key: string) {
return ACCOUNT_BALANCE_WEIGHT_LABELS[key] ?? key;
}
function toDraft(range: AccountBalanceRangeDto | null | undefined): RangeDraft {
if (!range) return { enabled: false, min: '', max: '' };
return { enabled: true, min: String(range.min), max: String(range.max) };
}
function parseDraft(draft: RangeDraft): AccountBalanceRangeDto | null {
if (!draft.enabled) return null;
const min = Number(String(draft.min).replace(/,/g, ''));
const max = Number(String(draft.max).replace(/,/g, ''));
if (!Number.isFinite(min) || !Number.isFinite(max)) {
throw new Error('بازه نامعتبر');
}
return { min, max: Math.max(min, max) };
}
function applySettings(data: AccountBalanceSettingsDto) {
firstStageName.value = data.firstStageName || 'مطالبه مشتریان';
Object.assign(rial, toDraft(data.rial));
for (const key of Object.keys(weights)) {
delete weights[key];
}
for (const key of ACCOUNT_BALANCE_WEIGHT_KEYS) {
weights[key] = toDraft(null);
}
for (const [key, range] of Object.entries(data.weights ?? {})) {
weights[key] = toDraft(range);
}
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<AccountBalanceSettingsDto>('/account-balances/settings');
applySettings(data);
} catch (e) {
error.value = axios.isAxiosError(e)
? Array.isArray(e.response?.data?.message)
? e.response.data.message.join('، ')
: String(e.response?.data?.message || 'بارگذاری تنظیمات ناموفق بود.')
: 'بارگذاری تنظیمات ناموفق بود.';
} finally {
loading.value = false;
}
}
async function save() {
saving.value = true;
error.value = '';
ok.value = '';
try {
const weightPayload: Record<string, AccountBalanceRangeDto | null> = {};
for (const key of weightKeys.value) {
weightPayload[key] = parseDraft(weights[key] ?? { enabled: false, min: '', max: '' });
}
const body: UpdateAccountBalanceSettingsRequest = {
firstStageName: firstStageName.value.trim() || 'مطالبه مشتریان',
rial: parseDraft(rial),
weights: weightPayload,
};
const { data } = await api.put<AccountBalanceSettingsDto>('/account-balances/settings', body);
applySettings(data);
ok.value = 'تنظیمات ذخیره شد. کاریز مطالبات آماده است.';
} catch (e) {
error.value =
e instanceof Error && e.message === 'بازه نامعتبر'
? 'برای بازه‌های فعال، حداقل و حداکثر عددی وارد کنید.'
: axios.isAxiosError(e)
? Array.isArray(e.response?.data?.message)
? e.response.data.message.join('، ')
: String(e.response?.data?.message || 'ذخیره ناموفق بود.')
: 'ذخیره ناموفق بود.';
} finally {
saving.value = false;
}
}
async function runEvaluate() {
evaluating.value = true;
error.value = '';
ok.value = '';
try {
await api.post('/account-balances/evaluate');
ok.value = 'بروزرسانی مطالبات اجرا شد.';
} catch (e) {
error.value = axios.isAxiosError(e)
? String(e.response?.data?.message || 'اجرای ارزیابی ناموفق بود.')
: 'اجرای ارزیابی ناموفق بود.';
} finally {
evaluating.value = false;
}
}
onMounted(load);
</script>
<template>
<section class="page">
<UiPageHeader
title="تعیین محدوده مانده"
description="بازه مانده مالی و وزنی مشتریان ته‌حساب برای ساخت فعالیت در کاریز مطالبات."
/>
<p v-if="error" class="error">{{ error }}</p>
<p v-if="ok" class="ok">{{ ok }}</p>
<p v-if="loading" class="muted">در حال بارگذاری…</p>
<UiCard v-else title="محدوده‌ها">
<p class="hint">
اعداد با همان علامت ته‌حساب هستند: منفی = بد، مثبت = بس. بازه خالی/خاموش برای آن معیار اعمال نمی‌شود.
اگر حداقل یکی از بازه‌های فعال با مانده مشتری بخورد، فعالیت پیگیری ساخته می‌شود.
</p>
<UiField label="عنوان ستون اول کاریز مطالبات">
<UiInput v-model="firstStageName" maxlength="80" placeholder="مطالبه مشتریان" />
</UiField>
<div class="range-block">
<label class="toggle">
<input v-model="rial.enabled" type="checkbox" />
<span>مانده مالی (ریال)</span>
</label>
<div v-if="rial.enabled" class="range-row">
<UiField label="از">
<UiInput v-model="rial.min" inputmode="decimal" placeholder="مثلاً -1000000" />
</UiField>
<UiField label="تا">
<UiInput v-model="rial.max" inputmode="decimal" placeholder="مثلاً 0" />
</UiField>
</div>
</div>
<div v-for="key in weightKeys" :key="key" class="range-block">
<label class="toggle">
<input v-model="weights[key].enabled" type="checkbox" />
<span>{{ weightLabel(key) }}</span>
</label>
<div v-if="weights[key]?.enabled" class="range-row">
<UiField label="از">
<UiInput v-model="weights[key].min" inputmode="decimal" placeholder="مثلاً -10" />
</UiField>
<UiField label="تا">
<UiInput v-model="weights[key].max" inputmode="decimal" placeholder="مثلاً 0" />
</UiField>
</div>
</div>
<div class="actions">
<UiButton type="button" :disabled="saving" @click="save">
{{ saving ? 'در حال ذخیره…' : 'ذخیره' }}
</UiButton>
<UiButton type="button" variant="ghost" :disabled="evaluating" @click="runEvaluate">
{{ evaluating ? 'در حال اجرا…' : 'اجرای الانِ مطالبات' }}
</UiButton>
</div>
<p class="muted tiny">
جاب خودکار هر روز ساعت ۸ و ۱۳ به وقت تهران اجرا می‌شود. دکمهٔ دستی همان ارزیابی را فوری می‌زند.
</p>
</UiCard>
</section>
</template>
<style scoped>
.page {
display: grid;
gap: 1rem;
}
.hint,
.muted {
color: var(--muted, #64748b);
font-size: 0.9rem;
line-height: 1.6;
}
.tiny {
font-size: 0.8rem;
}
.error {
color: #b91c1c;
}
.ok {
color: #047857;
}
.range-block {
display: grid;
gap: 0.6rem;
padding: 0.75rem 0;
border-top: 1px solid var(--border, #e2e8f0);
}
.toggle {
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-weight: 600;
}
.range-row {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.75rem;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 0.75rem;
}
@media (max-width: 640px) {
.range-row {
grid-template-columns: 1fr;
}
}
</style>
+8 -3
View File
@@ -549,7 +549,7 @@ function openCreateBoard() {
} }
function openEditBoard() { function openEditBoard() {
if (!currentBoard.value) return; if (!currentBoard.value || currentBoard.value.systemKey) return;
boardMemberQuery.value = ''; boardMemberQuery.value = '';
boardModal.value = { boardModal.value = {
mode: 'edit', mode: 'edit',
@@ -1562,7 +1562,12 @@ onUnmounted(() => {
<UiIcon name="plus" :size="14" /> <UiIcon name="plus" :size="14" />
گروه جدید گروه جدید
</button> </button>
<button type="button" class="board-menu-action" @click="openEditBoard"> <button
v-if="!currentBoard?.systemKey"
type="button"
class="board-menu-action"
@click="openEditBoard"
>
<UiIcon name="pencil" :size="14" /> <UiIcon name="pencil" :size="14" />
ویرایش این گروه ویرایش این گروه
</button> </button>
@@ -2111,7 +2116,7 @@ onUnmounted(() => {
</li> </li>
</ul> </ul>
<UiButton <UiButton
v-if="boardModal.mode === 'edit' && currentBoard && !currentBoard.isDefault" v-if="boardModal.mode === 'edit' && currentBoard && !currentBoard.isDefault && !currentBoard.systemKey"
variant="ghost" variant="ghost"
size="sm" size="sm"
type="button" type="button"
+114 -2
View File
@@ -153,6 +153,7 @@ export type OrgModuleKey =
| "reports" | "reports"
| "notes" | "notes"
| "tahesab" | "tahesab"
| "account_balances"
| "custom_fields" | "custom_fields"
| "currencies" | "currencies"
| "team_settings" | "team_settings"
@@ -197,6 +198,7 @@ export const ORG_MODULE_KEYS: OrgModuleKey[] = [
"reports", "reports",
"notes", "notes",
"tahesab", "tahesab",
"account_balances",
"custom_fields", "custom_fields",
"currencies", "currencies",
"team_settings", "team_settings",
@@ -241,6 +243,7 @@ export const ORG_MODULE_LABELS: Record<OrgModuleKey, string> = {
reports: "گزارش‌ها", reports: "گزارش‌ها",
notes: "یادداشت‌ها", notes: "یادداشت‌ها",
tahesab: "ته‌حساب (اتصال و گزارش فروش)", tahesab: "ته‌حساب (اتصال و گزارش فروش)",
account_balances: "مانده حساب",
custom_fields: "فیلدهای سفارشی", custom_fields: "فیلدهای سفارشی",
currencies: "ارزها", currencies: "ارزها",
team_settings: "تیم و تنظیمات سازمان", team_settings: "تیم و تنظیمات سازمان",
@@ -266,7 +269,7 @@ export const ORG_MODULE_GROUPS: Array<{
title: string; title: string;
keys: OrgModuleKey[]; keys: OrgModuleKey[];
}> = [ }> = [
{ title: "مشتریان", keys: ["customers"] }, { title: "مشتریان", keys: ["customers", "account_balances"] },
{ title: "لیدها", keys: ["leads", "lead_forms"] }, { title: "لیدها", keys: ["leads", "lead_forms"] },
{ {
title: "فروش", title: "فروش",
@@ -329,6 +332,7 @@ export function isOrgModuleKey(value: string): value is OrgModuleKey {
export const OPT_IN_ORG_MODULES: OrgModuleKey[] = [ export const OPT_IN_ORG_MODULES: OrgModuleKey[] = [
"workflow_automations_advanced", "workflow_automations_advanced",
"prior_data_archive", "prior_data_archive",
"account_balances",
]; ];
export function defaultEnabledModules(): OrgModuleKey[] { export function defaultEnabledModules(): OrgModuleKey[] {
@@ -1355,8 +1359,10 @@ export interface CustomerGroupDto {
/** گروه اصلی؛ خالی یعنی خودش اصلی است */ /** گروه اصلی؛ خالی یعنی خودش اصلی است */
parentId?: string | null; parentId?: string | null;
parentName?: string | null; parentName?: string | null;
/** مسئولان گروه (اختیاری) */ /** مسئولان گروه به ترتیب انتخاب در فرم */
assignees: CustomerGroupAssigneeDto[]; assignees: CustomerGroupAssigneeDto[];
/** شناسهٔ مسئولان به همان ترتیب انتخاب (منبع ترتیب) */
assigneeIds?: string[];
} }
export interface CreateCustomerGroupRequest { export interface CreateCustomerGroupRequest {
@@ -1979,6 +1985,9 @@ export const ACTIVITY_STAGE_KIND_LABELS: Record<ActivityStatus, string> = {
canceled: "لغو شده", canceled: "لغو شده",
}; };
/** کلید سیستمی گروه فعالیت مطالبات مانده حساب */
export const ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS = "balance_claims";
/** گروه فعالیت (مثل مسیر فروش): هر گروه ستون‌های خودش را دارد */ /** گروه فعالیت (مثل مسیر فروش): هر گروه ستون‌های خودش را دارد */
export interface ActivityBoardDto { export interface ActivityBoardDto {
id: string; id: string;
@@ -1987,6 +1996,8 @@ export interface ActivityBoardDto {
position: number; position: number;
/** خالی = گروه برای همهٔ اعضای محیط باز است */ /** خالی = گروه برای همهٔ اعضای محیط باز است */
memberIds: string[]; memberIds: string[];
/** مثلاً balance_claims — گروه سیستمی غیرقابل حذف/تغییر نام */
systemKey?: string | null;
} }
export interface CreateActivityBoardRequest { export interface CreateActivityBoardRequest {
@@ -4819,6 +4830,107 @@ export interface PersonAssetsDto {
fetchedAt: string; 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<string, string> = {
MandeyeVazni: "مانده وزنی (طلا)",
MandeyeVazniNoghre: "مانده وزنی نقره",
};
export interface AccountBalanceRangeDto {
min: number;
max: number;
}
export interface AccountBalanceSettingsDto {
/** عنوان ستون اول کاریز مطالبات */
firstStageName: string;
/** بازه مانده مالی؛ null = خاموش */
rial: AccountBalanceRangeDto | null;
/** بازه به‌ازای هر کلید مانده وزنی؛ نبود کلید = خاموش */
weights: Record<string, AccountBalanceRangeDto>;
}
export interface UpdateAccountBalanceSettingsRequest {
firstStageName?: string;
rial?: AccountBalanceRangeDto | null;
weights?: Record<string, AccountBalanceRangeDto | null>;
}
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<string, unknown>;
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<string, AccountBalanceRangeDto> = {};
if (obj.weights && typeof obj.weights === "object") {
for (const [key, value] of Object.entries(obj.weights as Record<string, unknown>)) {
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<string, number> {
const out: Record<string, number> = {};
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 = export type MessageAutomationTrigger =