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

Keep local template/style for conflicted Vue pages; take main script/API/shared logic.
This commit is contained in:
2026-11-24 12:16:21 +03:30
74 changed files with 8558 additions and 1727 deletions
@@ -0,0 +1,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");
@@ -0,0 +1,11 @@
-- AlterTable
ALTER TABLE "Lead" ADD COLUMN "activityExperience" TEXT;
-- AlterTable
ALTER TABLE "Person" ADD COLUMN "activityExperience" TEXT;
-- CreateIndex
CREATE INDEX "Lead_organizationId_activityExperience_idx" ON "Lead"("organizationId", "activityExperience");
-- CreateIndex
CREATE INDEX "Person_organizationId_activityExperience_idx" ON "Person"("organizationId", "activityExperience");
+15
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
@@ -650,6 +656,8 @@ model Person {
birthDate DateTime?
/// نام معرف
referrer String?
/// سابقه فعالیت (ندارم | 1 الی 2 سال | 2 الی 5 سال | بیش از 5 سال)
activityExperience String?
/// لیست آدرس‌ها (JSON array of strings)
addresses Json @default("[]")
notes String?
@@ -704,6 +712,7 @@ model Person {
@@index([ownerId])
@@index([loyaltyTierId])
@@index([organizationId, discLabel])
@@index([organizationId, activityExperience])
}
model Pipeline {
@@ -813,6 +822,8 @@ model ActivityBoard {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
name String
isDefault Boolean @default(false)
/// مثلاً balance_claims — گروه سیستمی
systemKey String?
position Int @default(0)
stages ActivityStage[]
activities Activity[]
@@ -821,6 +832,7 @@ model ActivityBoard {
updatedAt DateTime @updatedAt
@@unique([organizationId, name])
@@unique([organizationId, systemKey])
@@index([organizationId, position])
}
@@ -3149,6 +3161,8 @@ model Lead {
/// صنف
trade String?
source String?
/// سابقه فعالیت (ندارم | 1 الی 2 سال | 2 الی 5 سال | بیش از 5 سال)
activityExperience String?
notes String?
/// لوگوی فروشگاه / شرکت
logoStorageKey String?
@@ -3186,6 +3200,7 @@ model Lead {
@@index([organizationId, city])
@@index([organizationId, trade])
@@index([organizationId, source])
@@index([organizationId, activityExperience])
}
model LeadEvent {
@@ -0,0 +1,84 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import type {
AccountBalanceRangeDto,
AccountBalanceSettingsDto,
UpdateAccountBalanceSettingsRequest,
} from '@mento/shared';
import {
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
parseAccountBalanceRange,
parseAccountBalanceSettings,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { BalanceClaimsService } from './balance-claims.service';
@Injectable()
export class AccountBalanceSettingsService {
constructor(
private readonly prisma: PrismaService,
private readonly claims: BalanceClaimsService,
) {}
async get(organizationId: string): Promise<AccountBalanceSettingsDto> {
const row = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { accountBalanceSettings: true },
});
return parseAccountBalanceSettings(row?.accountBalanceSettings);
}
async update(
organizationId: string,
dto: UpdateAccountBalanceSettingsRequest,
): Promise<AccountBalanceSettingsDto> {
const current = await this.get(organizationId);
const next: AccountBalanceSettingsDto = {
firstStageName:
dto.firstStageName !== undefined
? this.cleanStageName(dto.firstStageName)
: current.firstStageName,
rial:
dto.rial === undefined
? current.rial
: dto.rial === null
? null
: this.requireRange(dto.rial, 'بازه مالی'),
weights: { ...current.weights },
};
if (dto.weights) {
for (const [key, value] of Object.entries(dto.weights)) {
const cleanKey = key.trim();
if (!cleanKey) continue;
if (value === null) {
delete next.weights[cleanKey];
continue;
}
next.weights[cleanKey] = this.requireRange(value, `بازه ${cleanKey}`);
}
}
await this.prisma.organization.update({
where: { id: organizationId },
data: {
accountBalanceSettings: next as unknown as Prisma.InputJsonValue,
},
});
await this.claims.ensureBoard(organizationId, next.firstStageName);
return next;
}
private cleanStageName(raw: string) {
const name = raw.trim().slice(0, 80);
if (!name) return DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
return name;
}
private requireRange(raw: AccountBalanceRangeDto, label: string): AccountBalanceRangeDto {
const range = parseAccountBalanceRange(raw);
if (!range) throw new BadRequestException(`${label} معتبر نیست.`);
if (range.mode === 'all_debtors') return { mode: 'all_debtors' };
return range;
}
}
@@ -0,0 +1,43 @@
import { Body, Controller, Get, Post, Put, UseGuards } from '@nestjs/common';
import { Roles } from '../auth/roles.decorator';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import type { Actor } from '../common/record-scope';
import { RequireOrgModule } from '../billing/org-module.decorator';
import { OrgModuleGuard } from '../billing/org-module.guard';
import { AccountBalanceSettingsService } from './account-balance-settings.service';
import { BalanceClaimsService } from './balance-claims.service';
import { EvaluateAccountBalancesDto, UpdateAccountBalanceSettingsDto } from './dto';
@Controller('account-balances')
@UseGuards(JwtAuthGuard, RolesGuard, OrgModuleGuard)
@RequireOrgModule('account_balances')
export class AccountBalancesController {
constructor(
private readonly settings: AccountBalanceSettingsService,
private readonly claims: BalanceClaimsService,
) {}
@Get('settings')
@Roles('owner', 'admin')
getSettings(@CurrentUser() user: Actor) {
return this.settings.get(user.organizationId);
}
@Put('settings')
@Roles('owner', 'admin')
updateSettings(@CurrentUser() user: Actor, @Body() dto: UpdateAccountBalanceSettingsDto) {
return this.settings.update(user.organizationId, dto);
}
/** یک تکه از ارزیابی (حداکثر ۲۰۰۰ نفر)؛ کلاینت تکه‌ها را پشت سر هم می‌زند */
@Post('evaluate')
@Roles('owner', 'admin')
evaluate(@CurrentUser() user: Actor, @Body() dto: EvaluateAccountBalancesDto) {
return this.claims.evaluateOrganization(user.organizationId, {
offset: dto.offset,
limit: dto.limit,
});
}
}
@@ -0,0 +1,17 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { BillingModule } from '../billing/billing.module';
import { ActivitiesModule } from '../activities/activities.module';
import { TahesabModule } from '../integrations/tahesab/tahesab.module';
import { AccountBalancesController } from './account-balances.controller';
import { AccountBalanceSettingsService } from './account-balance-settings.service';
import { BalanceClaimsScheduler } from './balance-claims.scheduler';
import { BalanceClaimsService } from './balance-claims.service';
@Module({
imports: [AuthModule, BillingModule, ActivitiesModule, TahesabModule],
controllers: [AccountBalancesController],
providers: [AccountBalanceSettingsService, BalanceClaimsService, BalanceClaimsScheduler],
exports: [AccountBalanceSettingsService, BalanceClaimsService],
})
export class AccountBalancesModule {}
@@ -0,0 +1,61 @@
import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { BalanceClaimsService } from './balance-claims.service';
import { tehranSyncSlot } from '../integrations/tahesab/customer-sync.scheduler';
@Injectable()
export class BalanceClaimsScheduler {
private readonly logger = new Logger(BalanceClaimsScheduler.name);
private busy = false;
constructor(
private readonly prisma: PrismaService,
private readonly claims: BalanceClaimsService,
) {}
@Cron('0 8,13 * * *', { timeZone: 'Asia/Tehran' })
async tick() {
if (process.env.NODE_ENV === 'test' || this.busy) return;
const { slot } = tehranSyncSlot();
this.busy = true;
try {
const orgs = await this.prisma.organization.findMany({
where: {
isActive: true,
enabledModules: { has: 'account_balances' },
OR: [
{ accountBalanceClaimsLastSlot: null },
{ accountBalanceClaimsLastSlot: { not: slot } },
],
},
select: { id: true, name: true },
});
for (const org of orgs) {
const claimed = await this.prisma.organization.updateMany({
where: {
id: org.id,
OR: [
{ accountBalanceClaimsLastSlot: null },
{ accountBalanceClaimsLastSlot: { not: slot } },
],
},
data: { accountBalanceClaimsLastSlot: slot },
});
if (claimed.count !== 1) continue;
try {
await this.claims.evaluateOrganizationFully(org.id);
this.logger.log(`جاب مطالبات مانده برای «${org.name}» اجرا شد (${slot}).`);
} catch (err) {
this.logger.warn(
`جاب مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
);
}
}
} finally {
this.busy = false;
}
}
}
@@ -0,0 +1,658 @@
import { Injectable, Logger } from '@nestjs/common';
import {
ACCOUNT_BALANCE_CLAIMS_TAG,
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
accountBalanceMatchesCriterion,
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE,
parseAccountBalanceSettings,
parseAccountBalanceWeightFields,
type AccountBalanceEvaluateResultDto,
type AccountBalanceSettingsDto,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { ActivityTypesService } from '../activities/activity-types.service';
import { TahesabBalanceService } from '../integrations/tahesab/balance.service';
const BOARD_NAME = 'مطالبات';
const FOLLOW_UP_TYPE_NAME = 'پیگیری';
/** همزمانی داخل هر تکه برای ماندن زیر تایم‌اوت */
const BATCH_CONCURRENCY = 20;
type PersonClaimContext = {
personId: string;
fullName: string;
connectionId: string;
assigneeId: string;
};
@Injectable()
export class BalanceClaimsService {
private readonly logger = new Logger(BalanceClaimsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly types: ActivityTypesService,
private readonly balances: TahesabBalanceService,
) {}
async ensureFollowUpType(organizationId: string) {
await this.types.ensureDefaults(organizationId);
const existing = await this.prisma.activityTypeDef.findFirst({
where: { organizationId, name: FOLLOW_UP_TYPE_NAME },
select: { id: true, baseType: true },
});
if (existing) return existing;
const max = await this.prisma.activityTypeDef.aggregate({
where: { organizationId },
_max: { position: true },
});
return this.prisma.activityTypeDef.create({
data: {
organizationId,
name: FOLLOW_UP_TYPE_NAME,
baseType: 'call',
icon: 'bell',
color: 'orange',
position: (max._max.position ?? 0) + 1,
isSystem: false,
fields: [
{
key: 'followup_reason',
label: 'دلیل پیگیری',
type: 'select',
options: ['پیش‌فاکتور', 'پرداخت', 'ارسال کالا', 'پشتیبانی', 'تمدید قرارداد', 'سایر'],
},
{ key: 'followup_result', label: 'نتیجهٔ پیگیری', type: 'textarea' },
{ key: 'followup_next', label: 'تاریخ پیگیری بعدی', type: 'date' },
] as Prisma.InputJsonValue,
},
select: { id: true, baseType: true },
});
}
async ensureBoard(organizationId: string, firstStageName?: string) {
const stageName =
(firstStageName ?? DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE).trim() ||
DEFAULT_ACCOUNT_BALANCE_FIRST_STAGE;
let board = await this.prisma.activityBoard.findFirst({
where: { organizationId, systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS },
select: { id: true, name: true },
});
if (!board) {
const byName = await this.prisma.activityBoard.findFirst({
where: { organizationId, name: BOARD_NAME },
select: { id: true, name: true },
});
if (byName) {
board = await this.prisma.activityBoard.update({
where: { id: byName.id },
data: { systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS },
select: { id: true, name: true },
});
}
}
if (!board) {
const max = await this.prisma.activityBoard.aggregate({
where: { organizationId },
_max: { position: true },
});
board = await this.prisma.activityBoard.create({
data: {
organizationId,
name: BOARD_NAME,
systemKey: ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
position: (max._max.position ?? 0) + 1,
isDefault: false,
},
select: { id: true, name: true },
});
}
await this.ensureStages(organizationId, board.id, stageName);
return board;
}
private async ensureStages(organizationId: string, boardId: string, firstStageName: string) {
const stages = await this.prisma.activityStage.findMany({
where: { boardId },
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
select: { id: true, name: true, kind: true, position: true },
});
if (!stages.length) {
await this.prisma.activityStage.createMany({
data: [
{
organizationId,
boardId,
name: firstStageName,
color: 'orange',
kind: 'open',
position: 0,
},
{
organizationId,
boardId,
name: 'در حال انجام',
color: 'blue',
kind: 'open',
position: 1,
},
{
organizationId,
boardId,
name: 'انجام‌شده',
color: 'green',
kind: 'done',
position: 2,
},
{
organizationId,
boardId,
name: 'لغو شده',
color: 'rose',
kind: 'canceled',
position: 3,
},
],
skipDuplicates: true,
});
return;
}
const firstOpen = stages.find((s) => s.kind === 'open') ?? stages[0];
if (firstOpen && firstOpen.name !== firstStageName) {
const clash = stages.some((s) => s.id !== firstOpen.id && s.name === firstStageName);
if (!clash) {
await this.prisma.activityStage.update({
where: { id: firstOpen.id },
data: { name: firstStageName },
});
}
}
}
async evaluateAll() {
const orgs = await this.prisma.organization.findMany({
where: {
isActive: true,
enabledModules: { has: 'account_balances' },
accountingConnections: { some: { provider: 'tahesab', enabled: true } },
},
select: { id: true, name: true },
});
for (const org of orgs) {
try {
await this.evaluateOrganizationFully(org.id);
} catch (err) {
this.logger.warn(
`ارزیابی مطالبات «${org.name}» ناموفق: ${err instanceof Error ? err.message : err}`,
);
}
}
}
/** همهٔ تکه‌ها پشت سر هم (برای جاب زمان‌بندی‌شده) */
async evaluateOrganizationFully(organizationId: string): Promise<AccountBalanceEvaluateResultDto> {
let offset = 0;
let merged: AccountBalanceEvaluateResultDto | null = null;
for (;;) {
const batch = await this.evaluateOrganization(organizationId, {
offset,
limit: ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
});
merged = merged ? this.mergeResults(merged, batch) : batch;
if (batch.done || batch.nextOffset == null) {
merged.message = this.summarize(merged);
this.logger.log(`مطالبات کامل ${organizationId}: ${merged.message}`);
return merged;
}
offset = batch.nextOffset;
}
}
async evaluateOrganization(
organizationId: string,
opts?: { offset?: number; limit?: number },
): Promise<AccountBalanceEvaluateResultDto> {
const offset = Math.max(0, Math.floor(opts?.offset ?? 0));
const limit = Math.min(
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
Math.max(1, Math.floor(opts?.limit ?? ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE)),
);
const empty = (message: string): AccountBalanceEvaluateResultDto => ({
linkedPeople: 0,
candidates: 0,
skippedNoAssignee: 0,
matched: 0,
created: 0,
reopened: 0,
canceled: 0,
unchanged: 0,
errors: 0,
message,
offset,
limit,
batchProcessed: 0,
done: true,
nextOffset: null,
});
const org = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { enabledModules: true, accountBalanceSettings: true },
});
if (!org?.enabledModules.includes('account_balances')) {
return empty('ماژول مانده حساب برای این محیط فعال نیست.');
}
const settings = parseAccountBalanceSettings(org.accountBalanceSettings);
const hasAnyRange =
Boolean(settings.rial) || Object.keys(settings.weights).length > 0;
if (!hasAnyRange) {
return empty('هیچ بازهٔ فعالی ذخیره نشده است. ابتدا محدوده را ذخیره کنید.');
}
const board = await this.ensureBoard(organizationId, settings.firstStageName);
const typeDef = await this.ensureFollowUpType(organizationId);
const stages = await this.prisma.activityStage.findMany({
where: { boardId: board.id },
orderBy: [{ position: 'asc' }, { createdAt: 'asc' }],
select: { id: true, kind: true },
});
const openStageId = stages.find((s) => s.kind === 'open')?.id;
const canceledStageId = stages.find((s) => s.kind === 'canceled')?.id;
if (!openStageId || !canceledStageId) {
return empty('ستون‌های کاریز مطالبات ناقص است.');
}
const { candidates, linkedPeople, skippedNoAssignee } =
await this.loadCandidates(organizationId);
const slice = candidates.slice(offset, offset + limit);
const nextOffset = offset + slice.length;
const done = nextOffset >= candidates.length;
const result: AccountBalanceEvaluateResultDto = {
linkedPeople,
candidates: candidates.length,
skippedNoAssignee,
matched: 0,
created: 0,
reopened: 0,
canceled: 0,
unchanged: 0,
errors: 0,
message: '',
offset,
limit,
batchProcessed: slice.length,
done,
nextOffset: done ? null : nextOffset,
};
const actions = await this.mapPool(slice, BATCH_CONCURRENCY, async (person) => {
try {
return await this.syncPerson({
organizationId,
person,
settings,
boardId: board.id,
openStageId,
canceledStageId,
typeDefId: typeDef.id,
baseType: typeDef.baseType,
preferCache: true,
});
} catch (err) {
this.logger.warn(
`مانده/مطالبه شخص ${person.personId}: ${err instanceof Error ? err.message : err}`,
);
return 'error' as const;
}
});
for (const action of actions) {
if (action === 'created') {
result.matched += 1;
result.created += 1;
} else if (action === 'reopened') {
result.matched += 1;
result.reopened += 1;
} else if (action === 'canceled') {
result.canceled += 1;
} else if (action === 'matched-unchanged') {
result.matched += 1;
result.unchanged += 1;
} else if (action === 'error') {
result.errors += 1;
} else {
result.unchanged += 1;
}
}
result.message = done
? this.summarize(result)
: `تکه ${offset + 1} تا ${nextOffset} از ${candidates.length} · ادامه…`;
this.logger.log(`مطالبات ${organizationId}: ${result.message}`);
return result;
}
private mergeResults(
a: AccountBalanceEvaluateResultDto,
b: AccountBalanceEvaluateResultDto,
): AccountBalanceEvaluateResultDto {
return {
linkedPeople: Math.max(a.linkedPeople, b.linkedPeople),
candidates: Math.max(a.candidates, b.candidates),
skippedNoAssignee: Math.max(a.skippedNoAssignee, b.skippedNoAssignee),
matched: a.matched + b.matched,
created: a.created + b.created,
reopened: a.reopened + b.reopened,
canceled: a.canceled + b.canceled,
unchanged: a.unchanged + b.unchanged,
errors: a.errors + b.errors,
message: b.message,
offset: a.offset,
limit: a.limit,
batchProcessed: a.batchProcessed + b.batchProcessed,
done: b.done,
nextOffset: b.nextOffset,
};
}
private async mapPool<T, R>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<R>,
): Promise<R[]> {
if (!items.length) return [];
const out = new Array<R>(items.length);
let index = 0;
const runners = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (index < items.length) {
const currentIndex = index++;
out[currentIndex] = await worker(items[currentIndex]!);
}
});
await Promise.all(runners);
return out;
}
private summarize(r: AccountBalanceEvaluateResultDto): string {
if (r.linkedPeople === 0) {
return 'هیچ مشتری لینک‌شده به ته‌حساب پیدا نشد.';
}
if (r.candidates === 0) {
return `از ${r.linkedPeople} مشتری لینک‌شده، هیچ‌کدام گروه با مسئول ندارند (${r.skippedNoAssignee} بدون مسئول گروه).`;
}
if (r.matched === 0 && r.canceled === 0 && r.errors === 0) {
return `بررسی شد: ${r.candidates} نفر واجد شرایط گروه/مسئول؛ هیچ‌کدام داخل بازهٔ ذخیره‌شده نبودند.`;
}
const parts = [
`${r.candidates} واجد شرایط`,
`${r.matched} داخل بازه`,
`${r.created} ساخته`,
`${r.reopened} بازگشایی`,
`${r.canceled} خارج از بازه`,
];
if (r.errors) parts.push(`${r.errors} خطا`);
if (r.skippedNoAssignee) parts.push(`${r.skippedNoAssignee} بدون مسئول گروه`);
return parts.join(' · ');
}
private async loadCandidates(organizationId: string): Promise<{
candidates: PersonClaimContext[];
linkedPeople: number;
skippedNoAssignee: number;
}> {
const links = await this.prisma.personAccountingLink.findMany({
where: {
connection: { organizationId, provider: 'tahesab', enabled: true },
person: { organizationId },
},
select: {
personId: true,
connectionId: true,
linkedAt: true,
connection: { select: { isDefault: true } },
person: {
select: {
id: true,
firstName: true,
lastName: true,
groupLinks: {
select: {
group: {
select: {
name: true,
position: true,
assigneeIds: true,
assignees: { select: { id: true } },
},
},
},
},
},
},
},
});
const out: PersonClaimContext[] = [];
const seen = new Set<string>();
let skippedNoAssignee = 0;
const orderedLinks = [...links].sort((a, b) => {
if (a.personId !== b.personId) return a.personId.localeCompare(b.personId);
if (a.connection.isDefault !== b.connection.isDefault) {
return a.connection.isDefault ? -1 : 1;
}
return a.linkedAt.getTime() - b.linkedAt.getTime();
});
for (const link of orderedLinks) {
if (seen.has(link.personId)) continue;
seen.add(link.personId);
const groups = [...link.person.groupLinks]
.map((g) => g.group)
.sort((a, b) => a.position - b.position || a.name.localeCompare(b.name, 'fa'));
let assigneeId: string | null = null;
for (const group of groups) {
const fromRelation = group.assignees.map((a) => a.id);
const valid = new Set(fromRelation);
let ordered =
group.assigneeIds.length > 0
? group.assigneeIds.filter((id) => valid.has(id))
: [];
// اگر ترتیب ذخیره‌شده با M2M هم‌خوان نبود، همان مسئولان رابطه را بگیر
if (!ordered.length) ordered = fromRelation;
if (ordered.length) {
assigneeId = ordered[0]!;
break;
}
}
if (!assigneeId) {
skippedNoAssignee += 1;
continue;
}
out.push({
personId: link.person.id,
fullName: `${link.person.firstName} ${link.person.lastName}`.trim(),
connectionId: link.connectionId,
assigneeId,
});
}
return {
candidates: out,
linkedPeople: seen.size,
skippedNoAssignee,
};
}
private async syncPerson(input: {
organizationId: string;
person: PersonClaimContext;
settings: AccountBalanceSettingsDto;
boardId: string;
openStageId: string;
canceledStageId: string;
typeDefId: string;
baseType: 'call' | 'meeting' | 'task' | 'note';
/** در ارزیابی دسته‌ای اول از کش استفاده کن تا تایم‌اوت نشود */
preferCache?: boolean;
}): Promise<'created' | 'reopened' | 'canceled' | 'matched-unchanged' | 'out-unchanged'> {
let assets;
if (input.preferCache) {
try {
assets = await this.balances.getCachedOrFetch(
input.organizationId,
input.person.personId,
input.person.connectionId,
false,
);
} catch {
assets = await this.balances.getAssets(
input.organizationId,
input.person.personId,
input.person.connectionId,
);
}
} else {
try {
assets = await this.balances.getAssets(
input.organizationId,
input.person.personId,
input.person.connectionId,
);
} catch {
assets = await this.balances.getCachedOrFetch(
input.organizationId,
input.person.personId,
input.person.connectionId,
false,
);
}
}
const matched = this.matchesAnyRange(assets, input.settings);
const existing = await this.prisma.activity.findFirst({
where: {
organizationId: input.organizationId,
boardId: input.boardId,
personId: input.person.personId,
tags: { has: ACCOUNT_BALANCE_CLAIMS_TAG },
},
orderBy: { createdAt: 'desc' },
select: {
id: true,
status: true,
stageId: true,
assigneeId: true,
},
});
const title = `مطالبه: ${input.person.fullName}`;
if (matched) {
if (!existing) {
await this.prisma.activity.create({
data: {
organizationId: input.organizationId,
boardId: input.boardId,
stageId: input.openStageId,
status: 'open',
title,
type: input.baseType,
typeDefId: input.typeDefId,
personId: input.person.personId,
assigneeId: input.person.assigneeId,
assignees: { connect: [{ id: input.person.assigneeId }] },
tags: [ACCOUNT_BALANCE_CLAIMS_TAG],
editPolicy: 'assignees',
completionMode: 'any',
completedByIds: [],
createdById: input.person.assigneeId,
},
});
return 'created';
}
// فقط بعد از خروج از بازه (لغو) دوباره از ستون اول بیاید؛
// ستون‌های میانی / انجام‌شده حفظ می‌شوند.
if (existing.status === 'canceled') {
await this.prisma.activity.update({
where: { id: existing.id },
data: {
status: 'open',
stageId: input.openStageId,
completedAt: null,
completedByIds: [],
assigneeId: input.person.assigneeId,
assignees: { set: [{ id: input.person.assigneeId }] },
title,
},
});
return 'reopened';
}
// هنوز داخل بازه: ستون و وضعیت (در حال انجام / انجام‌شده) حفظ شود
await this.prisma.activity.update({
where: { id: existing.id },
data: {
title,
...(existing.assigneeId !== input.person.assigneeId
? {
assigneeId: input.person.assigneeId,
assignees: { set: [{ id: input.person.assigneeId }] },
}
: {}),
},
});
return 'matched-unchanged';
}
if (existing && existing.status !== 'canceled') {
await this.prisma.activity.update({
where: { id: existing.id },
data: {
status: 'canceled',
stageId: input.canceledStageId,
completedAt: new Date(),
},
});
return 'canceled';
}
return 'out-unchanged';
}
private matchesAnyRange(
assets: {
rialBalance: number | null;
goldBalance: number | null;
mandehFields?: Array<{ key: string; value: string | null }>;
},
settings: AccountBalanceSettingsDto,
): boolean {
if (accountBalanceMatchesCriterion(assets.rialBalance, settings.rial)) return true;
const fieldMap = parseAccountBalanceWeightFields(assets.mandehFields);
for (const [key, criterion] of Object.entries(settings.weights)) {
const value =
fieldMap[key] ??
(key === 'MandeyeVazni' ? assets.goldBalance : null) ??
null;
if (accountBalanceMatchesCriterion(value, criterion)) return true;
}
return false;
}
}
+59
View File
@@ -0,0 +1,59 @@
import { Type } from 'class-transformer';
import {
IsIn,
IsInt,
IsNumber,
IsObject,
IsOptional,
IsString,
Max,
MaxLength,
Min,
ValidateIf,
ValidateNested,
} from 'class-validator';
export class AccountBalanceRangeBody {
@IsIn(['all_debtors', 'range'])
mode!: 'all_debtors' | 'range';
@ValidateIf((o: AccountBalanceRangeBody) => o.mode === 'range')
@IsNumber()
min?: number;
@ValidateIf((o: AccountBalanceRangeBody) => o.mode === 'range')
@IsNumber()
max?: number;
}
export class UpdateAccountBalanceSettingsDto {
@IsOptional()
@IsString()
@MaxLength(80)
firstStageName?: string;
@IsOptional()
@ValidateIf((_, v) => v !== null)
@ValidateNested()
@Type(() => AccountBalanceRangeBody)
rial?: AccountBalanceRangeBody | null;
@IsOptional()
@IsObject()
weights?: Record<string, AccountBalanceRangeBody | null>;
}
export class EvaluateAccountBalancesDto {
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
offset?: number;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(1)
@Max(2000)
limit?: number;
}
@@ -400,6 +400,7 @@ export class ActivitiesExcelService {
.join('\n'));
const dueAt = parseJalaliDateTime(row.dueDate, row.dueTime);
const doneAt = parseJalaliDateTime(row.doneDate, row.doneTime);
const createdAt = parseJalaliDateTime(row.createdAt);
const status = parseStatus(row.status);
try {
@@ -452,6 +453,7 @@ export class ActivitiesExcelService {
dealId,
assigneeId,
createdById: creatorId,
...(createdAt ? { createdAt } : {}),
},
select: { id: true },
});
+130 -5
View File
@@ -5,6 +5,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import type {
ActivityAccountBalanceDto,
ActivityDto,
ActivityFieldValues,
ActivityFilter,
@@ -15,6 +16,12 @@ import type {
PaginatedResponse,
UpdateActivityRequest,
} from '@mento/shared';
import {
ACCOUNT_BALANCE_CLAIMS_TAG,
ACCOUNT_BALANCE_WEIGHT_KEYS,
ACCOUNT_BALANCE_WEIGHT_LABELS,
parseAccountBalanceWeightFields,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { randomUUID } from 'node:crypto';
import * as path from 'node:path';
@@ -38,6 +45,7 @@ import { tehranDayKey } from '../routines/routine-dates';
import { buildSearchWhere, ci } from '../common/search';
import { activityPriorWhere } from '../common/prior-archive';
import { leadsDeepWhere } from '../common/data-access';
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
import { ActivityStagesService, type BoardStageContext } from './activity-stages.service';
import {
ActivityTypesService,
@@ -363,10 +371,24 @@ export class ActivitiesService {
]);
const ctx = await this.ctx(organizationId);
const [todayDto, overdueDto, upcomingDto] = await Promise.all([
this.withAccountBalances(
organizationId,
today.map((row) => this.toDto(row, ctx)),
),
this.withAccountBalances(
organizationId,
overdue.map((row) => this.toDto(row, ctx)),
),
this.withAccountBalances(
organizationId,
upcoming.map((row) => this.toDto(row, ctx)),
),
]);
return {
today: today.map((row) => this.toDto(row, ctx)),
overdue: overdue.map((row) => this.toDto(row, ctx)),
upcoming: upcoming.map((row) => this.toDto(row, ctx)),
today: todayDto,
overdue: overdueDto,
upcoming: upcomingDto,
todayCount,
overdueCount,
};
@@ -418,7 +440,10 @@ export class ActivitiesService {
]);
return {
items: rows.map((row) => this.toDto(row, ctx)),
items: await this.withAccountBalances(
organizationId,
rows.map((row) => this.toDto(row, ctx)),
),
total,
page,
limit: take,
@@ -689,7 +714,8 @@ export class ActivitiesService {
orderBy: { fullName: 'asc' },
});
}
return dto;
const [enriched] = await this.withAccountBalances(organizationId, [dto]);
return enriched;
}
async create(
@@ -1635,6 +1661,105 @@ export class ActivitiesService {
}
}
/** فقط فعالیت‌های تگ مطالبات؛ مانده از کش ته‌حساب بدون فراخوانی زنده */
private async withAccountBalances(
organizationId: string,
items: ActivityDto[],
): Promise<ActivityDto[]> {
if (!items.length) return items;
const claimItems = items.filter((item) =>
(item.tags ?? []).includes(ACCOUNT_BALANCE_CLAIMS_TAG),
);
if (!claimItems.length) return items;
const personIds = [
...new Set(
claimItems
.map((item) => item.person?.id)
.filter((id): id is string => Boolean(id)),
),
];
const balanceByPerson = new Map<string, ActivityAccountBalanceDto | null>();
if (personIds.length) {
const links = await this.prisma.personAccountingLink.findMany({
where: {
personId: { in: personIds },
person: { organizationId },
},
include: {
balanceCache: true,
connection: { select: { isDefault: true } },
},
orderBy: [{ linkedAt: 'desc' }],
});
const bestByPerson = new Map<string, (typeof links)[number]>();
for (const link of links) {
const prev = bestByPerson.get(link.personId);
if (!prev) {
bestByPerson.set(link.personId, link);
continue;
}
const prevScore =
(prev.balanceCache ? 2 : 0) + (prev.connection.isDefault ? 1 : 0);
const nextScore =
(link.balanceCache ? 2 : 0) + (link.connection.isDefault ? 1 : 0);
if (nextScore > prevScore) bestByPerson.set(link.personId, link);
}
for (const personId of personIds) {
const link = bestByPerson.get(personId);
balanceByPerson.set(
personId,
link?.balanceCache
? this.cacheToAccountBalance(link.balanceCache)
: null,
);
}
}
return items.map((item) => {
if (!(item.tags ?? []).includes(ACCOUNT_BALANCE_CLAIMS_TAG)) return item;
const personId = item.person?.id;
return {
...item,
accountBalance: personId
? (balanceByPerson.get(personId) ?? null)
: null,
};
});
}
private cacheToAccountBalance(cache: {
rialBalance: number | null;
goldBalance: number | null;
rawResponse: unknown;
fetchedAt: Date;
}): ActivityAccountBalanceDto {
const fields = parseAccountBalanceWeightFields(
extractMandehRaw(cache.rawResponse).fields,
);
const weights = ACCOUNT_BALANCE_WEIGHT_KEYS.map((key) => {
const value =
fields[key] ??
(key === 'MandeyeVazni' ? cache.goldBalance : null) ??
null;
if (value == null || !Number.isFinite(value)) return null;
return {
key,
label: ACCOUNT_BALANCE_WEIGHT_LABELS[key] ?? key,
value,
};
}).filter((row): row is NonNullable<typeof row> => row != null);
return {
rialBalance:
cache.rialBalance != null && Number.isFinite(cache.rialBalance)
? cache.rialBalance
: null,
weights,
fetchedAt: cache.fetchedAt.toISOString(),
};
}
private toDto(row: ActivityRow, ctx?: DtoContext): ActivityDto {
const fields =
row.fields && typeof row.fields === 'object' && !Array.isArray(row.fields)
@@ -10,7 +10,10 @@ import type {
ActivityStageDto,
ActivityStatus,
} from '@mento/shared';
import { ACTIVITY_STAGE_COLORS } from '@mento/shared';
import {
ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS,
ACTIVITY_STAGE_COLORS,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
@@ -39,6 +42,7 @@ type BoardRow = {
name: string;
isDefault: boolean;
position: number;
systemKey: string | null;
members: Array<{ userId: string }>;
};
@@ -49,6 +53,7 @@ function toBoardDto(row: BoardRow): ActivityBoardDto {
isDefault: row.isDefault,
position: row.position,
memberIds: row.members.map((member) => member.userId),
systemKey: row.systemKey,
};
}
@@ -69,6 +74,7 @@ const BOARD_SELECT = {
id: true,
name: true,
isDefault: true,
systemKey: true,
position: true,
members: { select: { userId: true } },
} satisfies Prisma.ActivityBoardSelect;
@@ -142,9 +148,35 @@ export class ActivityStagesService {
});
const boards = rows.map(toBoardDto);
if (!actor || managesAllBoards(actor.role)) return boards;
return boards.filter(
(board) => board.memberIds.length === 0 || board.memberIds.includes(actor.userId),
);
const claimBoardIds = boards
.filter((b) => b.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS)
.map((b) => b.id);
const assignedClaimBoardIds = new Set<string>();
if (claimBoardIds.length) {
const assigned = await this.prisma.activity.findMany({
where: {
organizationId,
boardId: { in: claimBoardIds },
OR: [
{ assigneeId: actor.userId },
{ assignees: { some: { id: actor.userId } } },
],
},
select: { boardId: true },
distinct: ['boardId'],
});
for (const row of assigned) {
if (row.boardId) assignedClaimBoardIds.add(row.boardId);
}
}
return boards.filter((board) => {
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
return assignedClaimBoardIds.has(board.id);
}
return board.memberIds.length === 0 || board.memberIds.includes(actor.userId);
});
}
/** گروه بدون عضو برای همه باز است؛ مالک و مدیر همهٔ گروه‌ها را می‌بینند */
@@ -154,6 +186,25 @@ export class ActivityStagesService {
actor: { userId: string; role: string },
) {
if (managesAllBoards(actor.role)) return;
const board = await this.prisma.activityBoard.findFirst({
where: { id: boardId, organizationId },
select: { systemKey: true },
});
if (!board) throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
if (board.systemKey === ACTIVITY_BOARD_SYSTEM_BALANCE_CLAIMS) {
const hit = await this.prisma.activity.count({
where: {
organizationId,
boardId,
OR: [
{ assigneeId: actor.userId },
{ assignees: { some: { id: actor.userId } } },
],
},
});
if (hit > 0) return;
throw new ForbiddenException('به این گروه فعالیت دسترسی ندارید');
}
const members = await this.prisma.activityBoardMember.findMany({
where: { boardId, board: { organizationId } },
select: { userId: true },
@@ -206,7 +257,13 @@ export class ActivityStagesService {
id: string,
dto: { name?: string; memberIds?: string[] },
): Promise<ActivityBoardDto> {
await this.getBoard(organizationId, id);
const board = await this.getBoard(organizationId, id);
if (board.systemKey && dto.name != null) {
throw new BadRequestException('نام این گروه سیستمی قابل تغییر نیست');
}
if (board.systemKey && dto.memberIds !== undefined) {
throw new BadRequestException('اعضای این گروه سیستمی از اینجا قابل تغییر نیست');
}
try {
if (dto.name != null) {
await this.prisma.activityBoard.update({
@@ -255,6 +312,9 @@ export class ActivityStagesService {
if (board.isDefault) {
throw new BadRequestException('گروه پیش‌فرض قابل حذف نیست');
}
if (board.systemKey) {
throw new BadRequestException('گروه سیستمی قابل حذف نیست');
}
await this.prisma.$transaction([
this.prisma.activity.updateMany({
where: { organizationId, boardId: id },
+2
View File
@@ -8,6 +8,7 @@ import { OrganizationsModule } from './organizations/organizations.module';
import { ContactsModule } from './contacts/contacts.module';
import { PipelinesModule } from './pipelines/pipelines.module';
import { ActivitiesModule } from './activities/activities.module';
import { AccountBalancesModule } from './account-balances/account-balances.module';
import { NotesModule } from './notes/notes.module';
import { CustomFieldsModule } from './custom-fields/custom-fields.module';
import { ProductsModule } from './products/products.module';
@@ -67,6 +68,7 @@ import { CustomerGroupsModule } from './customer-groups/customer-groups.module';
PrismaModule,
SmsBillingModule,
CustomerGroupsModule,
AccountBalancesModule,
OutboundSmsModule,
StorageModule,
HealthModule,
@@ -416,7 +416,10 @@ export class AutomationsService {
await this.syncLeadAssigneeFromActivity(ctx, type === 'call' ? assigneeId : null);
}
/** سرنخ تازه‌ای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس را می‌گیرد. */
/**
* سرنخ تازه‌ای که فرم برایش مسئول نوبتی ندارد، مسئول اولین تماس اتوماسیون را می‌گیرد.
* مالک سازمان به‌عنوان fallback ست نمی‌شود — فقط مسئول صریح فعالیت.
*/
private async syncLeadAssigneeFromActivity(
ctx: AutomationContext,
activityAssigneeId: string | null,
@@ -468,6 +471,7 @@ export class AutomationsService {
ctx: AutomationContext,
ref: StepRef,
): Promise<string | null> {
/** مسئول فعلی رکورد؛ هرگز مالک سازمان را به‌صورت ضمنی اضافه نکن */
const fallback = ctx.assigneeId || ctx.ownerId || null;
const mode = config.assignMode ?? (config.assigneeId ? 'user' : 'owner');
@@ -502,6 +506,7 @@ export class AutomationsService {
return pickRoundRobin(valid, cursor.counter) ?? fallback;
}
// mode === 'owner' → مسئول فعلی رکورد؛ اگر نباشد فعالیت بدون مسئول می‌ماند
return fallback;
}
+16
View File
@@ -100,6 +100,12 @@ export class ListQueryDto {
@IsString()
@MaxLength(2000)
groupId?: string;
/** فیلتر سابقه فعالیت؛ چندتایی با کاما */
@IsOptional()
@IsString()
@MaxLength(400)
activityExperience?: string;
}
class CompanyExtraFieldsDto {
@@ -360,6 +366,11 @@ export class CreatePersonDto {
@MaxLength(120)
referrer?: string;
@IsOptional()
@IsString()
@MaxLength(80)
activityExperience?: string | null;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -486,6 +497,11 @@ export class UpdatePersonDto {
@MaxLength(120)
referrer?: string;
@IsOptional()
@IsString()
@MaxLength(80)
activityExperience?: string | null;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -63,6 +63,7 @@ export class PeopleController {
hasMobile,
disc: query.disc,
groupId: query.groupId,
activityExperience: query.activityExperience,
},
);
}
@@ -81,6 +82,7 @@ export class PeopleController {
hasMobile,
disc: query.disc,
groupId: query.groupId,
activityExperience: query.activityExperience,
});
}
+59
View File
@@ -23,6 +23,8 @@ import {
PERSON_MOODS,
applyPersonGenderTitle,
canViewAllRecords,
extractActivityExperienceFromNotes,
normalizeActivityExperience,
splitPersonHonorific,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
@@ -102,6 +104,7 @@ type PersonRow = {
instagram: string | null;
birthDate: Date | null;
referrer: string | null;
activityExperience: string | null;
addresses: unknown;
notes: string | null;
mood: PersonMood;
@@ -174,6 +177,7 @@ export class PeopleService implements OnModuleInit {
hasMobile?: boolean;
disc?: string;
groupId?: string;
activityExperience?: string;
},
): Prisma.PersonWhereInput {
const sources = [...new Set(splitCsv(opts?.importSource).map(normalizePersonImportSource))];
@@ -181,6 +185,13 @@ export class PeopleService implements OnModuleInit {
(PERSON_MOODS as readonly string[]).includes(m),
);
const groupIds = splitCsv(opts?.groupId);
const experiences = [
...new Set(
splitCsv(opts?.activityExperience)
.map((v) => normalizeActivityExperience(v) ?? v)
.filter(Boolean),
),
];
const search = buildSearchWhere<Prisma.PersonWhereInput>(q, (t) => [
{ firstName: ci(t) },
{ lastName: ci(t) },
@@ -231,6 +242,9 @@ export class PeopleService implements OnModuleInit {
if (sources.length) {
facets.push({ importSource: { in: sources } });
}
if (experiences.length) {
facets.push({ activityExperience: { in: experiences } });
}
if (facets.length === 1) and.push(facets[0]!);
else if (facets.length > 1) and.push({ OR: facets });
return {
@@ -258,6 +272,7 @@ export class PeopleService implements OnModuleInit {
hasMobile?: boolean;
disc?: string;
groupId?: string;
activityExperience?: string;
},
): Promise<PaginatedResponse<PersonDto>> {
const seeDisc = await this.behaviorAccess.canView(actor);
@@ -296,6 +311,7 @@ export class PeopleService implements OnModuleInit {
hasMobile?: boolean;
disc?: string;
groupId?: string;
activityExperience?: string;
},
max = FILTERED_IDS_MAX,
): Promise<FilteredIdsResponse> {
@@ -369,6 +385,38 @@ export class PeopleService implements OnModuleInit {
onModuleInit() {
void this.backfillStoredBirthDates();
void this.backfillActivityExperienceFromNotes();
}
/** سابقه فعالیت قدیمی که فقط در یادداشت بود، روی ستون مشتری می‌نشیند. */
async backfillActivityExperienceFromNotes() {
try {
const rows = await this.prisma.person.findMany({
where: {
activityExperience: null,
notes: { contains: 'سابقه' },
},
select: { id: true, notes: true },
take: 20000,
});
let filled = 0;
for (const row of rows) {
const value = extractActivityExperienceFromNotes(row.notes);
if (!value) continue;
const updated = await this.prisma.person.updateMany({
where: { id: row.id, activityExperience: null },
data: { activityExperience: value },
});
filled += updated.count;
}
if (filled) {
this.logger.log(`سابقه فعالیت ${filled} مشتری از یادداشت پر شد`);
}
} catch (err) {
this.logger.warn(
`پر کردن سابقه فعالیت مشتریان ناموفق بود: ${err instanceof Error ? err.message : err}`,
);
}
}
/** تاریخ تولدی که قبلاً در فیلد اضافی دیدار/اکسل یا پروفایل مونتیفای مانده، روی شخص می‌نشیند. */
@@ -475,6 +523,9 @@ export class PeopleService implements OnModuleInit {
instagram: emptyToNull(dto.instagram),
birthDate: parseBirthDate(dto.birthDate),
referrer: emptyToNull(dto.referrer),
activityExperience:
normalizeActivityExperience(dto.activityExperience) ??
emptyToNull(dto.activityExperience),
addresses: toJsonAddresses(dto.addresses),
notes: emptyToNull(dto.notes),
mood: dto.mood ?? 'newcomer',
@@ -587,6 +638,11 @@ export class PeopleService implements OnModuleInit {
if ('instagram' in dto) data.instagram = emptyToNull(dto.instagram);
if ('birthDate' in dto) data.birthDate = parseBirthDate(dto.birthDate);
if ('referrer' in dto) data.referrer = emptyToNull(dto.referrer);
if ('activityExperience' in dto) {
data.activityExperience =
normalizeActivityExperience(dto.activityExperience) ??
emptyToNull(dto.activityExperience);
}
if ('addresses' in dto) data.addresses = toJsonAddresses(dto.addresses);
if ('notes' in dto) data.notes = emptyToNull(dto.notes);
if (dto.mood !== undefined) data.mood = dto.mood;
@@ -1022,6 +1078,9 @@ export class PeopleService implements OnModuleInit {
instagram: row.instagram,
birthDate: row.birthDate?.toISOString() ?? null,
referrer: row.referrer,
activityExperience:
row.activityExperience ||
extractActivityExperienceFromNotes(row.notes),
addresses: (() => {
const fromCol = asAddresses(row.addresses);
if (fromCol.length) return fromCol;
@@ -51,7 +51,7 @@ export class CustomerGroupsService {
include: {
_count: { select: { people: true, companies: true } },
parent: { select: { name: true } },
assignees: { select: { id: true, fullName: true }, orderBy: { fullName: 'asc' } },
assignees: { select: { id: true, fullName: true } },
},
});
return rows.map((r) => this.toDto(r));
@@ -77,6 +77,7 @@ export class CustomerGroupsService {
name,
color: this.cleanColor(dto.color),
position: (max._max.position ?? -1) + 1,
assigneeIds,
...(assigneeIds.length
? { assignees: { connect: assigneeIds.map((id) => ({ id })) } }
: {}),
@@ -116,7 +117,10 @@ export class CustomerGroupsService {
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
...(parentId !== undefined ? { parentId } : {}),
...(assigneeIds !== undefined
? { assignees: { set: assigneeIds.map((uid) => ({ id: uid })) } }
? {
assigneeIds,
assignees: { set: assigneeIds.map((uid) => ({ id: uid })) },
}
: {}),
},
});
@@ -336,8 +340,15 @@ export class CustomerGroupsService {
parentId: string | null;
parent?: { name: string } | null;
_count: { people: number; companies: number };
assigneeIds: string[];
assignees: Array<{ id: string; fullName: string }>;
}): CustomerGroupDto {
const order = new Map(r.assigneeIds.map((id, index) => [id, index]));
const assignees = [...r.assignees].sort((a, b) => {
const ai = order.get(a.id) ?? Number.MAX_SAFE_INTEGER;
const bi = order.get(b.id) ?? Number.MAX_SAFE_INTEGER;
return ai - bi || a.fullName.localeCompare(b.fullName, 'fa');
});
return {
id: r.id,
name: r.name,
@@ -348,7 +359,8 @@ export class CustomerGroupsService {
companyCount: r._count.companies,
parentId: r.parentId,
parentName: r.parent?.name ?? null,
assignees: r.assignees.map((a) => ({ id: a.id, fullName: a.fullName })),
assigneeIds: assignees.map((a) => a.id),
assignees: assignees.map((a) => ({ id: a.id, fullName: a.fullName })),
};
}
@@ -366,7 +378,8 @@ export class CustomerGroupsService {
if (rows.length !== unique.length) {
throw new BadRequestException('یکی از مسئولان انتخاب‌شده معتبر نیست');
}
return rows.map((r) => r.id);
const found = new Set(rows.map((r) => r.id));
return unique.filter((id) => found.has(id));
}
private async require(organizationId: string, id: string) {
+2
View File
@@ -30,9 +30,11 @@ const MAP_TO = [
'lead.city',
'lead.region',
'lead.trade',
'lead.activityExperience',
'lead.notes',
'lead.source',
'lead.gender',
'person.activityExperience',
'person.gender',
'notes',
'custom',
+51 -12
View File
@@ -13,7 +13,12 @@ import type {
SubmitLeadFormResponse,
UpdateLeadFormRequest,
} from '@mento/shared';
import { isGenderQuestionLabel, parsePersonGenderAnswer } from '@mento/shared';
import {
isActivityExperienceLabel,
isGenderQuestionLabel,
normalizeActivityExperience,
parsePersonGenderAnswer,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { LocalFileStorage } from '../storage/local-file.storage';
@@ -298,14 +303,20 @@ export class LeadFormsService {
mapped.notes = [mapped.notes, utmNote].filter(Boolean).join('\n');
}
const ownerId = await this.nextAssignee(form);
/** فقط از لیست صریح «توزیع نوبتی»؛ بدون fallback به مالک سازمان */
const formAssigneeId = await this.nextAssignee(form);
/** فقط برای createdBy / رویدادها — مسئول لید نمی‌شود */
const actorId =
ownerId ??
formAssigneeId ??
(
await this.prisma.user.findFirst({
where: {
memberships: {
some: { organizationId: form.organizationId, role: 'owner' },
some: {
organizationId: form.organizationId,
role: { in: ['owner', 'admin'] },
isActive: true,
},
},
},
select: { id: true },
@@ -324,7 +335,7 @@ export class LeadFormsService {
let message: string | null = null;
if (form.createLead) {
const result = await this.upsertLead(form, mapped, ownerId ?? actorId, actorId);
const result = await this.upsertLead(form, mapped, formAssigneeId, actorId);
leadId = result.leadId;
status = result.status;
leadCreated = result.created;
@@ -344,12 +355,12 @@ export class LeadFormsService {
personId = await this.upsertPerson(
form.organizationId,
mapped,
ownerId ?? actorId,
formAssigneeId ?? actorId,
);
}
if (form.createDeal) {
await this.createDeal(form, mapped, personId, actorId, ownerId);
await this.createDeal(form, mapped, personId, actorId, formAssigneeId);
} else if (personId && mapped.notes && !form.createLead) {
await this.prisma.person.update({
where: { id: personId },
@@ -394,7 +405,9 @@ export class LeadFormsService {
entityId: personId ?? leadId ?? form.id,
title,
personId,
ownerId: ownerId ?? actorId,
/** فقط مسئول صریح فرم؛ مالک سازمان به‌عنوان fallback ست نمی‌شود */
ownerId: formAssigneeId,
assigneeId: formAssigneeId,
};
await this.automations.runTrigger('lead_submitted', {
...leadCtx,
@@ -402,7 +415,7 @@ export class LeadFormsService {
sourceId: form.id,
sourceType: 'lead_form',
leadId,
syncLeadAssignee: !ownerId && leadCreated && !!leadId,
syncLeadAssignee: !formAssigneeId && leadCreated && !!leadId,
mobile: mapped.mobile ?? mapped.phone ?? null,
formName: form.name,
formValues: values,
@@ -437,7 +450,7 @@ export class LeadFormsService {
private async upsertLead(
form: FormRow,
mapped: MappedValues,
assigneeId: string,
assigneeId: string | null,
actorId: string,
): Promise<{
leadId: string | null;
@@ -561,6 +574,9 @@ export class LeadFormsService {
region: emptyToNull(mapped.region) ?? existingLead.region,
trade: emptyToNull(mapped.trade) ?? existingLead.trade,
source: source ?? existingLead.source,
activityExperience:
emptyToNull(mapped.activityExperience) ??
existingLead.activityExperience,
notes: emptyToNull(mapped.notes) ?? existingLead.notes,
...(mapped.gender ? { gender: mapped.gender } : {}),
assigneeId: existingLead.assigneeId ?? assigneeId,
@@ -587,7 +603,9 @@ export class LeadFormsService {
};
}
const stages = await this.leadStages.list(form.organizationId);
const stages = await this.leadStages.list(form.organizationId, {
withLeadCounts: false,
});
const stageId =
(form.leadStageId && stages.find((s) => s.id === form.leadStageId)?.id) ||
stages.find((s) => !s.isConverted && !s.isLost && !s.isUnqualified)?.id ||
@@ -610,6 +628,7 @@ export class LeadFormsService {
region: emptyToNull(mapped.region),
trade: emptyToNull(mapped.trade),
source,
activityExperience: emptyToNull(mapped.activityExperience),
notes: emptyToNull(mapped.notes),
gender: mapped.gender ?? 'none',
stageId,
@@ -674,6 +693,8 @@ export class LeadFormsService {
phone: phone ?? existing.phone,
position: emptyToNull(mapped.position) ?? existing.position,
notes: emptyToNull(mapped.notes) ?? existing.notes,
activityExperience:
emptyToNull(mapped.activityExperience) ?? existing.activityExperience,
...(mapped.gender ? { gender: mapped.gender } : {}),
ownerId: existing.ownerId ?? ownerId,
},
@@ -691,6 +712,7 @@ export class LeadFormsService {
phone,
position: emptyToNull(mapped.position),
notes: emptyToNull(mapped.notes),
activityExperience: emptyToNull(mapped.activityExperience),
gender: mapped.gender ?? 'none',
ownerId,
},
@@ -954,6 +976,7 @@ type MappedValues = {
city?: string;
region?: string;
trade?: string;
activityExperience?: string;
leadSource?: string;
gender?: 'male' | 'female' | 'none';
};
@@ -985,6 +1008,15 @@ function mapValues(
if (gender) mapped.gender = gender;
continue;
}
if (
field.mapTo === 'lead.activityExperience' ||
field.mapTo === 'person.activityExperience' ||
isActivityExperienceLabel(field.label)
) {
mapped.activityExperience =
normalizeActivityExperience(raw) ?? raw;
continue;
}
switch (field.mapTo) {
case 'person.fullName': {
const parts = raw.split(/\s+/).filter(Boolean);
@@ -1038,6 +1070,11 @@ function mapValues(
case 'lead.trade':
mapped.trade = raw;
break;
case 'lead.activityExperience':
case 'person.activityExperience':
mapped.activityExperience =
normalizeActivityExperience(raw) ?? raw;
break;
case 'lead.notes':
mapped.notes = raw;
break;
@@ -1108,7 +1145,9 @@ function collectExtras(
for (const field of fields) {
if (field.fieldType === 'heading' || field.mapTo !== 'custom') continue;
const raw = (values?.[field.key] ?? '').toString().trim();
if (!raw || (isGenderQuestionLabel(field.label) && parsePersonGenderAnswer(raw))) continue;
if (!raw) continue;
if (isGenderQuestionLabel(field.label) && parsePersonGenderAnswer(raw)) continue;
if (isActivityExperienceLabel(field.label)) continue;
lines.push(`${field.label}: ${raw}`);
}
return lines.join('\n');
+6
View File
@@ -37,6 +37,7 @@ export class CreateLeadDto {
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
@IsOptional() @IsString() trade?: string;
@IsOptional() @IsString() source?: string;
@IsOptional() @IsString() activityExperience?: string | null;
@IsOptional() @IsString() notes?: string;
@IsOptional() @IsNumber() estimatedValue?: number;
@IsOptional() @IsString() stageId?: string;
@@ -60,9 +61,12 @@ export class UpdateLeadDto {
@IsOptional() @IsArray() @IsString({ each: true }) addresses?: string[];
@IsOptional() @IsString() trade?: string | null;
@IsOptional() @IsString() source?: string | null;
@IsOptional() @IsString() activityExperience?: string | null;
@IsOptional() @IsString() notes?: string | null;
@IsOptional() @IsNumber() estimatedValue?: number | null;
@IsOptional() @IsString() stageId?: string;
/** الزامی هنگام تغییر ستون؛ در جدول زمانی لید ثبت می‌شود */
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
@IsOptional() @IsString() assigneeId?: string | null;
@IsOptional() @IsString() nextFollowUpAt?: string | null;
@IsOptional() @IsString() lastContactAt?: string | null;
@@ -71,6 +75,7 @@ export class UpdateLeadDto {
export class MoveLeadDto {
@IsString() stageId!: string;
@IsOptional() @IsNumber() position?: number;
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
}
export class AssignLeadsDto {
@@ -81,6 +86,7 @@ export class AssignLeadsDto {
export class BulkLeadStageDto {
@IsArray() @IsString({ each: true }) leadIds!: string[];
@IsString() stageId!: string;
@IsOptional() @IsString() @MaxLength(1000) reason?: string | null;
}
export class AutoAssignLeadsDto {
+16 -8
View File
@@ -43,18 +43,26 @@ export class LeadStagesService {
});
}
async list(organizationId: string): Promise<LeadStageDto[]> {
async list(
organizationId: string,
opts: { withLeadCounts?: boolean } = {},
): Promise<LeadStageDto[]> {
const withLeadCounts = opts.withLeadCounts !== false;
await this.ensureDefaults(organizationId);
const rows = await this.prisma.leadStage.findMany({
where: { organizationId },
orderBy: { position: 'asc' },
include: {
_count: {
select: {
leads: { where: { archivedAt: null } },
},
},
},
...(withLeadCounts
? {
include: {
_count: {
select: {
leads: { where: { archivedAt: null } },
},
},
},
}
: {}),
});
return rows.map((r) => this.toDto(r));
}
+3 -1
View File
@@ -181,7 +181,9 @@ export class LeadsImportService {
const job = await this.prisma.leadImportJob.findUnique({ where: { id } });
if (!job) return;
const stages = await this.stages.list(job.organizationId);
const stages = await this.stages.list(job.organizationId, {
withLeadCounts: false,
});
const defaultStageId = stages[0]?.id;
if (!defaultStageId) {
await this.prisma.leadImportJob.update({
+13 -4
View File
@@ -70,8 +70,13 @@ export class LeadsController {
}
@Get('stages')
listStages(@CurrentUser() user: Actor) {
return this.stages.list(user.organizationId);
listStages(
@CurrentUser() user: Actor,
@Query('counts') counts?: string,
) {
return this.stages.list(user.organizationId, {
withLeadCounts: counts !== '0' && counts !== 'false',
});
}
@Post('stages')
@@ -244,6 +249,7 @@ export class LeadsController {
@Query('region') region?: string,
@Query('trade') trade?: string,
@Query('source') source?: string,
@Query('activityExperience') activityExperience?: string,
@Query('unassigned') unassigned?: string,
@Query('archived') archived?: string,
@Query('converted') converted?: string,
@@ -260,6 +266,7 @@ export class LeadsController {
region,
trade,
source,
activityExperience,
unassigned: unassigned === '1' || unassigned === 'true',
archived: archived === '1' || archived === 'true',
converted: converted === '1' || converted === 'true',
@@ -282,6 +289,7 @@ export class LeadsController {
@Query('region') region?: string,
@Query('trade') trade?: string,
@Query('source') source?: string,
@Query('activityExperience') activityExperience?: string,
@Query('unassigned') unassigned?: string,
@Query('archived') archived?: string,
@Query('converted') converted?: string,
@@ -301,6 +309,7 @@ export class LeadsController {
region,
trade,
source,
activityExperience,
unassigned: unassigned === '1' || unassigned === 'true',
archived: archived === '1' || archived === 'true',
converted: converted === '1' || converted === 'true',
@@ -329,7 +338,7 @@ export class LeadsController {
@Roles('owner', 'admin')
bulkStage(@CurrentUser() user: Actor, @Body() dto: BulkLeadStageDto) {
return this.leads
.bulkStage(user, dto.leadIds, dto.stageId)
.bulkStage(user, dto.leadIds, dto.stageId, dto.reason)
.then((count) => ({ count }));
}
@@ -393,7 +402,7 @@ export class LeadsController {
@Param('id') id: string,
@Body() dto: MoveLeadDto,
) {
return this.leads.move(user, id, dto.stageId, dto.position);
return this.leads.move(user, id, dto.stageId, dto.position, dto.reason);
}
@Get(':id/sms-history')
+296 -34
View File
@@ -2,8 +2,10 @@ import {
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
ServiceUnavailableException,
type OnModuleInit,
} from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { parseBirthDate } from '../common/excel';
@@ -20,7 +22,12 @@ import type {
PaginatedResponse,
} from '@mento/shared';
import { FILTERED_IDS_MAX } from '@mento/shared';
import { applyLeadGenderName, applyPersonGenderTitle } from '@mento/shared';
import {
applyLeadGenderName,
applyPersonGenderTitle,
extractActivityExperienceFromNotes,
normalizeActivityExperience,
} from '@mento/shared';
import { PrismaService } from '../prisma/prisma.service';
import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
import { renderSmsText } from '../common/sms-text';
@@ -104,10 +111,44 @@ const leadInclude = {
assignee: { select: { id: true, fullName: true } },
} as const;
/** فیلدهای لازم برای کارت مسیر لیدها — بدون notes/addresses حجیم و بدون join مرحله */
const boardLeadSelect = {
id: true,
title: true,
contactName: true,
gender: true,
showGenderInName: true,
mobile: true,
phone: true,
city: true,
region: true,
instagram: true,
birthDate: true,
trade: true,
source: true,
activityExperience: true,
logoStorageKey: true,
estimatedValue: true,
stageId: true,
position: true,
assigneeId: true,
lastContactAt: true,
nextFollowUpAt: true,
convertedPersonId: true,
convertedAt: true,
archivedAt: true,
createdAt: true,
updatedAt: true,
assignee: { select: { id: true, fullName: true } },
} as const;
type LeadRow = Prisma.LeadGetPayload<{ include: typeof leadInclude }>;
type BoardLeadRow = Prisma.LeadGetPayload<{ select: typeof boardLeadSelect }>;
@Injectable()
export class LeadsService {
export class LeadsService implements OnModuleInit {
private readonly logger = new Logger(LeadsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly stages: LeadStagesService,
@@ -118,6 +159,41 @@ export class LeadsService {
private readonly outboundSms: OutboundSmsLogService,
) {}
onModuleInit() {
void this.backfillActivityExperienceFromNotes();
}
/** سابقه فعالیت قدیمی که فقط در یادداشت فرم بود، روی ستون لید می‌نشیند. */
async backfillActivityExperienceFromNotes() {
try {
const rows = await this.prisma.lead.findMany({
where: {
activityExperience: null,
notes: { contains: 'سابقه' },
},
select: { id: true, notes: true },
take: 20000,
});
let filled = 0;
for (const row of rows) {
const value = extractActivityExperienceFromNotes(row.notes);
if (!value) continue;
const updated = await this.prisma.lead.updateMany({
where: { id: row.id, activityExperience: null },
data: { activityExperience: value },
});
filled += updated.count;
}
if (filled) {
this.logger.log(`سابقه فعالیت ${filled} لید از یادداشت فرم پر شد`);
}
} catch (err) {
this.logger.warn(
`پر کردن سابقه فعالیت لیدها ناموفق بود: ${err instanceof Error ? err.message : err}`,
);
}
}
private gameEvent(
actor: Actor,
event: Parameters<GamificationService['emit']>[0]['event'],
@@ -146,6 +222,7 @@ export class LeadsService {
region?: string;
trade?: string;
source?: string;
activityExperience?: string;
unassigned?: boolean;
archived?: boolean;
converted?: boolean;
@@ -165,6 +242,7 @@ export class LeadsService {
{ trade: ci(t) },
{ instagram: ci(t) },
{ source: ci(t) },
{ activityExperience: ci(t) },
]);
const and: Prisma.LeadWhereInput[] = [];
if (search) and.push(search);
@@ -191,6 +269,13 @@ export class LeadsService {
...(opts.source
? { source: { contains: opts.source, mode: 'insensitive' } }
: {}),
...(opts.activityExperience
? {
activityExperience:
normalizeActivityExperience(opts.activityExperience) ??
opts.activityExperience,
}
: {}),
},
...(opts.unassigned ? [{ assigneeId: null }] : []),
...(opts.assigneeId && !opts.unassigned ? [{ assigneeId: opts.assigneeId }] : []),
@@ -257,6 +342,7 @@ export class LeadsService {
region?: string;
trade?: string;
source?: string;
activityExperience?: string;
unassigned?: boolean;
archived?: boolean;
converted?: boolean;
@@ -310,6 +396,7 @@ export class LeadsService {
region?: string;
trade?: string;
source?: string;
activityExperience?: string;
unassigned?: boolean;
archived?: boolean;
converted?: boolean;
@@ -338,33 +425,56 @@ export class LeadsService {
}
async board(actor: Actor): Promise<LeadBoardColumnDto[]> {
const stages = await this.stages.list(actor.organizationId);
// بدون شمارش لید روی هر مرحله — شمارش را یک‌بار با groupBy می‌گیریم
const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const boardStages = stages.filter((s) => s.showOnBoard);
const whereBase = {
if (!boardStages.length) return [];
const access = leadAccessWhere(actor);
const stageIds = boardStages.map((s) => s.id);
const whereBase: Prisma.LeadWhereInput = {
organizationId: actor.organizationId,
...leadAccessWhere(actor),
...access,
archivedAt: null,
stageId: { in: stageIds },
};
const perColumn = 120;
return Promise.all(
boardStages.map(async (stage) => {
const where = { ...whereBase, stageId: stage.id };
const [total, rows] = await Promise.all([
this.prisma.lead.count({ where }),
this.prisma.lead.findMany({
where,
include: leadInclude,
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
take: perColumn,
}),
]);
return {
stage,
total,
leads: rows.map((row) => this.toDto(row)),
};
const [counts, ...columnRows] = await Promise.all([
this.prisma.lead.groupBy({
by: ['stageId'],
where: whereBase,
_count: { _all: true },
}),
...boardStages.map((stage) =>
this.prisma.lead.findMany({
where: {
organizationId: actor.organizationId,
...access,
archivedAt: null,
stageId: stage.id,
},
// کارت بورد به join مرحله نیاز ندارد؛ اسم مرحله را از ستون می‌گذاریم
select: boardLeadSelect,
orderBy: [{ position: 'asc' }, { updatedAt: 'desc' }],
take: perColumn,
}),
),
]);
const totalByStage = new Map(
counts.map((row) => [row.stageId, row._count._all]),
);
return boardStages.map((stage, index) => ({
stage,
total: totalByStage.get(stage.id) ?? 0,
leads: (columnRows[index] ?? []).map((row) =>
this.toBoardDto(row, stage.name),
),
}));
}
async get(actor: Actor, id: string): Promise<LeadDto & { events: LeadEventDto[] }> {
@@ -438,6 +548,7 @@ export class LeadsService {
addresses?: string[];
trade?: string | null;
source?: string | null;
activityExperience?: string | null;
notes?: string | null;
estimatedValue?: number | null;
stageId?: string;
@@ -459,7 +570,9 @@ export class LeadsService {
);
}
const stages = await this.stages.list(actor.organizationId);
const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const stageId = dto.stageId || stages[0]?.id;
if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده');
@@ -497,6 +610,9 @@ export class LeadsService {
addresses: toJsonAddresses(dto.addresses),
trade: emptyToNull(dto.trade),
source: emptyToNull(dto.source),
activityExperience:
normalizeActivityExperience(dto.activityExperience) ??
emptyToNull(dto.activityExperience),
notes: emptyToNull(dto.notes),
estimatedValue:
dto.estimatedValue != null
@@ -515,7 +631,10 @@ export class LeadsService {
include: leadInclude,
});
await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null);
await this.addEvent(actor, row.id, 'created', 'لید ایجاد شد', null, {
stageId: row.stageId,
stageName: row.stage.name,
});
if (assigneeId) {
await this.addEvent(
actor,
@@ -625,6 +744,13 @@ export class LeadsService {
...(dto.source !== undefined
? { source: emptyToNull(dto.source as string) }
: {}),
...(dto.activityExperience !== undefined
? {
activityExperience:
normalizeActivityExperience(dto.activityExperience as string | null) ??
emptyToNull(dto.activityExperience as string),
}
: {}),
...(dto.notes !== undefined
? { notes: emptyToNull(dto.notes as string) }
: {}),
@@ -670,11 +796,22 @@ export class LeadsService {
});
if (typeof dto.stageId === 'string' && dto.stageId !== existing.stageId) {
const reason = this.requireStageReason(
typeof dto.reason === 'string' ? dto.reason : null,
);
await this.addEvent(
actor,
id,
'stage_changed',
`وضعیت به «${row.stage.name}» تغییر کرد`,
reason,
{
fromStageId: existing.stageId,
fromStageName: existing.stage?.name ?? null,
toStageId: row.stageId,
toStageName: row.stage.name,
reason,
},
);
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
eventKey: `${id}:${row.stageId}`,
@@ -689,6 +826,7 @@ export class LeadsService {
id: string,
stageId: string,
position?: number,
reasonRaw?: string | null,
): Promise<LeadDto> {
const before = await this.findAccessible(actor, id);
const stage = await this.prisma.leadStage.findFirst({
@@ -696,6 +834,9 @@ export class LeadsService {
});
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
const stageChanged = before.stageId !== stageId;
const reason = stageChanged ? this.requireStageReason(reasonRaw) : null;
let placedIds: string[] | null = null;
let nextPosition = position ?? 0;
if (position != null) {
@@ -726,12 +867,20 @@ export class LeadsService {
this.prisma.lead.update({ where: { id: leadId }, data: { position: leadPosition } }),
);
}
if (before.stageId !== stageId) {
if (stageChanged && reason) {
await this.addEvent(
actor,
id,
'stage_changed',
`به مرحله «${stage.name}» منتقل شد`,
reason,
{
fromStageId: before.stageId,
fromStageName: before.stage?.name ?? null,
toStageId: stageId,
toStageName: stage.name,
reason,
},
);
this.gameEvent(actor, 'LEAD_STAGE_CHANGED', row, {
eventKey: `${id}:${stageId}`,
@@ -782,7 +931,9 @@ export class LeadsService {
actor: Actor,
leadIds: string[],
stageId: string,
reasonRaw?: string | null,
): Promise<number> {
const reason = this.requireStageReason(reasonRaw);
if (!elevated(actor.role)) {
throw new BadRequestException('فقط مدیر می‌تواند وضعیت گروهی تغییر دهد');
}
@@ -790,6 +941,18 @@ export class LeadsService {
where: { id: stageId, organizationId: actor.organizationId },
});
if (!stage) throw new NotFoundException('مرحله پیدا نشد');
const beforeRows = await this.prisma.lead.findMany({
where: {
organizationId: actor.organizationId,
id: { in: leadIds },
archivedAt: null,
},
select: {
id: true,
stageId: true,
stage: { select: { name: true } },
},
});
const result = await this.prisma.lead.updateMany({
where: {
organizationId: actor.organizationId,
@@ -798,12 +961,21 @@ export class LeadsService {
},
data: { stageId },
});
for (const leadId of leadIds) {
for (const lead of beforeRows) {
if (lead.stageId === stageId) continue;
await this.addEvent(
actor,
leadId,
lead.id,
'stage_changed',
`وضعیت گروهی به «${stage.name}»`,
reason,
{
fromStageId: lead.stageId,
fromStageName: lead.stage.name,
toStageId: stageId,
toStageName: stage.name,
reason,
},
);
}
return result.count;
@@ -1089,6 +1261,7 @@ export class LeadsService {
]
.filter(Boolean)
.join('\n'),
activityExperience: lead.activityExperience,
ownerId: lead.assigneeId ?? actor.userId,
createdAt: lead.createdAt,
importSource: 'lead_form',
@@ -1096,11 +1269,23 @@ export class LeadsService {
},
});
createdPerson = true;
} else if (!person.birthDate && lead.birthDate) {
await this.prisma.person.update({
where: { id: person.id },
data: { birthDate: lead.birthDate },
});
} else {
const personPatch: {
birthDate?: Date | null;
activityExperience?: string | null;
} = {};
if (!person.birthDate && lead.birthDate) {
personPatch.birthDate = lead.birthDate;
}
if (!person.activityExperience && lead.activityExperience) {
personPatch.activityExperience = lead.activityExperience;
}
if (Object.keys(personPatch).length) {
await this.prisma.person.update({
where: { id: person.id },
data: personPatch,
});
}
}
const convertedStage = await this.prisma.leadStage.findFirst({
@@ -1118,6 +1303,22 @@ export class LeadsService {
include: leadInclude,
});
if (convertedStage && convertedStage.id !== lead.stageId) {
await this.addEvent(
actor,
id,
'stage_changed',
`وضعیت به «${convertedStage.name}» تغییر کرد`,
null,
{
fromStageId: lead.stageId,
fromStageName: lead.stage?.name ?? null,
toStageId: convertedStage.id,
toStageName: convertedStage.name,
},
);
}
await this.addEvent(
actor,
id,
@@ -1167,7 +1368,9 @@ export class LeadsService {
...leadAccessWhere(actor),
archivedAt: null,
};
const stages = await this.stages.list(actor.organizationId);
const stages = await this.stages.list(actor.organizationId, {
withLeadCounts: false,
});
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
const lostIds = stages.filter((s) => s.isLost).map((s) => s.id);
// همان مقصد فرم و ورود از اکسل: اولین ستون باز، مستقل از اسم «جدید»
@@ -1309,7 +1512,9 @@ export class LeadsService {
}
await this.stages.ensureDefaults(input.organizationId);
const stages = await this.stages.list(input.organizationId);
const stages = await this.stages.list(input.organizationId, {
withLeadCounts: false,
});
const stageId = stages[0]?.id;
if (!stageId) throw new BadRequestException('مرحله‌ای تعریف نشده');
@@ -1447,6 +1652,17 @@ export class LeadsService {
return row;
}
private requireStageReason(raw: string | null | undefined): string {
const reason = String(raw ?? '').trim();
if (!reason) {
throw new BadRequestException('دلیل تغییر ستون الزامی است.');
}
if (reason.length > 1000) {
throw new BadRequestException('دلیل تغییر ستون نباید بیش از ۱۰۰۰ کاراکتر باشد.');
}
return reason;
}
private async addEvent(
actor: Actor,
leadId: string,
@@ -1490,6 +1706,9 @@ export class LeadsService {
addresses: asAddresses(row.addresses),
trade: row.trade,
source: row.source,
activityExperience:
row.activityExperience ||
extractActivityExperienceFromNotes(row.notes),
notes: row.notes,
estimatedValue:
row.estimatedValue != null ? Number(row.estimatedValue) : null,
@@ -1510,6 +1729,49 @@ export class LeadsService {
};
}
private toBoardDto(row: BoardLeadRow, stageName: string): LeadDto {
const daysInStage = Math.max(
0,
Math.floor(
(Date.now() - row.updatedAt.getTime()) / (24 * 60 * 60 * 1000),
),
);
return {
id: row.id,
title: row.title,
contactName: row.contactName,
gender: row.gender === 'male' || row.gender === 'female' ? row.gender : 'none',
showGenderInName: row.showGenderInName,
mobile: row.mobile,
phone: row.phone,
city: row.city,
region: row.region,
instagram: row.instagram,
birthDate: row.birthDate?.toISOString() ?? null,
addresses: [],
trade: row.trade,
source: row.source,
activityExperience: row.activityExperience,
notes: null,
estimatedValue:
row.estimatedValue != null ? Number(row.estimatedValue) : null,
stageId: row.stageId,
stageName,
position: row.position,
assigneeId: row.assigneeId,
assigneeName: row.assignee?.fullName ?? null,
lastContactAt: row.lastContactAt?.toISOString() ?? null,
nextFollowUpAt: row.nextFollowUpAt?.toISOString() ?? null,
convertedPersonId: row.convertedPersonId,
convertedAt: row.convertedAt?.toISOString() ?? null,
archivedAt: row.archivedAt?.toISOString() ?? null,
daysInStage,
hasLogo: Boolean(row.logoStorageKey),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
async saveLogo(
actor: Actor,
id: string,
@@ -0,0 +1,99 @@
/** بازهٔ ماندن یک لید در یک مرحله */
export type LeadStageStay = {
stageId: string;
fromMs: number;
toMs: number;
};
type StageChangeMeta = {
fromStageId?: string | null;
toStageId?: string | null;
};
function asMeta(raw: unknown): StageChangeMeta {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
const obj = raw as Record<string, unknown>;
return {
fromStageId:
typeof obj.fromStageId === 'string' ? obj.fromStageId : null,
toStageId: typeof obj.toStageId === 'string' ? obj.toStageId : null,
};
}
/**
* از رویدادهای لید، بازه‌های ماندن در هر مرحله را می‌سازد.
* برای دادهٔ قدیمی بدون meta، فقط toStage از meta یا ترتیب رویدادها استفاده می‌شود.
*/
export function buildLeadStageStays(input: {
leadId: string;
currentStageId: string;
createdAt: Date;
convertedAt: Date | null;
archivedAt: Date | null;
events: Array<{ type: string; createdAt: Date; meta: unknown }>;
nowMs?: number;
}): LeadStageStay[] {
const nowMs = input.nowMs ?? Date.now();
const endCap = Math.min(
nowMs,
input.convertedAt?.getTime() ?? Number.POSITIVE_INFINITY,
input.archivedAt?.getTime() ?? Number.POSITIVE_INFINITY,
);
type Point = { at: number; stageId: string | null };
const points: Point[] = [{ at: input.createdAt.getTime(), stageId: null }];
const timeline = [...input.events].sort(
(a, b) => a.createdAt.getTime() - b.createdAt.getTime(),
);
for (const ev of timeline) {
if (ev.type === 'created') {
const meta = asMeta(ev.meta);
const rawStage =
meta.toStageId ||
(ev.meta &&
typeof ev.meta === 'object' &&
!Array.isArray(ev.meta) &&
typeof (ev.meta as { stageId?: unknown }).stageId === 'string'
? String((ev.meta as { stageId: string }).stageId)
: null);
if (rawStage) {
points[0] = { at: ev.createdAt.getTime(), stageId: rawStage };
}
continue;
}
if (ev.type !== 'stage_changed') continue;
const meta = asMeta(ev.meta);
const toStageId = meta.toStageId;
if (!toStageId) continue;
points.push({ at: ev.createdAt.getTime(), stageId: toStageId });
}
// اگر نقطهٔ اول stage نداشت، از اولین stage_changed یا مرحلهٔ فعلی استفاده کن
if (!points[0]?.stageId) {
const firstKnown = points.find((p) => p.stageId);
points[0]!.stageId = firstKnown?.stageId ?? input.currentStageId;
}
// آخرین مرحله تا endCap ادامه دارد
const last = points[points.length - 1]!;
if (last.stageId !== input.currentStageId && !input.convertedAt && !input.archivedAt) {
// مرحلهٔ فعلی ممکن است بدون رویداد باشد (دادهٔ قدیمی)
points.push({ at: endCap, stageId: input.currentStageId });
}
const stays: LeadStageStay[] = [];
for (let i = 0; i < points.length; i++) {
const cur = points[i]!;
if (!cur.stageId) continue;
const nextAt = points[i + 1]?.at ?? endCap;
const toMs = Math.min(nextAt, endCap);
if (toMs <= cur.at) continue;
stays.push({ stageId: cur.stageId, fromMs: cur.at, toMs });
}
return stays;
}
export function hoursBetween(fromMs: number, toMs: number): number {
return Math.max(0, (toMs - fromMs) / (1000 * 60 * 60));
}
@@ -97,6 +97,15 @@ export class ReportsController {
});
}
/** قیف لید، تبدیل بین‌مرحله‌ای و میانگین ماندن در ستون‌ها */
@Get('leads')
leads(@CurrentUser() user: Actor, @Query() query: ReportsQueryDto) {
return this.reportsService.leadsAnalytics(user, {
from: query.from,
to: query.to,
});
}
/** داشبورد صفحهٔ خانه برای همه باز است */
@Get('home')
@RequirePermission('reports', { reads: false })
+444 -15
View File
@@ -10,19 +10,22 @@ import type {
ReportsDrillKind,
ReportsDrilldownDto,
ReportsFunnelStageDto,
ReportsLeadsAnalyticsDto,
ReportsPeriodCompareRowDto,
} from '@mento/shared';
import {
isReportsLeadBuilderMetric,
REPORTS_BUILDER_DIMENSION_LABELS,
REPORTS_BUILDER_METRIC_LABELS,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { customersPersonWhere } from '../common/data-access';
import { customersPersonWhere, leadsDeepWhere } from '../common/data-access';
import {
type Actor,
assigneeWhere,
elevated,
forScope,
ownerWhere,
ticketAccessWhere,
} from '../common/record-scope';
@@ -38,6 +41,10 @@ import {
jalaliMonthName,
startOfJalaliMonth,
} from '../common/jalali';
import {
buildLeadStageStays,
hoursBetween,
} from './leads-analytics.util';
const DRILL_LIMIT = 50;
@@ -1205,6 +1212,230 @@ export class ReportsService {
};
}
async leadsAnalytics(
actor: Actor,
opts: { from?: string; to?: string },
): Promise<ReportsLeadsAnalyticsDto> {
const { start, end } = resolveRange(opts.from, opts.to);
const orgId = actor.organizationId;
const access = this.leadAccessWhere(actor);
const stages = await this.prisma.leadStage.findMany({
where: { organizationId: orgId },
orderBy: { position: 'asc' },
select: {
id: true,
name: true,
position: true,
isConverted: true,
isLost: true,
isUnqualified: true,
},
});
const stageName = new Map(stages.map((s) => [s.id, s.name]));
const lostIds = new Set(
stages.filter((s) => s.isLost || s.isUnqualified).map((s) => s.id),
);
const convertedIds = new Set(
stages.filter((s) => s.isConverted).map((s) => s.id),
);
const [created, converted, lost, activeLeads, stageEvents] =
await Promise.all([
this.prisma.lead.count({
where: {
organizationId: orgId,
...access,
createdAt: { gte: start, lte: end },
},
}),
this.prisma.lead.count({
where: {
organizationId: orgId,
...access,
convertedAt: { gte: start, lte: end },
},
}),
this.prisma.lead.count({
where: {
organizationId: orgId,
...access,
archivedAt: null,
stageId: { in: [...lostIds] },
updatedAt: { gte: start, lte: end },
},
}),
this.prisma.lead.findMany({
where: {
organizationId: orgId,
...access,
archivedAt: null,
convertedAt: null,
stageId: { notIn: [...lostIds, ...convertedIds] },
},
select: { id: true, stageId: true },
}),
this.prisma.leadEvent.findMany({
where: {
organizationId: orgId,
type: { in: ['created', 'stage_changed'] },
createdAt: { gte: start, lte: end },
lead: { ...access },
},
select: {
leadId: true,
type: true,
createdAt: true,
meta: true,
},
orderBy: { createdAt: 'asc' },
}),
]);
const active = activeLeads.length;
const byStageCount = new Map<string, number>();
for (const lead of activeLeads) {
byStageCount.set(lead.stageId, (byStageCount.get(lead.stageId) ?? 0) + 1);
}
const funnelTotal = active || 1;
let prevCount: number | null = null;
// ماندگاری و انتقال‌ها از رویدادها + وضعیت فعلی لیدهای درگیر
const leadIds = [
...new Set([
...stageEvents.map((e) => e.leadId),
...activeLeads.map((l) => l.id),
]),
];
const leadsForDwell = leadIds.length
? await this.prisma.lead.findMany({
where: { id: { in: leadIds }, organizationId: orgId, ...access },
select: {
id: true,
stageId: true,
createdAt: true,
convertedAt: true,
archivedAt: true,
events: {
where: { type: { in: ['created', 'stage_changed'] } },
select: { type: true, createdAt: true, meta: true },
orderBy: { createdAt: 'asc' },
},
},
})
: [];
const dwellSum = new Map<string, { hours: number; n: number }>();
const transitionCount = new Map<string, number>();
const leftFromCount = new Map<string, number>();
for (const lead of leadsForDwell) {
const stays = buildLeadStageStays({
leadId: lead.id,
currentStageId: lead.stageId,
createdAt: lead.createdAt,
convertedAt: lead.convertedAt,
archivedAt: lead.archivedAt,
events: lead.events,
});
for (const stay of stays) {
// فقط بازه‌هایی که با بازهٔ گزارش همپوشانی دارند
const fromMs = Math.max(stay.fromMs, start.getTime());
const toMs = Math.min(stay.toMs, end.getTime());
if (toMs <= fromMs) continue;
const hours = hoursBetween(fromMs, toMs);
const cur = dwellSum.get(stay.stageId) ?? { hours: 0, n: 0 };
cur.hours += hours;
cur.n += 1;
dwellSum.set(stay.stageId, cur);
}
for (const ev of lead.events) {
if (ev.type !== 'stage_changed') continue;
if (ev.createdAt < start || ev.createdAt > end) continue;
const meta =
ev.meta && typeof ev.meta === 'object' && !Array.isArray(ev.meta)
? (ev.meta as Record<string, unknown>)
: {};
const fromId =
typeof meta.fromStageId === 'string' ? meta.fromStageId : null;
const toId = typeof meta.toStageId === 'string' ? meta.toStageId : null;
if (!fromId || !toId || fromId === toId) continue;
const key = `${fromId}→${toId}`;
transitionCount.set(key, (transitionCount.get(key) ?? 0) + 1);
leftFromCount.set(fromId, (leftFromCount.get(fromId) ?? 0) + 1);
}
}
const funnel = stages.map((s) => {
const count = byStageCount.get(s.id) ?? 0;
const conversionFromPrevPercent =
prevCount == null
? null
: prevCount === 0
? count > 0
? 100
: 0
: Math.round((count / prevCount) * 1000) / 10;
prevCount = count;
const dwell = dwellSum.get(s.id);
return {
stageId: s.id,
stageName: s.name,
count,
sharePercent: Math.round((count / funnelTotal) * 1000) / 10,
conversionFromPrevPercent,
avgDwellHours: dwell
? Math.round((dwell.hours / dwell.n) * 10) / 10
: null,
};
});
const transitions = [...transitionCount.entries()]
.map(([key, count]) => {
const [fromStageId, toStageId] = key.split('→');
const left = leftFromCount.get(fromStageId!) ?? 0;
return {
fromStageId: fromStageId!,
fromStageName: stageName.get(fromStageId!) ?? fromStageId!,
toStageId: toStageId!,
toStageName: stageName.get(toStageId!) ?? toStageId!,
count,
conversionPercent:
left > 0 ? Math.round((count / left) * 1000) / 10 : 0,
};
})
.sort((a, b) => b.count - a.count);
const dwellByStage = stages
.map((s) => {
const d = dwellSum.get(s.id);
if (!d || d.n === 0) return null;
return {
stageId: s.id,
stageName: s.name,
avgHours: Math.round((d.hours / d.n) * 10) / 10,
sampleCount: d.n,
};
})
.filter((row): row is NonNullable<typeof row> => row != null);
const closed = converted + lost;
return {
from: start.toISOString(),
to: end.toISOString(),
created,
converted,
lost,
active,
conversionRate:
closed > 0 ? Math.round((converted / closed) * 1000) / 10 : 0,
funnel,
transitions,
dwellByStage,
};
}
async builder(
actor: Actor,
query: ReportsBuilderQuery,
@@ -1226,11 +1457,16 @@ export class ReportsService {
'invoice_amount',
'invoice_count',
]);
const leadMetric = isReportsLeadBuilderMetric(metric);
if (
if (leadMetric) {
if (dimension === 'stage') dimension = 'lead_stage';
if (dimension === 'status') dimension = 'none';
} else if (
!dealMetrics.has(metric) &&
(dimension === 'source' ||
dimension === 'stage' ||
dimension === 'lead_stage' ||
dimension === 'status')
) {
dimension = 'none';
@@ -1246,6 +1482,7 @@ export class ReportsService {
const ownerFilterIds = await this.resolveBuilderOwnerIds(actor, {
userId: query.userId,
teamId: query.teamId,
scope: leadMetric ? 'leads' : 'deals',
});
if (ownerFilterIds && ownerFilterIds.length === 0) {
return emptyBuilderResult(metric, dimension, start, end, rates.baseCurrency, format);
@@ -1310,7 +1547,7 @@ export class ReportsService {
const label = normalizeSource(opts.source);
return { key: label, label };
}
if (dimension === 'stage') {
if (dimension === 'stage' || dimension === 'lead_stage') {
const id = opts.stageId || 'none';
return { key: id, label: opts.stageName || 'بدون مرحله' };
}
@@ -1437,13 +1674,174 @@ export class ReportsService {
add(dim.key, dim.label, amount);
}
}
} else if (leadMetric) {
const leadAccess = this.leadAccessWhere(actor);
const assigneeFilter =
ownerFilterIds == null
? {}
: { assigneeId: { in: ownerFilterIds } };
const stages = await this.prisma.leadStage.findMany({
where: { organizationId: orgId },
select: {
id: true,
name: true,
isConverted: true,
isLost: true,
isUnqualified: true,
},
});
const lostIds = stages
.filter((s) => s.isLost || s.isUnqualified)
.map((s) => s.id);
const convertedIds = stages.filter((s) => s.isConverted).map((s) => s.id);
if (metric === 'leads_avg_dwell_hours') {
const leads = await this.prisma.lead.findMany({
where: {
organizationId: orgId,
...leadAccess,
...assigneeFilter,
OR: [
{ createdAt: { gte: start, lte: end } },
{ updatedAt: { gte: start, lte: end } },
{ convertedAt: { gte: start, lte: end } },
],
},
select: {
id: true,
stageId: true,
assigneeId: true,
source: true,
createdAt: true,
convertedAt: true,
archivedAt: true,
events: {
where: { type: { in: ['created', 'stage_changed'] } },
select: { type: true, createdAt: true, meta: true },
orderBy: { createdAt: 'asc' },
},
},
});
const sum = new Map<string, { hours: number; n: number; label: string }>();
for (const lead of leads) {
const stays = buildLeadStageStays({
leadId: lead.id,
currentStageId: lead.stageId,
createdAt: lead.createdAt,
convertedAt: lead.convertedAt,
archivedAt: lead.archivedAt,
events: lead.events,
});
for (const stay of stays) {
const fromMs = Math.max(stay.fromMs, start.getTime());
const toMs = Math.min(stay.toMs, end.getTime());
if (toMs <= fromMs) continue;
const hours = hoursBetween(fromMs, toMs);
if (dimension === 'lead_stage' || dimension === 'stage') {
const name =
stages.find((s) => s.id === stay.stageId)?.name ?? stay.stageId;
const cur = sum.get(stay.stageId) ?? {
hours: 0,
n: 0,
label: name,
};
cur.hours += hours;
cur.n += 1;
sum.set(stay.stageId, cur);
} else {
const dim = await dimKey({
ownerId: lead.assigneeId,
source: lead.source,
stageId: stay.stageId,
stageName:
stages.find((s) => s.id === stay.stageId)?.name ?? null,
at: new Date(stay.fromMs),
});
const cur = sum.get(dim.key) ?? {
hours: 0,
n: 0,
label: dim.label,
};
cur.hours += hours;
cur.n += 1;
sum.set(dim.key, cur);
}
}
}
for (const [key, row] of sum.entries()) {
if (row.n <= 0) continue;
add(key, row.label, Math.round((row.hours / row.n) * 10) / 10);
}
} else {
let where: Prisma.LeadWhereInput = {
organizationId: orgId,
...leadAccess,
...assigneeFilter,
};
if (metric === 'leads_created') {
where = { ...where, createdAt: { gte: start, lte: end } };
} else if (metric === 'leads_converted') {
where = { ...where, convertedAt: { gte: start, lte: end } };
} else if (metric === 'leads_lost') {
where = {
...where,
archivedAt: null,
stageId: { in: lostIds.length ? lostIds : ['__none__'] },
updatedAt: { gte: start, lte: end },
};
} else {
// leads_active
where = {
...where,
archivedAt: null,
convertedAt: null,
stageId: {
notIn: [...lostIds, ...convertedIds],
},
};
}
const leads = await this.prisma.lead.findMany({
where,
select: {
assigneeId: true,
source: true,
stageId: true,
stage: { select: { name: true } },
createdAt: true,
updatedAt: true,
convertedAt: true,
},
});
for (const lead of leads) {
const at =
metric === 'leads_converted'
? lead.convertedAt ?? lead.updatedAt
: metric === 'leads_created'
? lead.createdAt
: lead.updatedAt;
const dim = await dimKey({
ownerId: lead.assigneeId,
source: lead.source,
stageId: lead.stageId,
stageName: lead.stage?.name,
at,
});
add(dim.key, dim.label, 1);
}
}
}
const rows: ReportsBuilderRowDto[] = [...buckets.entries()]
.map(([key, row]) => ({
key,
label: row.label,
value: Math.round(row.value * (format === 'money' ? 1 : 1)),
value:
metric === 'leads_avg_dwell_hours'
? Math.round(row.value * 10) / 10
: Math.round(row.value * (format === 'money' ? 1 : 1)),
}))
.sort((a, b) => b.value - a.value);
@@ -1471,21 +1869,52 @@ export class ReportsService {
};
}
private leadAccessWhere(actor: Actor): Prisma.LeadWhereInput {
if (actor.leadsAccess !== undefined) {
return leadsDeepWhere(actor);
}
const scoped = forScope(actor, 'leads');
if (elevated(scoped.role)) return {};
if (scoped.dataVisibility === 'org') return {};
if (
scoped.dataVisibility === 'team' &&
scoped.visibleUserIds &&
scoped.visibleUserIds.length
) {
return { assigneeId: { in: scoped.visibleUserIds } };
}
return { assigneeId: scoped.userId };
}
private async resolveBuilderOwnerIds(
actor: Actor,
opts: { userId?: string; teamId?: string },
opts: { userId?: string; teamId?: string; scope?: 'deals' | 'leads' },
): Promise<string[] | null> {
const scope = ownerWhere(actor, 'deals');
let allowed: string[] | null = null;
if ('ownerId' in scope && typeof scope.ownerId === 'string') {
allowed = [scope.ownerId];
} else if (
'ownerId' in scope &&
scope.ownerId &&
typeof scope.ownerId === 'object' &&
'in' in scope.ownerId
) {
allowed = [...scope.ownerId.in];
if (opts.scope === 'leads') {
const scoped = forScope(actor, 'leads');
if (elevated(scoped.role) || scoped.dataVisibility === 'org') {
allowed = null;
} else if (
scoped.dataVisibility === 'team' &&
scoped.visibleUserIds?.length
) {
allowed = [...scoped.visibleUserIds];
} else {
allowed = [scoped.userId];
}
} else {
const scope = ownerWhere(actor, 'deals');
if ('ownerId' in scope && typeof scope.ownerId === 'string') {
allowed = [scope.ownerId];
} else if (
'ownerId' in scope &&
scope.ownerId &&
typeof scope.ownerId === 'object' &&
'in' in scope.ownerId
) {
allowed = [...scope.ownerId.in];
}
}
let ids: string[] | null = null;
@@ -181,6 +181,33 @@ export class TreasuryController {
});
}
@Get('documents/:id')
getDocument(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.treasury.getDocument(user, id);
}
@Patch('documents/:id')
updateDocument(
@CurrentUser() user: Actor,
@Param('id') id: string,
@Body()
body: {
title?: string;
notes?: string | null;
categoryId?: string | null;
method?: string | null;
bookedAt?: string;
amount?: string | number;
},
) {
return this.treasury.updateDocument(user, id, body);
}
@Delete('documents/:id')
deleteDocument(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.treasury.deleteDocument(user, id);
}
@Get('attachments/:id')
async downloadAttachment(@CurrentUser() user: Actor, @Param('id') id: string) {
const file = await this.treasury.openAttachment(user, id);
+123 -21
View File
@@ -4,7 +4,11 @@ import {
Injectable,
NotFoundException,
} from '@nestjs/common';
import { parseUserTreasuryAccess } from '@mento/shared';
import {
canManageTreasuryDocuments,
parseUserTreasuryAccess,
permissionsWithTreasuryOverride,
} from '@mento/shared';
import { randomUUID } from 'node:crypto';
import { Prisma } from '@prisma/client';
import ExcelJS from 'exceljs';
@@ -506,13 +510,87 @@ export class TreasuryService {
}
: {}),
},
include: { category: true, account: true, movements: true, attachments: { select: { id: true, fileName: true } } },
include: {
category: true,
account: true,
movements: true,
attachments: { select: { id: true, fileName: true, mimeType: true } },
},
orderBy: { bookedAt: 'desc' },
take: 200,
});
return rows.map((row) => this.toDocumentDto(row));
}
async getDocument(actor: Actor, id: string): Promise<FinancialDocumentDto> {
const doc = await this.requireScopedDocument(actor, id);
return this.toDocumentDto(doc);
}
async updateDocument(
actor: Actor,
id: string,
input: {
title?: string;
notes?: string | null;
categoryId?: string | null;
method?: string | null;
bookedAt?: string;
amount?: string | number;
},
): Promise<FinancialDocumentDto> {
await this.assertDocumentsManage(actor);
const doc = await this.requireScopedDocument(actor, id);
if (doc.status === 'void' || doc.voidedAt) {
throw new BadRequestException('سند باطل‌شده قابل ویرایش نیست.');
}
const data: Prisma.FinancialDocumentUncheckedUpdateInput = {};
if (input.title !== undefined) {
const title = input.title.trim();
if (title.length < 2) throw new BadRequestException('عنوان را وارد کنید.');
data.title = title;
}
if (input.notes !== undefined) data.notes = input.notes?.trim() || null;
if (input.categoryId !== undefined) data.categoryId = input.categoryId || null;
if (input.method !== undefined) data.method = input.method || null;
if (input.bookedAt !== undefined) {
const bookedAt = startOfDay(input.bookedAt);
if (!bookedAt) throw new BadRequestException('تاریخ نامعتبر است.');
data.bookedAt = bookedAt;
}
if (input.amount !== undefined) {
const active = doc.movements.filter((row) => !row.voidedAt);
if (active.length > 0 || doc.status !== 'open') {
throw new BadRequestException('مبلغ فقط برای سند باز بدون دریافت/پرداخت قابل تغییر است.');
}
const amount = dec(input.amount);
if (!amount.greaterThan(0)) throw new BadRequestException('مبلغ باید بزرگ‌تر از صفر باشد.');
data.amount = amount;
}
await this.prisma.financialDocument.update({ where: { id: doc.id }, data });
return this.getDocument(actor, id);
}
async deleteDocument(actor: Actor, id: string): Promise<{ ok: true }> {
await this.assertDocumentsManage(actor);
const doc = await this.requireScopedDocument(actor, id);
const active = doc.movements.filter((row) => !row.voidedAt);
if (doc.status !== 'void' && active.length > 0) {
throw new BadRequestException('ابتدا سند را ابطال کنید، سپس حذف کنید.');
}
const attachments = await this.prisma.financialAttachment.findMany({
where: { documentId: doc.id, organizationId: actor.organizationId },
select: { id: true, storageKey: true },
});
for (const file of attachments) {
const bytes = await this.files.sizeOf(file.storageKey);
await this.files.remove(file.storageKey);
if (bytes) await this.storage.addLocal(actor.organizationId, -bytes);
}
await this.prisma.financialDocument.delete({ where: { id: doc.id } });
return { ok: true };
}
async createDocument(
actor: Actor,
input: {
@@ -557,12 +635,6 @@ export class TreasuryService {
if (input.accountId) {
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
if (input.kind === 'expense' && settle.greaterThan(0)) {
const balance = await this.accountBalance(account.id);
if (balance.lessThan(settle)) {
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
}
}
}
const bookedAt = startOfDay(input.bookedAt) ?? new Date();
const settlement = input.settlement === true;
@@ -905,12 +977,6 @@ export class TreasuryService {
if (amount.greaterThan(available)) {
throw new BadRequestException('مبلغ از ماندهٔ سندهای باز این طرف حساب بیشتر است.');
}
if (input.kind === 'expense') {
const balance = await this.accountBalance(account.id);
if (balance.lessThan(amount)) {
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
}
}
const occurredAt = startOfDay(input.occurredAt) ?? new Date();
let left = amount;
const touched: string[] = [];
@@ -1050,12 +1116,6 @@ export class TreasuryService {
}
const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.');
if (doc.kind === 'expense') {
const balance = await this.accountBalance(account.id);
if (balance.lessThan(amount)) {
throw new BadRequestException('موجودی حساب برای این پرداخت کافی نیست.');
}
}
const nextSettled = settled.plus(amount);
const status = nextSettled.equals(doc.amount) ? 'settled' : 'partial';
await this.prisma.$transaction([
@@ -1443,6 +1503,47 @@ export class TreasuryService {
);
}
private async actorPermissions(actor: Actor): Promise<string[]> {
const membership = await this.prisma.membership.findFirst({
where: { userId: actor.userId, organizationId: actor.organizationId, isActive: true },
select: {
orgRole: { select: { permissions: true } },
treasuryAccessOverride: true,
},
});
const rolePermissions = Array.isArray(membership?.orgRole?.permissions)
? membership.orgRole.permissions.map(String)
: [];
return permissionsWithTreasuryOverride(
rolePermissions,
parseUserTreasuryAccess(membership?.treasuryAccessOverride),
);
}
private async assertDocumentsManage(actor: Actor) {
if (canManageTreasuryDocuments(actor.role, await this.actorPermissions(actor))) return;
throw new ForbiddenException('اجازه ویرایش یا حذف اسناد را ندارید.');
}
private async requireScopedDocument(actor: Actor, id: string) {
const scope = await this.accountScope(actor);
const doc = await this.prisma.financialDocument.findFirst({
where: {
id,
organizationId: actor.organizationId,
...(scope ? { OR: [{ accountId: null }, { accountId: { in: scope } }] } : {}),
},
include: {
category: true,
account: true,
movements: true,
attachments: { select: { id: true, fileName: true, mimeType: true } },
},
});
if (!doc) throw new NotFoundException('سند پیدا نشد.');
return doc;
}
private async accountScope(actor: Actor): Promise<string[] | null> {
if (actor.role === 'owner' || actor.role === 'admin') return null;
const membership = await this.prisma.membership.findFirst({
@@ -1566,7 +1667,8 @@ export class TreasuryService {
category?: { name: string } | null;
account?: { name: string } | null;
movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | null }>;
attachments?: Array<{ id: string; fileName: string }>;
attachments?: Array<{ id: string; fileName: string; mimeType?: string }>;
voidedAt?: Date | null;
}): FinancialDocumentDto {
const settled = this.settledOf(row.movements);
const rawRemaining = row.amount.minus(settled);
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';
import type { CustomerGroupDto, PersonImportSourceStatDto, PersonMood } from '@mento/shared';
import { ACTIVITY_EXPERIENCE_OPTIONS } from '@mento/shared';
import { PERSON_MOOD_LABELS, PERSON_MOODS } from '@/lib/person-mood';
import { groupSwatch } from '@/lib/customer-groups';
import { toFaDigits } from '@/lib/jalali';
@@ -12,6 +13,7 @@ export type ContactsFilterValue = {
sources: string[];
moods: PersonMood[];
disc: string;
activityExperiences: string[];
};
const props = defineProps<{
@@ -33,7 +35,13 @@ const emit = defineEmits<{
close: [];
}>();
const draft = reactive<ContactsFilterValue>({ groups: [], sources: [], moods: [], disc: '' });
const draft = reactive<ContactsFilterValue>({
groups: [],
sources: [],
moods: [],
disc: '',
activityExperiences: [],
});
const draftSort = ref('');
const groupQuery = ref('');
const GROUP_SEARCH_MIN = 8;
@@ -50,6 +58,7 @@ watch(
draft.sources = [...props.value.sources];
draft.moods = [...props.value.moods];
draft.disc = props.value.disc;
draft.activityExperiences = [...(props.value.activityExperiences ?? [])];
draftSort.value = props.sort ?? defaultSort.value;
groupQuery.value = '';
},
@@ -77,7 +86,12 @@ const filteredGroups = computed(() => {
const draftCount = computed(
() =>
draft.groups.length +
(isPeople.value ? draft.sources.length + draft.moods.length + (draft.disc ? 1 : 0) : 0) +
(isPeople.value
? draft.sources.length +
draft.moods.length +
draft.activityExperiences.length +
(draft.disc ? 1 : 0)
: 0) +
(hasSort.value && draftSort.value !== defaultSort.value ? 1 : 0),
);
@@ -92,6 +106,7 @@ function clearAll() {
draft.sources = [];
draft.moods = [];
draft.disc = '';
draft.activityExperiences = [];
if (hasSort.value) draftSort.value = defaultSort.value;
}
@@ -103,6 +118,7 @@ function apply() {
sources: [...draft.sources],
moods: [...draft.moods],
disc: draft.disc,
activityExperiences: [...draft.activityExperiences],
},
hasSort.value ? draftSort.value : undefined,
);
@@ -210,6 +226,27 @@ function apply() {
</div>
</section>
<section class="sec">
<h4>
سابقه فعالیت
<span v-if="draft.activityExperiences.length" class="sel">
{{ toFaDigits(draft.activityExperiences.length) }} انتخاب
</span>
</h4>
<div class="pills">
<button
v-for="item in ACTIVITY_EXPERIENCE_OPTIONS"
:key="item"
type="button"
class="pill"
:class="{ on: draft.activityExperiences.includes(item) }"
@click="toggle(draft.activityExperiences, item)"
>
{{ item }}
</button>
</div>
</section>
<section v-if="canBehavior" class="sec">
<h4>تیپ DISC</h4>
<div class="pills">
@@ -158,6 +158,7 @@ function toCard(item: ActivityDto, stageId: string): PipelineDeal {
assigneeIds: (item.assignees ?? []).map((a) => a.id),
priority: item.priority,
activityStatus: item.status,
accountBalance: item.accountBalance ?? null,
};
}
@@ -0,0 +1,94 @@
<script setup lang="ts">
import { computed } from 'vue';
import { theme } from 'ant-design-vue';
import type { ActivityAccountBalanceDto } from '@mento/shared';
import { formatTahesabBedBes } from '@/lib/tahesab';
const props = withDefaults(
defineProps<{
balance: ActivityAccountBalanceDto | null | undefined;
/** فشرده‌تر برای کارت کانبان */
compact?: boolean;
}>(),
{ compact: false },
);
const { token } = theme.useToken();
type Line = {
key: string;
label: string;
text: string;
value: number | null;
};
const lines = computed<Line[]>(() => {
const bal = props.balance;
if (!bal) return [];
const out: Line[] = [];
if (bal.rialBalance != null && Number.isFinite(bal.rialBalance)) {
out.push({
key: 'rial',
label: 'مانده ریالی',
text: `${formatTahesabBedBes(bal.rialBalance, 0)} ریال`,
value: bal.rialBalance,
});
}
for (const w of bal.weights ?? []) {
if (w.value == null || !Number.isFinite(w.value)) continue;
out.push({
key: w.key,
label: w.label,
text: `${formatTahesabBedBes(w.value, 3)} گرم`,
value: w.value,
});
}
return out;
});
const visible = computed(() => lines.value.length > 0);
function toneColor(value: number | null) {
if (value == null || !Number.isFinite(value) || value === 0) {
return token.value.colorTextSecondary;
}
return value < 0 ? token.value.colorError : token.value.colorSuccess;
}
</script>
<template>
<a-flex
v-if="visible"
vertical
:gap="compact ? 2 : 4"
:style="{ minWidth: 0, width: '100%' }"
>
<a-typography-text
v-for="line in lines"
:key="line.key"
dir="ltr"
:style="{
margin: 0,
display: 'block',
fontSize: `${compact ? token.fontSizeSM : token.fontSize}px`,
fontWeight: 600,
color: toneColor(line.value),
textAlign: 'right',
direction: 'rtl',
}"
:title="`${line.label}: ${line.text}`"
>
<a-typography-text
type="secondary"
:style="{
fontSize: `${token.fontSizeSM}px`,
fontWeight: 500,
marginInlineEnd: '6px',
}"
>
{{ line.label }}:
</a-typography-text>
{{ line.text }}
</a-typography-text>
</a-flex>
</template>
@@ -16,7 +16,11 @@ import type { ActivityDto, ActivityType, OrganizationDto, OrgUserDto } from '@me
const props = defineProps<{
activity: ActivityDto;
saving?: boolean;
save: (payload: { text: string; photoOnly: boolean }) => Promise<void>;
save: (payload: {
text: string;
photoOnly: boolean;
attachmentIds?: string[];
}) => Promise<void>;
/** بالاتر از مودال خلاصهٔ فعالیت */
overlayZIndex?: number;
}>();
@@ -233,28 +237,35 @@ async function toggleVoiceNote() {
}
}
async function uploadQueue(items: Array<{ localId: string; name: string; file: File }>, drop: (localId: string) => void) {
async function uploadQueue(
items: Array<{ localId: string; name: string; file: File }>,
drop: (localId: string) => void,
): Promise<string[]> {
const ids: string[] = [];
for (const item of items) {
const form = new FormData();
form.append('file', item.file, item.name);
await api.post(`/activities/${props.activity.id}/images`, form);
const { data } = await api.post<{ id: string }>(`/activities/${props.activity.id}/images`, form);
ids.push(data.id);
drop(item.localId);
uploadedCount.value += 1;
}
return ids;
}
async function uploadPendingPhotos() {
await uploadQueue([...pendingPhotos.value], (localId) => {
async function uploadPendingPhotos(): Promise<string[]> {
const photoIds = await uploadQueue([...pendingPhotos.value], (localId) => {
pendingPhotos.value = pendingPhotos.value.filter((item) => item.localId !== localId);
});
await uploadQueue([...pendingVoices.value], (localId) => {
const voiceIds = await uploadQueue([...pendingVoices.value], (localId) => {
const voice = pendingVoices.value.find((item) => item.localId === localId);
if (voice) URL.revokeObjectURL(voice.url);
pendingVoices.value = pendingVoices.value.filter((item) => item.localId !== localId);
});
await uploadQueue([...pendingFiles.value], (localId) => {
const fileIds = await uploadQueue([...pendingFiles.value], (localId) => {
pendingFiles.value = pendingFiles.value.filter((item) => item.localId !== localId);
});
return [...photoIds, ...voiceIds, ...fileIds];
}
async function submit() {
@@ -268,11 +279,15 @@ async function submit() {
pendingFiles.value.length > 0 ||
uploadedCount.value > 0;
try {
await uploadPendingPhotos();
await props.save({ text, photoOnly: hadPhoto && !text });
const attachmentIds = await uploadPendingPhotos();
await props.save({
text,
photoOnly: hadPhoto && !text,
attachmentIds,
});
} catch (error) {
photoError.value =
pendingPhotos.value.length > 0
pendingPhotos.value.length > 0 || pendingFiles.value.length > 0 || pendingVoices.value.length > 0
? apiMessage(error, 'افزودن فایل ناموفق بود.')
: apiMessage(error, 'ثبت نظر ناموفق بود.');
} finally {
@@ -31,6 +31,7 @@ import {
import { useAuthStore } from '@/stores/auth';
import { canCollaborateOnActivity, canMutateActivity } from '@/lib/activity-access';
import ActivityCommentSheet from '@/components/activities/ActivityCommentSheet.vue';
import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
const props = defineProps<{
@@ -309,17 +310,35 @@ function apiMessage(e: unknown, fallback: string) {
return fallback;
}
function viewMedia(item: NoteMedia) {
window.open(item.url, '_blank', 'noopener,noreferrer');
}
function downloadMedia(item: NoteMedia) {
const link = document.createElement('a');
link.href = item.url;
link.download = item.name || 'file';
link.rel = 'noopener';
document.body.appendChild(link);
link.click();
link.remove();
}
async function loadNoteMedia(row: ActivityDto) {
clearNoteMedia();
const next: NoteMedia[] = [];
for (const image of row.images ?? []) {
const mime = image.mimeType.toLowerCase();
const mime = (image.mimeType || 'application/octet-stream').toLowerCase();
const kind = mime.startsWith('audio/') ? 'audio' : mime.startsWith('image/') ? 'image' : 'file';
try {
const { data } = await api.get<Blob>(`/activities/${row.id}/images/${image.id}`, {
responseType: 'blob',
});
const url = URL.createObjectURL(data);
const blob =
data.type && data.type !== 'application/octet-stream' && !data.type.includes('json')
? data
: new Blob([data], { type: mime });
const url = URL.createObjectURL(blob);
if (props.activityId !== row.id) {
URL.revokeObjectURL(url);
continue;
@@ -425,7 +444,7 @@ async function runAction() {
const { data } = await api.patch<ActivityDto>(`/activities/${id}/complete`, undefined, {
params: undo ? { undo: '1' } : undefined,
});
if (data.status === 'done') {
if (data.status === 'done' || (!undo && data.completionMode === 'all')) {
emit('changed');
emit('close');
return;
@@ -455,10 +474,14 @@ async function postponeTo(iso: string) {
}
}
async function submitComment(payload: { text: string; photoOnly: boolean }) {
async function submitComment(payload: {
text: string;
photoOnly: boolean;
attachmentIds?: string[];
}) {
const id = props.activityId;
const row = activity.value;
const body = payload.text.trim() || (payload.photoOnly ? 'عکس پیوست شد.' : '');
const body = payload.text.trim() || (payload.photoOnly ? 'فایل پیوست شد.' : '');
if (!id || !row || !body) return;
saving.value = true;
error.value = '';
@@ -467,7 +490,9 @@ async function submitComment(payload: { text: string; photoOnly: boolean }) {
const now = new Date();
const author = auth.user?.fullName?.trim();
const stamp = `[${formatJalaliNumeric(now)} ساعت ${formatClockFa(now)}${author ? ` — ${author}` : ''}]`;
const entry = `${stamp}\n${body}`;
const ids = [...new Set((payload.attachmentIds ?? []).filter(Boolean))];
const attachLine = ids.length ? `\n[[attachments:${ids.join(',')}]]` : '';
const entry = `${stamp}\n${body}${attachLine}`;
await api.patch(`/activities/${id}`, { description: prev ? `${prev}\n\n${entry}` : entry });
commentOpen.value = false;
await load(id);
@@ -531,6 +556,16 @@ function openFull() {
</a-col>
</a-row>
<div
v-if="activity.accountBalance"
:style="{ marginTop: '12px' }"
>
<a-typography-text type="secondary" :style="{ display: 'block', marginBottom: '4px' }">
مانده حساب
</a-typography-text>
<ActivityAccountBalances :balance="activity.accountBalance" />
</div>
<a-divider :style="{ margin: '16px 0 12px' }" />
<a-flex justify="space-between" align="center" :style="{ marginBottom: '8px' }">
<a-typography-text strong>یادداشت</a-typography-text>
@@ -597,11 +632,60 @@ function openFull() {
:preview="{ zIndex: 1300 }"
/>
</a-flex>
<a-flex
v-if="entry.media.some((item) => item.kind === 'audio')"
vertical
:gap="8"
:style="{ marginTop: '8px' }"
>
<audio
v-for="voice in entry.media.filter((item) => item.kind === 'audio')"
:key="voice.id"
:src="voice.url"
controls
preload="metadata"
style="width: 100%"
/>
</a-flex>
<a-flex
v-if="entry.media.some((item) => item.kind === 'file')"
vertical
:gap="4"
:style="{ marginTop: '8px' }"
>
<a-flex
v-for="file in entry.media.filter((item) => item.kind === 'file')"
:key="file.id"
align="center"
justify="space-between"
:gap="8"
wrap="wrap"
>
<a-typography-text>{{ file.name }}</a-typography-text>
<a-space :size="4">
<a-button type="link" @click="viewMedia(file)">مشاهده</a-button>
<a-button type="link" @click="downloadMedia(file)">دانلود</a-button>
</a-space>
</a-flex>
</a-flex>
</div>
<div v-for="image in threadBlocks.loose.filter((item) => item.kind === 'image')" :key="image.id" :style="noteBubbleStyle">
<a-image :src="image.url" :alt="image.name" :width="72"
:height="72" :preview="{ zIndex: 1300 }" />
</div>
<div
v-for="file in threadBlocks.loose.filter((item) => item.kind === 'file')"
:key="file.id"
:style="noteBubbleStyle"
>
<a-flex align="center" justify="space-between" :gap="8" wrap="wrap">
<a-typography-text>{{ file.name }}</a-typography-text>
<a-space :size="4">
<a-button type="link" @click="viewMedia(file)">مشاهده</a-button>
<a-button type="link" @click="downloadMedia(file)">دانلود</a-button>
</a-space>
</a-flex>
</div>
</a-flex>
<div v-else-if="plainNote || looseImages.length" :style="noteBubbleStyle">
<a-typography-paragraph v-if="plainNote" :style="{ margin: 0, whiteSpace: 'pre-wrap' }">
@@ -20,6 +20,7 @@ import {
theme,
} from 'ant-design-vue';
import DealQuickActivityPopover from '@/components/pipeline/DealQuickActivityPopover.vue';
import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue';
import { calendarDaysBetween, formatJalaliNumeric } from '@/lib/jalali';
import { userAvatarSrc } from '@/lib/userAvatars';
import type { PipelineAccent, PipelineDeal, PipelineUiCopy } from '@/lib/pipeline-board';
@@ -244,6 +245,12 @@ const cardStyle = computed(() => ({
>
{{ deal.description }}
</a-typography-text>
<ActivityAccountBalances
v-if="deal.accountBalance"
:balance="deal.accountBalance"
compact
:style="{ marginTop: '6px' }"
/>
</div>
<span :data-card-id="deal.id">
@@ -0,0 +1,89 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { Button as AButton, Upload as AUpload, message } from 'ant-design-vue';
import type { UploadFile, UploadProps } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { FormFileTooLargeError, prepareFormFieldFile } from '@/lib/form-file-compress';
import type { TreasuryPendingPhoto } from '@/lib/treasury-doc-photos';
export type { TreasuryPendingPhoto };
const PHOTO_LIMIT = 8;
const props = withDefaults(
defineProps<{
disabled?: boolean;
}>(),
{ disabled: false },
);
const model = defineModel<TreasuryPendingPhoto[]>({ default: () => [] });
const busy = ref(false);
const fileList = computed<UploadFile[]>(() =>
model.value.map((photo) => ({
uid: photo.localId,
name: photo.name,
status: 'done',
url: photo.dataUrl,
})),
);
const beforeUpload: UploadProps['beforeUpload'] = async (file) => {
if (props.disabled || busy.value) return AUpload.LIST_IGNORE;
if (model.value.length >= PHOTO_LIMIT) {
message.warning(`حداکثر ${PHOTO_LIMIT} عکس برای هر سند.`);
return AUpload.LIST_IGNORE;
}
const raw = file as File;
if (!raw.type.startsWith('image/')) {
message.error('فقط فایل تصویری مجاز است.');
return AUpload.LIST_IGNORE;
}
busy.value = true;
try {
const prepared = await prepareFormFieldFile(raw);
model.value = [
...model.value,
{
localId: crypto.randomUUID(),
name: prepared.name,
dataUrl: prepared.dataUrl,
file: prepared.file,
},
];
} catch (e) {
if (e instanceof FormFileTooLargeError) {
message.error('حجم عکس باید زیر ۲۰۰ کیلوبایت باشد');
} else {
message.error('فشرده‌سازی عکس ناموفق بود.');
}
} finally {
busy.value = false;
}
return AUpload.LIST_IGNORE;
};
const onRemove: UploadProps['onRemove'] = (file) => {
if (props.disabled || busy.value) return false;
model.value = model.value.filter((photo) => photo.localId !== file.uid);
return true;
};
</script>
<template>
<AUpload
list-type="picture"
accept="image/*"
:file-list="fileList"
:disabled="disabled || busy || model.length >= PHOTO_LIMIT"
:before-upload="beforeUpload"
:on-remove="onRemove"
multiple
>
<AButton :disabled="disabled || busy || model.length >= PHOTO_LIMIT">
<template #icon><UploadOutlined /></template>
{{ busy ? 'آماده‌سازی…' : 'افزودن عکس' }}
</AButton>
</AUpload>
</template>
@@ -0,0 +1,626 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue';
import axios from 'axios';
import {
Button as AButton,
Card as ACard,
Col as ACol,
Descriptions as ADescriptions,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Image as AImage,
Input as AInput,
Modal as AModal,
Row as ARow,
Select as ASelect,
Space as ASpace,
Table as ATable,
Tag as ATag,
Tooltip as ATooltip,
Typography,
message,
theme,
} from 'ant-design-vue';
import {
DeleteOutlined,
EditOutlined,
EyeOutlined,
StopOutlined,
} from '@ant-design/icons-vue';
import {
canManageTreasuryDocuments,
type FinancialCategoryDto,
type FinancialDocumentDto,
} from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue';
import { api } from '@/lib/api';
import { formatJalaliNumeric, formatLocalDateInput } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
import { useAuthStore } from '@/stores/auth';
import { toman } from '@/views/treasury/treasury-format';
import { useTreasuryListPaging } from '@/views/treasury/useTreasuryListPaging';
import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
const props = defineProps<{
rows: FinancialDocumentDto[];
categories: FinancialCategoryDto[];
statusLabel: Record<string, string>;
q: string;
}>();
const emit = defineEmits<{
'update:q': [value: string];
reload: [];
}>();
const { Text: ATypographyText } = Typography;
const ASelectOption = ASelect.Option;
const ADescriptionsItem = ADescriptions.Item;
const AImagePreviewGroup = AImage.PreviewGroup;
const { token } = theme.useToken();
const auth = useAuthStore();
const isMobile = useTreasuryMobile();
const canManage = computed(() =>
canManageTreasuryDocuments(auth.user?.role, auth.user?.permissions),
);
const methodLabel: Record<string, string> = {
cash: 'نقدی',
card_to_card: 'کارت‌به‌کارت',
pos: 'کارت‌خوان',
transfer: 'حواله',
other: 'سایر',
};
const methodOptions = [
{ value: 'cash', label: 'نقدی' },
{ value: 'card_to_card', label: 'کارت‌به‌کارت' },
{ value: 'pos', label: 'کارت‌خوان' },
{ value: 'transfer', label: 'حواله' },
{ value: 'other', label: 'سایر' },
];
const statusColor: Record<string, string> = {
open: 'default',
partial: 'processing',
settled: 'success',
void: 'error',
};
const detailOpen = ref(false);
const detailLoading = ref(false);
const detail = ref<FinancialDocumentDto | null>(null);
const previewUrls = ref<Record<string, string>>({});
const editOpen = ref(false);
const editSaving = ref(false);
const editId = ref<string | null>(null);
const {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
resetPage,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => props.rows, 'treasury.documents');
const editForm = reactive({
title: '',
notes: '',
categoryId: undefined as string | undefined,
method: undefined as string | undefined,
bookedAt: '',
amount: '',
});
const editAmountLocked = ref(true);
function apiMessage(e: unknown) {
if (!axios.isAxiosError(e)) return 'عملیات ناموفق بود.';
const msg = (e.response?.data as { message?: string | string[] })?.message;
return Array.isArray(msg) ? msg.join('، ') : msg || 'عملیات ناموفق بود.';
}
function clearPreviews() {
for (const url of Object.values(previewUrls.value)) {
URL.revokeObjectURL(url);
}
previewUrls.value = {};
}
onBeforeUnmount(clearPreviews);
watch(detailOpen, (open) => {
if (!open) {
clearPreviews();
detail.value = null;
}
});
async function loadAttachmentPreview(id: string, mimeType?: string) {
if (previewUrls.value[id]) return;
if (mimeType && !mimeType.startsWith('image/')) return;
try {
const { data } = await api.get<Blob>(`/treasury/attachments/${id}`, { responseType: 'blob' });
if (!data || data.type.includes('json') || data.size === 0) return;
if (data.type && !data.type.startsWith('image/')) return;
previewUrls.value = { ...previewUrls.value, [id]: URL.createObjectURL(data) };
} catch {
/* ignore preview failures */
}
}
async function openDetail(row: FinancialDocumentDto) {
detailOpen.value = true;
detailLoading.value = true;
detail.value = row;
clearPreviews();
try {
const { data } = await api.get<FinancialDocumentDto>(`/treasury/documents/${row.id}`);
detail.value = data;
await Promise.all(
(data.attachments ?? []).map((att) => loadAttachmentPreview(att.id, att.mimeType)),
);
} catch (e) {
message.error(apiMessage(e));
} finally {
detailLoading.value = false;
}
}
function openEdit(row: FinancialDocumentDto) {
editId.value = row.id;
editForm.title = row.title;
editForm.notes = row.notes ?? '';
editForm.categoryId = row.categoryId ?? undefined;
editForm.method = row.method ?? undefined;
editForm.bookedAt = formatLocalDateInput(new Date(row.bookedAt));
editForm.amount = String(row.amount ?? '');
editAmountLocked.value = row.status !== 'open' || Number(row.settledAmount) > 0;
editOpen.value = true;
}
async function saveEdit() {
if (!editId.value) return;
const title = editForm.title.trim();
if (title.length < 2) {
message.warning('عنوان را وارد کنید.');
return;
}
editSaving.value = true;
try {
const body: Record<string, unknown> = {
title,
notes: editForm.notes.trim() || null,
categoryId: editForm.categoryId || null,
method: editForm.method || null,
bookedAt: editForm.bookedAt || undefined,
};
if (!editAmountLocked.value) {
const amount = parseMoneyNumber(String(editForm.amount ?? ''), 0) ?? 0;
if (amount <= 0) {
message.warning('مبلغ معتبر نیست.');
editSaving.value = false;
return;
}
body.amount = amount;
}
await api.patch(`/treasury/documents/${editId.value}`, body);
message.success('سند به‌روز شد.');
editOpen.value = false;
emit('reload');
} catch (e) {
message.error(apiMessage(e));
} finally {
editSaving.value = false;
}
}
function confirmVoid(row: FinancialDocumentDto) {
AModal.confirm({
title: 'ابطال سند',
content: 'این سند و گردش متصل به آن باطل شود؟',
okText: 'ابطال',
okType: 'danger',
cancelText: 'انصراف',
centered: true,
async onOk() {
try {
await api.post(`/treasury/documents/${row.id}/void`, { reason: 'ابطال توسط کاربر' });
message.success('سند باطل شد.');
emit('reload');
} catch (e) {
message.error(apiMessage(e));
throw e;
}
},
});
}
function confirmDelete(row: FinancialDocumentDto) {
AModal.confirm({
title: 'حذف سند',
content:
row.status === 'void'
? 'سند باطل‌شده برای همیشه حذف شود؟'
: 'سند بدون گردش برای همیشه حذف شود؟ در صورت داشتن دریافت/پرداخت ابتدا ابطال کنید.',
okText: 'حذف',
okType: 'danger',
cancelText: 'انصراف',
centered: true,
async onOk() {
try {
await api.delete(`/treasury/documents/${row.id}`);
message.success('سند حذف شد.');
emit('reload');
} catch (e) {
message.error(apiMessage(e));
throw e;
}
},
});
}
async function downloadAttachment(id: string, fileName: string) {
try {
const { data } = await api.get<Blob>(`/treasury/attachments/${id}`, { responseType: 'blob' });
const url = URL.createObjectURL(data);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
} catch (e) {
message.error(apiMessage(e));
}
}
const columns = computed(() => {
const cols = [
{ title: 'پیگیری', dataIndex: 'reference', key: 'reference', width: 150 },
{ title: 'عنوان', dataIndex: 'title', key: 'title' },
{ title: 'طرف حساب', dataIndex: 'partyName', key: 'partyName', width: 140 },
{ title: 'دسته', dataIndex: 'categoryName', key: 'categoryName', width: 120 },
{ title: 'مبلغ', key: 'amount', width: 130 },
{ title: 'مانده', key: 'remaining', width: 130 },
{ title: 'وضعیت', key: 'status', width: 110 },
{ title: 'تاریخ', key: 'bookedAt', width: 110 },
{ title: 'عملیات', key: 'actions', width: canManage.value ? 160 : 80 },
];
return cols;
});
const searchModel = computed({
get: () => props.q,
set: (value: string) => emit('update:q', value),
});
function onSearch() {
resetPage();
emit('reload');
}
function asDoc(record: unknown): FinancialDocumentDto {
return record as FinancialDocumentDto;
}
function modalContainer() {
return document.body;
}
</script>
<template>
<a-card :bordered="false" title="فهرست اسناد">
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="جستجو">
<a-input
v-model:value="searchModel"
allow-clear
placeholder="عنوان یا شماره پیگیری"
@press-enter="onSearch"
@change="onSearch"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-empty v-if="!rows.length" description="سندی نیست." />
<a-table
v-else-if="!isMobile"
:columns="columns"
:data-source="pagedRows"
:pagination="false"
:scroll="{ x: 1100 }"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'partyName'">
{{ record.partyName || 'بدون طرف حساب' }}
</template>
<template v-else-if="column.key === 'categoryName'">
{{ record.categoryName || '—' }}
</template>
<template v-else-if="column.key === 'amount'">
{{ toman(record.amount) }}
</template>
<template v-else-if="column.key === 'remaining'">
{{ toman(record.remaining) }}
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="statusColor[record.status] || 'default'">
{{ statusLabel[record.status] ?? record.status }}
</a-tag>
</template>
<template v-else-if="column.key === 'bookedAt'">
{{ formatJalaliNumeric(new Date(record.bookedAt)) }}
</template>
<template v-else-if="column.key === 'actions'">
<a-space :size="4">
<a-tooltip title="جزئیات">
<a-button
type="text"
aria-label="جزئیات"
:style="{ color: token.colorInfo }"
@click="openDetail(asDoc(record))"
>
<template #icon><EyeOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage && record.status !== 'void'" title="ویرایش">
<a-button
type="text"
aria-label="ویرایش"
:style="{ color: token.colorPrimary }"
@click="openEdit(asDoc(record))"
>
<template #icon><EditOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="record.status !== 'void'" title="ابطال">
<a-button
type="text"
aria-label="ابطال"
:style="{ color: token.colorWarning }"
@click="confirmVoid(asDoc(record))"
>
<template #icon><StopOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage" title="حذف">
<a-button
type="text"
aria-label="حذف"
:style="{ color: token.colorError }"
@click="confirmDelete(asDoc(record))"
>
<template #icon><DeleteOutlined /></template>
</a-button>
</a-tooltip>
</a-space>
</template>
</template>
</a-table>
<a-flex v-else vertical :gap="12">
<a-card v-for="item in pagedRows" :key="item.id" :bordered="true">
<a-flex vertical :gap="8">
<a-flex justify="space-between" align="flex-start" wrap="wrap" :gap="8">
<a-typography-text strong>{{ item.title }}</a-typography-text>
<a-tag :color="statusColor[item.status] || 'default'">
{{ statusLabel[item.status] ?? item.status }}
</a-tag>
</a-flex>
<a-typography-text type="secondary">
{{ item.reference ? `پیگیری ${item.reference}` : 'بدون پیگیری' }}
· {{ item.partyName || 'بدون طرف حساب' }}
</a-typography-text>
<a-typography-text v-if="item.categoryName" type="secondary">
{{ item.categoryName }}
</a-typography-text>
<a-flex justify="space-between" wrap="wrap" :gap="8">
<a-typography-text>مبلغ {{ toman(item.amount) }}</a-typography-text>
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
</a-flex>
<a-typography-text type="secondary">
{{ formatJalaliNumeric(new Date(item.bookedAt)) }}
</a-typography-text>
<a-space wrap :size="4">
<a-tooltip title="جزئیات">
<a-button
type="text"
aria-label="جزئیات"
:style="{ color: token.colorInfo }"
@click="openDetail(item)"
>
<template #icon><EyeOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage && item.status !== 'void'" title="ویرایش">
<a-button
type="text"
aria-label="ویرایش"
:style="{ color: token.colorPrimary }"
@click="openEdit(item)"
>
<template #icon><EditOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="item.status !== 'void'" title="ابطال">
<a-button
type="text"
aria-label="ابطال"
:style="{ color: token.colorWarning }"
@click="confirmVoid(item)"
>
<template #icon><StopOutlined /></template>
</a-button>
</a-tooltip>
<a-tooltip v-if="canManage" title="حذف">
<a-button
type="text"
aria-label="حذف"
:style="{ color: token.colorError }"
@click="confirmDelete(item)"
>
<template #icon><DeleteOutlined /></template>
</a-button>
</a-tooltip>
</a-space>
</a-flex>
</a-card>
</a-flex>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</a-card>
<a-modal
v-model:open="detailOpen"
title="جزئیات سند"
:footer="null"
:width="isMobile ? '100%' : 720"
:get-container="modalContainer"
centered
destroy-on-close
>
<a-flex v-if="detailLoading && !detail" justify="center">
<a-typography-text type="secondary">در حال بارگذاری…</a-typography-text>
</a-flex>
<template v-else-if="detail">
<a-descriptions :column="1" bordered>
<a-descriptions-item label="عنوان">{{ detail.title }}</a-descriptions-item>
<a-descriptions-item label="پیگیری">{{ detail.reference || '—' }}</a-descriptions-item>
<a-descriptions-item label="طرف حساب">{{ detail.partyName || 'بدون طرف حساب' }}</a-descriptions-item>
<a-descriptions-item label="دسته">{{ detail.categoryName || '—' }}</a-descriptions-item>
<a-descriptions-item label="حساب">{{ detail.accountName || '—' }}</a-descriptions-item>
<a-descriptions-item label="روش">
{{ detail.method ? methodLabel[detail.method] || detail.method : '—' }}
</a-descriptions-item>
<a-descriptions-item label="مبلغ">{{ toman(detail.amount) }}</a-descriptions-item>
<a-descriptions-item label="تسویه">{{ toman(detail.settledAmount) }}</a-descriptions-item>
<a-descriptions-item label="مانده">{{ toman(detail.remaining) }}</a-descriptions-item>
<a-descriptions-item label="وضعیت">
{{ statusLabel[detail.status] ?? detail.status }}
</a-descriptions-item>
<a-descriptions-item label="تاریخ">
{{ formatJalaliNumeric(new Date(detail.bookedAt)) }}
</a-descriptions-item>
<a-descriptions-item label="یادداشت">{{ detail.notes || '—' }}</a-descriptions-item>
</a-descriptions>
<a-flex vertical :gap="12" style="margin-top: 16px">
<a-typography-text strong>پیوست‌ها</a-typography-text>
<a-empty
v-if="!(detail.attachments && detail.attachments.length)"
description="پیوستی نیست."
/>
<a-image-preview-group v-else>
<a-row :gutter="[12, 12]">
<a-col
v-for="att in detail.attachments"
:key="att.id"
:xs="24"
:sm="12"
:md="8"
>
<a-card :bordered="true">
<a-flex vertical :gap="8" align="center">
<a-image
v-if="previewUrls[att.id]"
:src="previewUrls[att.id]"
:alt="att.fileName"
style="width: 100%"
/>
<a-typography-text v-else type="secondary">{{ att.fileName }}</a-typography-text>
<a-button type="link" @click="downloadAttachment(att.id, att.fileName)">
دانلود
</a-button>
</a-flex>
</a-card>
</a-col>
</a-row>
</a-image-preview-group>
</a-flex>
</template>
</a-modal>
<a-modal
v-model:open="editOpen"
title="ویرایش سند"
ok-text="ذخیره"
cancel-text="انصراف"
:confirm-loading="editSaving"
:width="isMobile ? '100%' : 560"
:get-container="modalContainer"
centered
destroy-on-close
@ok="saveEdit"
>
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :span="24">
<a-form-item label="عنوان" required>
<a-input v-model:value="editForm.title" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تاریخ">
<JalaliDateInput v-model="editForm.bookedAt" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="روش">
<a-select
v-model:value="editForm.method"
allow-clear
placeholder="روش"
style="width: 100%"
>
<a-select-option v-for="opt in methodOptions" :key="opt.value" :value="opt.value">
{{ opt.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="دسته‌بندی">
<a-select
v-model:value="editForm.categoryId"
allow-clear
show-search
option-filter-prop="label"
placeholder="دسته"
style="width: 100%"
:options="categories.map((c) => ({ value: c.id, label: c.name }))"
/>
</a-form-item>
</a-col>
<a-col v-if="!editAmountLocked" :xs="24" :md="12">
<a-form-item label="مبلغ">
<MoneyInput v-model="editForm.amount" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="یادداشت">
<a-input v-model:value="editForm.notes" />
</a-form-item>
</a-col>
</a-row>
</a-form>
</a-modal>
</template>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { Pagination as APagination } from 'ant-design-vue';
const page = defineModel<number>('page', { required: true });
defineProps<{
total: number;
pageSize: number;
pageSizeOptions: string[];
showTotal: (total: number) => string;
}>();
const emit = defineEmits<{
'update:pageSize': [size: number];
}>();
</script>
<template>
<a-pagination
v-if="total > 0"
v-model:current="page"
:page-size="pageSize"
:total="total"
:page-size-options="pageSizeOptions"
show-size-changer
:show-total="showTotal"
style="margin-top: 16px"
@update:page-size="emit('update:pageSize', $event)"
/>
</template>
@@ -7,7 +7,9 @@ import {
Typography,
} from 'ant-design-vue';
import type { TreasuryPartyBalanceDto } from '@mento/shared';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from '@/views/treasury/treasury-format';
import { useTreasuryListPaging } from '@/views/treasury/useTreasuryListPaging';
import { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile';
const props = defineProps<{
@@ -19,6 +21,16 @@ const isMobile = useTreasuryMobile();
const { Text: ATypographyText } = Typography;
const AListItem = AList.Item;
const {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => props.rows, 'treasury.party-balances');
const kindLabel: Record<string, string> = {
person: 'مشتری',
company: 'شرکت',
@@ -58,7 +70,7 @@ function kindOf(record: TreasuryPartyBalanceDto) {
<template>
<a-list
v-if="isMobile"
:data-source="rows"
:data-source="pagedRows"
:locale="{ emptyText: 'مانده‌ای نیست.' }"
>
<template #renderItem="{ item }">
@@ -87,9 +99,17 @@ function kindOf(record: TreasuryPartyBalanceDto) {
<a-table
v-else
:columns="columns"
:data-source="rows"
:data-source="pagedRows"
:pagination="false"
row-key="key"
:locale="{ emptyText: 'مانده‌ای نیست.' }"
/>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</template>
+6
View File
@@ -129,6 +129,12 @@ export function isBirthDateAnswer(label: string): boolean {
return label.trim() === 'تاریخ تولد';
}
/** فیلد سابقه فعالیت روی خود لید/مشتری هست؛ جواب فرم نباید دوباره ردیف بسازد. */
export function isActivityExperienceAnswer(label: string): boolean {
const text = label.trim().replace(/ي/g, 'ی').replace(/ك/g, 'ک');
return /سابقه\s*فعالیت/.test(text);
}
function parseAnswerLine(line: string): LeadNoteRow | null {
const splitAt = line.indexOf(':');
if (splitAt <= 0 || splitAt > 200) return null;
+9
View File
@@ -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',
},
],
},
{
+3
View File
@@ -1,6 +1,7 @@
import { currencySuffix } from '@/lib/money';
import { matchesSearch } from '@/lib/search';
import type {
ActivityAccountBalanceDto,
ActivityPriority,
ActivityStatus,
DealActivityCue,
@@ -39,6 +40,8 @@ export type PipelineDeal = {
activityCue?: DealActivityCue;
/** خلاصه فعالیت‌ها برای پاپ‌آپ دکمهٔ تقویم */
activitySummaries?: DealActivitySummaryDto[];
/** مانده ریالی/وزنی فقط برای کارت‌های کاریز مطالبات */
accountBalance?: ActivityAccountBalanceDto | null;
};
export type PipelineUiCopy = {
+22
View File
@@ -0,0 +1,22 @@
import { api } from '@/lib/api';
export type TreasuryPendingPhoto = {
localId: string;
name: string;
dataUrl: string;
file: File;
};
export async function uploadTreasuryDocumentPhotos(
documentId: string,
photos: TreasuryPendingPhoto[],
): Promise<number> {
let attached = 0;
for (const photo of photos) {
const body = new FormData();
body.append('file', photo.file);
await api.post(`/treasury/documents/${documentId}/attachments`, body);
attached += 1;
}
return attached;
}
+16
View File
@@ -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' };
}
@@ -0,0 +1,412 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import {
ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE,
ACCOUNT_BALANCE_WEIGHT_KEYS,
ACCOUNT_BALANCE_WEIGHT_LABELS,
type AccountBalanceCriterionMode,
type AccountBalanceEvaluateResultDto,
type AccountBalanceRangeDto,
type AccountBalanceSettingsDto,
type UpdateAccountBalanceSettingsRequest,
} from '@mento/shared';
import MoneyInput from '@/components/MoneyInput.vue';
import { parseMoneyNumber } from '@/lib/money';
import { UiButton, UiCard, UiField, UiInput, UiPageHeader } from '@/components/ui';
type RangeDraft = {
enabled: boolean;
mode: AccountBalanceCriterionMode;
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,
mode: 'all_debtors',
min: '',
max: '',
});
const weights = reactive<Record<string, RangeDraft>>(
Object.fromEntries(
ACCOUNT_BALANCE_WEIGHT_KEYS.map((key) => [
key,
{ enabled: false, mode: 'all_debtors', 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) {
const base = ACCOUNT_BALANCE_WEIGHT_LABELS[key] ?? key;
return /گرم/.test(base) ? base : `${base} (گرم)`;
}
function emptyDraft(): RangeDraft {
return { enabled: false, mode: 'all_debtors', min: '', max: '' };
}
function toDraft(range: AccountBalanceRangeDto | null | undefined): RangeDraft {
if (!range) return emptyDraft();
if (range.mode === 'all_debtors') {
return { enabled: true, mode: 'all_debtors', min: '', max: '' };
}
return {
enabled: true,
mode: 'range',
min: range.min == null ? '' : String(range.min),
max: range.max == null ? '' : String(range.max),
};
}
function parseBound(raw: string, decimals: number): number | null {
return parseMoneyNumber(String(raw ?? ''), decimals);
}
function parseDraft(draft: RangeDraft, decimals: number): AccountBalanceRangeDto | null {
if (!draft.enabled) return null;
if (draft.mode === 'all_debtors') return { mode: 'all_debtors' };
const min = parseBound(draft.min, decimals);
const max = parseBound(draft.max, decimals);
if (min == null || max == null) {
throw new Error('بازه نامعتبر');
}
return { mode: 'range', 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] ?? emptyDraft(),
3,
);
}
const body: UpdateAccountBalanceSettingsRequest = {
firstStageName: firstStageName.value.trim() || 'مطالبه مشتریان',
rial: parseDraft(rial, 0),
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;
}
}
function mergeEvaluate(
a: AccountBalanceEvaluateResultDto | null,
b: AccountBalanceEvaluateResultDto,
): AccountBalanceEvaluateResultDto {
if (!a) return b;
return {
linkedPeople: Math.max(a.linkedPeople, b.linkedPeople),
candidates: Math.max(a.candidates, b.candidates),
skippedNoAssignee: Math.max(a.skippedNoAssignee, b.skippedNoAssignee),
matched: a.matched + b.matched,
created: a.created + b.created,
reopened: a.reopened + b.reopened,
canceled: a.canceled + b.canceled,
unchanged: a.unchanged + b.unchanged,
errors: a.errors + b.errors,
message: b.message,
offset: a.offset,
limit: a.limit,
batchProcessed: a.batchProcessed + b.batchProcessed,
done: b.done,
nextOffset: b.nextOffset,
};
}
async function runEvaluate() {
evaluating.value = true;
error.value = '';
ok.value = '';
try {
let offset = 0;
let merged: AccountBalanceEvaluateResultDto | null = null;
let guard = 0;
while (guard < 100) {
guard += 1;
ok.value =
offset === 0
? 'در حال اجرای مطالبات…'
: `در حال اجرای مطالبات… (${offset.toLocaleString('fa-IR')} نفر پردازش‌شده)`;
const { data } = await api.post<AccountBalanceEvaluateResultDto>(
'/account-balances/evaluate',
{ offset, limit: ACCOUNT_BALANCE_EVALUATE_BATCH_SIZE },
);
merged = mergeEvaluate(merged, data);
if (data.done || data.nextOffset == null) break;
offset = data.nextOffset;
}
const final = merged!;
final.message =
final.message && !final.message.includes('ادامه')
? final.message
: [
`${final.candidates} واجد شرایط`,
`${final.matched} منطبق`,
`${final.created} ساخته`,
`${final.reopened} بازگشایی`,
`${final.canceled} خارج از معیار`,
].join(' · ');
ok.value = final.message;
if (final.matched === 0 && final.created === 0) {
error.value =
final.candidates === 0
? 'برای ساخت فعالیت، مشتری باید به ته‌حساب لینک باشد و حداقل در یک گروه با مسئول باشد.'
: 'هیچ مشتری‌ای با معیارهای فعال منطبق نبود. حالت تمام بدهکاران یا بازه و علامت بد/بس را بررسی کنید.';
}
} catch (e) {
error.value = axios.isAxiosError(e)
? String(
Array.isArray(e.response?.data?.message)
? e.response.data.message.join('، ')
: 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">
برای هر معیار می‌توانید «تمام بدهکاران» (مانده منفی / بد) را بدون بازه بگیرید، یا بازهٔ سفارشی
بگذارید. اعداد با همان علامت ته‌حساب هستند: منفی = بد، مثبت = بس. مانده مالی به ریال و
مانده‌های وزنی به <strong>گرم</strong> است. اگر حداقل یکی از معیارهای فعال با مانده مشتری
بخورد، فعالیت پیگیری ساخته می‌شود.
</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="criterion-body">
<div class="mode-row" role="radiogroup" aria-label="حالت مانده مالی">
<label class="mode-option">
<input v-model="rial.mode" type="radio" value="all_debtors" />
<span>تمام بدهکاران</span>
</label>
<label class="mode-option">
<input v-model="rial.mode" type="radio" value="range" />
<span>بازه</span>
</label>
</div>
<div v-if="rial.mode === 'range'" class="range-row">
<UiField label="از">
<MoneyInput
v-model="rial.min"
:decimals="0"
addon-after="ریال"
placeholder="مثلاً ۱٬۰۰۰٬۰۰۰-"
/>
</UiField>
<UiField label="تا">
<MoneyInput
v-model="rial.max"
:decimals="0"
addon-after="ریال"
placeholder="مثلاً ۰"
/>
</UiField>
</div>
<p v-else class="muted tiny">همهٔ مشتریانی که مانده مالی‌شان منفی (بد) باشد.</p>
</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="criterion-body">
<div class="mode-row" role="radiogroup" :aria-label="`حالت ${weightLabel(key)}`">
<label class="mode-option">
<input v-model="weights[key].mode" type="radio" value="all_debtors" />
<span>تمام بدهکاران</span>
</label>
<label class="mode-option">
<input v-model="weights[key].mode" type="radio" value="range" />
<span>بازه</span>
</label>
</div>
<div v-if="weights[key].mode === 'range'" class="range-row">
<UiField label="از (گرم)">
<MoneyInput
v-model="weights[key].min"
:decimals="3"
addon-after="گرم"
placeholder="مثلاً ۱۰-"
/>
</UiField>
<UiField label="تا (گرم)">
<MoneyInput
v-model="weights[key].max"
:decimals="3"
addon-after="گرم"
placeholder="مثلاً ۰"
/>
</UiField>
</div>
<p v-else class="muted tiny">همهٔ مشتریانی که این مانده وزنی‌شان منفی (بد) باشد.</p>
</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;
}
.criterion-body {
display: grid;
gap: 0.6rem;
}
.mode-row {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.mode-option {
display: inline-flex;
align-items: center;
gap: 0.4rem;
font-weight: 500;
}
.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>
+22 -5
View File
@@ -21,6 +21,7 @@ import {
import UiIcon from '@/components/UiIcon.vue';
import ExcelImportFlow from '@/components/ExcelImportFlow.vue';
import ActivitiesKanban from '@/components/activities/ActivitiesKanban.vue';
import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue';
import ActivityDeskFilters from '@/components/activities/ActivityDeskFilters.vue';
import ActivityStagesManager from '@/components/activities/ActivityStagesManager.vue';
import ActivityTypesManager from '@/components/activities/ActivityTypesManager.vue';
@@ -335,7 +336,8 @@ const sharedParams = computed<Record<string, string | undefined>>(() => ({
boardId: board.value || undefined,
filter: filter.value,
q: typeof route.query.q === 'string' && route.query.q.trim() ? route.query.q.trim() : undefined,
desk: showDeskTabs.value ? desk.value : undefined,
// همیشه desk بفرست تا سهمِ انجام‌شده از میز «من» حذف شود (حتی بدون تب تیم/من)
desk: desk.value,
typeDefId: typeof route.query.typeDefId === 'string' && route.query.typeDefId.trim()
? route.query.typeDefId.trim()
: undefined,
@@ -455,7 +457,7 @@ function deskDetailQuery(columnStageId?: string): Record<string, string> {
filter: filter.value,
};
if (board.value) query.board = board.value;
if (showDeskTabs.value) query.desk = desk.value;
query.desk = desk.value;
const search = typeof route.query.q === 'string' ? route.query.q.trim() : '';
if (search) query.q = search;
if (typeFilter.value !== 'all') query.typeDefId = typeFilter.value;
@@ -549,7 +551,7 @@ function openCreateBoard() {
}
function openEditBoard() {
if (!currentBoard.value) return;
if (!currentBoard.value || currentBoard.value.systemKey) return;
boardMemberQuery.value = '';
boardModal.value = {
mode: 'edit',
@@ -1562,7 +1564,12 @@ onUnmounted(() => {
<UiIcon name="plus" :size="14" />
گروه جدید
</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" />
ویرایش این گروه
</button>
@@ -1768,6 +1775,11 @@ onUnmounted(() => {
{{ item.title }}
</RouterLink>
<p v-if="subtitle(item)" class="sub">{{ subtitle(item) }}</p>
<ActivityAccountBalances
v-if="item.accountBalance"
:balance="item.accountBalance"
compact
/>
<p v-if="item.tags?.length" class="row-tags">
<span v-for="t in item.tags.slice(0, 3)" :key="t">#{{ t }}</span>
<span v-if="item.tags.length > 3">+{{ toFaDigits(item.tags.length - 3) }}</span>
@@ -1900,6 +1912,11 @@ onUnmounted(() => {
<UiIcon name="star" :size="14" class="star" />
</RouterLink>
<p v-if="subtitle(item)" class="sub">{{ subtitle(item) }}</p>
<ActivityAccountBalances
v-if="item.accountBalance"
:balance="item.accountBalance"
compact
/>
<p class="meta-line">
<span v-if="item.person">
<UiIcon name="user" :size="13" />
@@ -2111,7 +2128,7 @@ onUnmounted(() => {
</li>
</ul>
<UiButton
v-if="boardModal.mode === 'edit' && currentBoard && !currentBoard.isDefault"
v-if="boardModal.mode === 'edit' && currentBoard && !currentBoard.isDefault && !currentBoard.systemKey"
variant="ghost"
size="sm"
type="button"
+99 -11
View File
@@ -17,6 +17,7 @@ import JalaliDateInput from '@/components/JalaliDateInput.vue';
import ActivityCommentSheet from '@/components/activities/ActivityCommentSheet.vue';
import ActivityPostponeSheet from '@/components/activities/ActivityPostponeSheet.vue';
import ActivityFieldsView from '@/components/activities/ActivityFieldsView.vue';
import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue';
import StagePathStrip from '@/components/StagePathStrip.vue';
import { Button as AButton, message, Modal } from 'ant-design-vue';
import type {
@@ -841,7 +842,8 @@ function moveToStage(stageId: string) {
message.info(
'سهم شما ثبت شد. فعالیت وقتی انجام‌شده می‌شود که همهٔ مسئول‌ها سهم خود را بزنند.',
);
await load();
discardDrafts();
await advanceAfterLeavingColumn(leftId);
return;
}
discardDrafts();
@@ -865,16 +867,20 @@ async function loadActivityImages(row: ActivityDto) {
clearImageUrls();
const next: NoteMedia[] = [];
for (const image of row.images ?? []) {
const mime = image.mimeType.toLowerCase();
const mime = (image.mimeType || 'application/octet-stream').toLowerCase();
const kind = mime.startsWith('audio/') ? 'audio' : mime.startsWith('image/') ? 'image' : 'file';
try {
const { data } = await api.get<Blob>(`/activities/${row.id}/images/${image.id}`, {
responseType: 'blob',
});
const blob =
data.type && data.type !== 'application/octet-stream' && !data.type.includes('json')
? data
: new Blob([data], { type: mime });
next.push({
id: image.id,
name: image.fileName,
url: URL.createObjectURL(data),
url: URL.createObjectURL(blob),
kind,
createdAt: image.createdAt,
});
@@ -885,6 +891,20 @@ async function loadActivityImages(row: ActivityDto) {
imageUrls.value = next;
}
function viewMedia(item: NoteMedia) {
window.open(item.url, '_blank', 'noopener,noreferrer');
}
function downloadMedia(item: NoteMedia) {
const link = document.createElement('a');
link.href = item.url;
link.download = item.name || 'file';
link.rel = 'noopener';
document.body.appendChild(link);
link.click();
link.remove();
}
async function loadUsers() {
try {
@@ -919,6 +939,12 @@ async function complete(kind: 'share' | 'force' | 'undo' = 'share') {
await advanceAfterLeavingColumn(leftId);
return;
}
// سهم شخصی ثبت شد ولی فعالیت هنوز باز است — از میزکار این نفر خارج شو
if (kind === 'share' && data.completionMode === 'all') {
discardDrafts();
await advanceAfterLeavingColumn(leftId);
return;
}
activity.value = data;
} catch {
error.value =
@@ -1004,8 +1030,12 @@ async function postponeTo(iso: string) {
}
}
async function submitComment(payload: { text: string; photoOnly: boolean }) {
const body = payload.text.trim() || (payload.photoOnly ? 'عکس پیوست شد.' : '');
async function submitComment(payload: {
text: string;
photoOnly: boolean;
attachmentIds?: string[];
}) {
const body = payload.text.trim() || (payload.photoOnly ? 'فایل پیوست شد.' : '');
if (!id.value || !activity.value || !body) return;
saving.value = true;
error.value = '';
@@ -1014,7 +1044,9 @@ async function submitComment(payload: { text: string; photoOnly: boolean }) {
const now = new Date();
const author = auth.user?.fullName?.trim();
const stamp = `[${formatJalaliNumeric(now)} ساعت ${formatClockFa(now)}${author ? ` — ${author}` : ''}]`;
const entry = `${stamp}\n${body}`;
const ids = [...new Set((payload.attachmentIds ?? []).filter(Boolean))];
const attachLine = ids.length ? `\n[[attachments:${ids.join(',')}]]` : '';
const entry = `${stamp}\n${body}${attachLine}`;
const next = prev ? `${prev}\n\n${entry}` : entry;
await api.patch(`/activities/${id.value}`, { description: next });
commentOpen.value = false;
@@ -1213,6 +1245,9 @@ onUnmounted(() => {
#{{ t }}
</RouterLink>
</div>
<div v-if="activity.accountBalance" class="claim-balances">
<ActivityAccountBalances :balance="activity.accountBalance" />
</div>
</div>
<span class="type-ico" :style="typeColorStyle(draftTypeView!.color)">
<UiIcon :name="draftTypeView!.icon" :size="22" />
@@ -1663,7 +1698,11 @@ onUnmounted(() => {
</div>
<ul v-if="entry.media.some((image) => image.kind === 'file')" class="note-files">
<li v-for="image in entry.media.filter((item) => item.kind === 'file')" :key="image.id">
<a :href="image.url" :download="image.name">{{ image.name }}</a>
<span class="note-file-name">{{ image.name }}</span>
<span class="note-file-actions">
<button type="button" class="note-file-btn" @click="viewMedia(image)">مشاهده</button>
<button type="button" class="note-file-btn" @click="downloadMedia(image)">دانلود</button>
</span>
</li>
</ul>
</template>
@@ -1746,7 +1785,11 @@ onUnmounted(() => {
</div>
<ul v-if="looseMedia.some((image) => image.kind === 'file')" class="note-files">
<li v-for="image in looseMedia.filter((item) => item.kind === 'file')" :key="image.id">
<a :href="image.url" :download="image.name">{{ image.name }}</a>
<span class="note-file-name">{{ image.name }}</span>
<span class="note-file-actions">
<button type="button" class="note-file-btn" @click="viewMedia(image)">مشاهده</button>
<button type="button" class="note-file-btn" @click="downloadMedia(image)">دانلود</button>
</span>
</li>
</ul>
</div>
@@ -1847,8 +1890,15 @@ onUnmounted(() => {
align-items: center;
gap: 0.45rem;
min-height: 32px;
position: relative;
z-index: 4;
/* زیر هدر دسکتاپ اپ (۱۶ + control + ۱۶) بماند تا با اسکرول در دسترس باشد */
position: sticky;
top: calc(16px + var(--control-h) + 16px);
z-index: 15;
margin-inline: -16px;
padding: 0.4rem 16px;
background: color-mix(in srgb, var(--bg, #f8fafc) 92%, transparent);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.nav h1 {
@@ -1998,6 +2048,10 @@ onUnmounted(() => {
margin-top: 0.5rem;
}
.claim-balances {
margin-top: 0.65rem;
}
.tag {
background: #f0fdfa;
color: #0f766e;
@@ -2677,8 +2731,35 @@ dd {
gap: 0.35rem;
}
.note-files a {
.note-files li {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.note-file-name {
color: #0f766e;
font-weight: 600;
word-break: break-word;
}
.note-file-actions {
display: inline-flex;
gap: 0.35rem;
}
.note-file-btn {
border: 1px solid #99f6e4;
background: #fff;
color: #0f766e;
border-radius: 0.45rem;
font: inherit;
font-size: 0.85rem;
font-weight: 700;
padding: 0.2rem 0.55rem;
cursor: pointer;
}
.dock {
@@ -2716,6 +2797,13 @@ dd {
cursor: not-allowed;
}
@media (max-width: 900px) {
.nav {
/* زیر هدر موبایل اپ (۰٫۷۵rem + control + ۰٫۷۵rem) */
top: calc(0.75rem + var(--control-h) + 0.75rem);
}
}
@media (max-width: 899px) {
.page {
padding-bottom: calc(1rem + var(--mobile-tabbar-h));
+12
View File
@@ -35,6 +35,7 @@ import ActivityFieldsEditor from '@/components/activities/ActivityFieldsEditor.v
import { useActivityPriorities } from '@/lib/activity-priorities';
import { typeColorStyle, useActivityTypes } from '@/lib/activity-types';
import type {
ActivityAccountBalanceDto,
ActivityBoardDto,
ActivityDto,
ActivityImageDto,
@@ -51,6 +52,7 @@ import type {
PipelineBoardDto,
TeamDto,
} from '@mento/shared';
import ActivityAccountBalances from '@/components/activities/ActivityAccountBalances.vue';
const props = withDefaults(
defineProps<{
@@ -101,6 +103,8 @@ const keepTypeId = ref('');
const priority = ref<ActivityPriority>('medium');
const description = ref('');
const tagsRaw = ref('');
/** فقط فعالیت‌های کاریز مطالبات از API می‌آید */
const accountBalance = ref<ActivityAccountBalanceDto | null>(null);
const PHOTO_TOO_LARGE = 'حجم عکس باید زیر 200 کیلوبایت باشد';
const PHOTO_LIMIT = 8;
type PendingPhoto = { localId: string; name: string; dataUrl: string; file: File };
@@ -438,6 +442,7 @@ function resetForm() {
priority.value = 'medium';
description.value = '';
tagsRaw.value = '';
accountBalance.value = null;
clearPhotos();
createdActivityId.value = '';
defaultDue();
@@ -515,6 +520,7 @@ async function load() {
description.value = data.description ?? '';
needsNote.value = Boolean(data.description?.trim());
tagsRaw.value = (data.tags ?? []).join('، ');
accountBalance.value = data.accountBalance ?? null;
splitDue(data.dueAt);
durationMinutes.value = data.durationMinutes ?? 30;
reminderAt.value = data.reminderAt
@@ -1641,6 +1647,12 @@ watch([id, isNew], () => void load(), { immediate: true });
<dt>مشتری مرتبط</dt>
<dd>{{ selectedPerson?.fullName || '—' }}</dd>
</div>
<div v-if="accountBalance">
<dt>مانده حساب</dt>
<dd>
<ActivityAccountBalances :balance="accountBalance" />
</dd>
</div>
<div>
<dt>وضعیت انجام</dt>
<dd>
File diff suppressed because it is too large Load Diff
+98 -7
View File
@@ -17,6 +17,7 @@ import {
Space as ASpace,
Spin as ASpin,
Tag as ATag,
Textarea as ATextarea,
Typography,
theme,
} from 'ant-design-vue';
@@ -62,6 +63,17 @@ const addLost = ref(false);
const addUnqualified = ref(false);
const deleteTarget = ref<LeadStageDto | null>(null);
const moveConfirm = ref<{ stageIds: string[]; message: string } | null>(null);
const pendingLeadMove = ref<{
leadId: string;
stageId: string;
position: number;
fromStageName: string;
toStageName: string;
prev: LeadBoardColumnDto[];
nextColumns: LeadBoardColumnDto[];
} | null>(null);
const stageMoveReason = ref('');
const stageMoveError = ref('');
const draggingId = ref<string | null>(null);
const insertAt = ref<number | null>(null);
const bodyEls = new Map<string, HTMLElement>();
@@ -201,7 +213,8 @@ async function load() {
try {
const [board, stageRows] = await Promise.all([
api.get<LeadBoardColumnDto[]>('/leads/board'),
api.get<LeadStageDto[]>('/leads/stages'),
// بدون شمارش لید روی هر مرحله — total ستون‌ها از خود board می‌آید
api.get<LeadStageDto[]>('/leads/stages', { params: { counts: '0' } }),
]);
columns.value = board.data;
stages.value = stageRows.data;
@@ -521,7 +534,7 @@ async function onDrop(stageId: string, event: DragEvent, index?: number) {
draggingId.value = null;
dropStageId.value = null;
clearDragUi();
if (!leadId || moving.value) return;
if (!leadId || moving.value || pendingLeadMove.value) return;
const fromCol = columns.value.find((c) =>
c.leads.some((l) => l.id === leadId),
@@ -547,7 +560,7 @@ async function onDrop(stageId: string, event: DragEvent, index?: number) {
leads: [...c.leads],
}));
columns.value = columns.value.map((c) => {
const nextColumns = columns.value.map((c) => {
if (same && c.stage.id === stageId) return { ...c, leads: nextLeads };
if (c.stage.id === fromCol.stage.id) {
return {
@@ -562,13 +575,66 @@ async function onDrop(stageId: string, event: DragEvent, index?: number) {
return c;
});
// جابه‌جایی داخل همان ستون: بدون دلیل
if (same) {
columns.value = nextColumns;
moving.value = true;
error.value = '';
try {
await api.patch(`/leads/${leadId}/move`, { stageId, position: insertIndex });
} catch {
columns.value = prev;
error.value = 'جابه‌جایی لید ناموفق بود.';
} finally {
moving.value = false;
}
return;
}
// تغییر ستون: اول دلیل، بعد اعمال
stageMoveReason.value = '';
stageMoveError.value = '';
pendingLeadMove.value = {
leadId,
stageId,
position: insertIndex,
fromStageName: fromCol.stage.name,
toStageName: target.stage.name,
prev,
nextColumns,
};
}
function cancelPendingLeadMove() {
pendingLeadMove.value = null;
stageMoveReason.value = '';
stageMoveError.value = '';
}
async function confirmPendingLeadMove() {
const pending = pendingLeadMove.value;
if (!pending || moving.value) return Promise.reject();
const reason = stageMoveReason.value.trim();
if (!reason) {
stageMoveError.value = 'دلیل تغییر وضعیت را بنویسید.';
return Promise.reject();
}
columns.value = pending.nextColumns;
moving.value = true;
error.value = '';
stageMoveError.value = '';
try {
await api.patch(`/leads/${leadId}/move`, { stageId, position: insertIndex });
} catch {
columns.value = prev;
error.value = 'جابه‌جایی لید ناموفق بود.';
await api.patch(`/leads/${pending.leadId}/move`, {
stageId: pending.stageId,
position: pending.position,
reason,
});
cancelPendingLeadMove();
} catch (e) {
columns.value = pending.prev;
stageMoveError.value = apiMessage(e, 'جابه‌جایی لید ناموفق بود.');
error.value = stageMoveError.value;
return Promise.reject(e);
} finally {
moving.value = false;
}
@@ -981,6 +1047,31 @@ onMounted(load);
>
<a-alert v-if="moveConfirm" type="warning" show-icon :message="moveConfirm.message" />
</a-modal>
<a-modal
:open="!!pendingLeadMove"
title="دلیل تغییر وضعیت"
ok-text="ثبت و انتقال"
cancel-text="انصراف"
:confirm-loading="moving"
:ok-button-props="{ disabled: !stageMoveReason.trim() }"
@ok="confirmPendingLeadMove"
@cancel="cancelPendingLeadMove"
>
<a-flex vertical :gap="12">
<a-typography-text v-if="pendingLeadMove" type="secondary">
انتقال از «{{ pendingLeadMove.fromStageName }}» به «{{ pendingLeadMove.toStageName }}»
</a-typography-text>
<a-textarea
v-model:value="stageMoveReason"
:rows="4"
:maxlength="1000"
show-count
placeholder="دلیل تغییر وضعیت را بنویسید…"
/>
<a-alert v-if="stageMoveError" type="error" show-icon :message="stageMoveError" />
</a-flex>
</a-modal>
</div>
</template>
+154 -30
View File
@@ -22,7 +22,7 @@ import {
List as AList,
ListItem as AListItem,
ListItemMeta as AListItemMeta,
Modal,
Modal as AModal,
Row as ARow,
Select as ASelect,
Space as ASpace,
@@ -46,7 +46,13 @@ import {
UserAddOutlined,
} from '@ant-design/icons-vue';
import { api } from '@/lib/api';
import { isBirthDateAnswer, leadNoteFileIsImage, parseLeadFormNotes } from '@/lib/lead-form-notes';
import {
isActivityExperienceAnswer,
isBirthDateAnswer,
leadNoteFileIsImage,
parseLeadFormNotes,
} from '@/lib/lead-form-notes';
import { ACTIVITY_EXPERIENCE_OPTIONS } from '@mento/shared';
import {
formatClockFa,
formatJalaliNumeric,
@@ -87,6 +93,18 @@ const canBehavior = computed(() => canUseBehavior(auth.user));
const copilotOpen = ref(false);
const id = computed(() => String(route.params.id));
/** برگشت به همان جایی که از آن آمده‌ایم (فهرست یا مسیر/بورد لیدها). */
function goBack() {
const back = String((window.history.state as { back?: string | null } | null)?.back ?? '');
const path = back.split('?')[0];
if (path === '/leads' || path === '/leads/board') {
router.back();
return;
}
void router.push({ name: 'leads' });
}
const loading = ref(false);
const busy = ref(false);
const error = ref('');
@@ -97,6 +115,9 @@ const users = ref<OrgUserDto[]>([]);
const activities = ref<ActivityDto[]>([]);
const stageId = ref('');
const stageMoveOpen = ref(false);
const stageMoveReason = ref('');
const stageMoveError = ref('');
const assigneeId = ref('');
const callOutcome = ref('');
const callBody = ref('');
@@ -125,9 +146,15 @@ const editForm = ref({
instagram: '',
birthDate: '',
trade: '',
activityExperience: '' as string,
notes: '',
});
const activityExperienceOptions = [
{ value: '', label: '—' },
...ACTIVITY_EXPERIENCE_OPTIONS.map((value) => ({ value, label: value })),
];
function formatDate(value: string | null | undefined) {
if (!value) return '—';
try {
@@ -145,8 +172,18 @@ const shownBirthDate = computed(() => {
if (lead.value?.birthDate) return formatDate(lead.value.birthDate);
return formBirthDate.value || '—';
});
const formActivityExperience = computed(
() =>
noteView.value.rows.find((row) => isActivityExperienceAnswer(row.label) && !row.file)?.text ??
'',
);
const shownActivityExperience = computed(
() => lead.value?.activityExperience || formActivityExperience.value || '—',
);
const answerRows = computed(() =>
noteView.value.rows.filter((row) => !isBirthDateAnswer(row.label)),
noteView.value.rows.filter(
(row) => !isBirthDateAnswer(row.label) && !isActivityExperienceAnswer(row.label),
),
);
const genderOptions = PERSON_GENDERS.map((key) => ({
@@ -231,6 +268,7 @@ function startEdit() {
? formatLocalDateInput(new Date(lead.value.birthDate))
: '',
trade: lead.value.trade ?? '',
activityExperience: lead.value.activityExperience ?? '',
notes: lead.value.notes ?? '',
};
}
@@ -257,6 +295,7 @@ async function saveEdit() {
instagram: editForm.value.instagram.trim() || null,
birthDate: editForm.value.birthDate || null,
trade: editForm.value.trade.trim() || null,
activityExperience: editForm.value.activityExperience.trim() || null,
notes: editForm.value.notes.trim() || null,
});
okMsg.value = 'لید ویرایش شد.';
@@ -270,18 +309,48 @@ async function saveEdit() {
}
}
async function changeStage() {
function openStageMove() {
if (!stageId.value || stageId.value === lead.value?.stageId) return;
stageMoveReason.value = '';
stageMoveError.value = '';
stageMoveOpen.value = true;
}
function cancelStageMove() {
stageMoveOpen.value = false;
stageMoveReason.value = '';
stageMoveError.value = '';
if (lead.value) stageId.value = lead.value.stageId;
}
async function changeStage() {
if (!stageId.value || stageId.value === lead.value?.stageId) {
return Promise.reject();
}
const reason = stageMoveReason.value.trim();
if (!reason) {
stageMoveError.value = 'دلیل تغییر وضعیت را بنویسید.';
return Promise.reject();
}
busy.value = true;
error.value = '';
stageMoveError.value = '';
try {
await api.patch(`/leads/${id.value}/move`, { stageId: stageId.value });
await api.patch(`/leads/${id.value}/move`, {
stageId: stageId.value,
reason,
});
okMsg.value = 'وضعیت به‌روز شد.';
message.success(okMsg.value);
moreOpen.value = false;
stageMoveOpen.value = false;
stageMoveReason.value = '';
await load();
} catch (e) {
error.value = apiError(e, 'تغییر وضعیت ناموفق بود.');
const msg = apiError(e, 'تغییر وضعیت ناموفق بود.');
stageMoveError.value = msg;
error.value = msg;
return Promise.reject(e);
} finally {
busy.value = false;
}
@@ -378,7 +447,7 @@ async function setFollowUp() {
}
function convertLead() {
Modal.confirm({
AModal.confirm({
title: 'این لید به مشتری تبدیل شود؟',
okText: 'تبدیل',
cancelText: 'انصراف',
@@ -407,7 +476,7 @@ function convertLead() {
}
function archiveLead() {
Modal.confirm({
AModal.confirm({
title: 'این لید بایگانی شود؟',
okText: 'بایگانی',
cancelText: 'انصراف',
@@ -438,10 +507,15 @@ function openTel() {
const feed = computed(() => {
const rows: Array<{ key: string; title: string; by: string; at: string }> = [];
for (const ev of lead.value?.events ?? []) {
const body = ev.body?.trim();
rows.push({
key: `ev-${ev.id}`,
title: ev.title,
by: ev.body?.trim() || 'توسط سیستم',
by: body
? ev.type === 'stage_changed'
? `دلیل: ${body}`
: body
: 'توسط سیستم',
at: ev.createdAt,
});
}
@@ -496,11 +570,9 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
<a-col :span="24">
<a-flex justify="space-between" align="center" wrap="wrap" :gap="token.marginSM">
<a-space :size="12" align="start">
<RouterLink :to="{ name: 'leads-board' }" custom v-slot="{ navigate }">
<a-button @click="navigate">
<template #icon><ArrowLeftOutlined /></template>
</a-button>
</RouterLink>
<a-button aria-label="بازگشت" @click="goBack">
<template #icon><ArrowLeftOutlined /></template>
</a-button>
<div>
<a-typography-title :level="3" :style="{ margin: 0 }">
{{ lead?.title || 'جزئیات لید' }}
@@ -662,6 +734,17 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
<a-input v-model:value="editForm.trade" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="سابقه فعالیت">
<a-select
v-model:value="editForm.activityExperience"
allow-clear
placeholder="اختیاری"
style="width: 100%"
:options="activityExperienceOptions"
/>
</a-form-item>
</a-col>
<a-col :span="24">
<a-form-item label="یادداشت">
<a-textarea
@@ -734,6 +817,9 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
<span dir="ltr">{{ lead.instagram || '—' }}</span>
</a-descriptions-item>
<a-descriptions-item label="صنف">{{ lead.trade || '—' }}</a-descriptions-item>
<a-descriptions-item label="سابقه فعالیت">
{{ shownActivityExperience }}
</a-descriptions-item>
<a-descriptions-item label="منبع">
{{ lead.source || '—' }}
</a-descriptions-item>
@@ -866,7 +952,7 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
</a-typography-text>
</div>
<a-typography-paragraph v-if="ev.body" type="secondary">
{{ ev.body }}
<template v-if="ev.type === 'stage_changed'">دلیل: </template>{{ ev.body }}
</a-typography-paragraph>
</a-timeline-item>
</a-timeline>
@@ -936,7 +1022,12 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
:options="stages.map((s) => ({ value: s.id, label: s.name }))"
/>
</a-form-item>
<a-button block :disabled="busy" :loading="busy" @click="changeStage">
<a-button
block
:disabled="busy || stageId === lead.stageId"
:loading="busy"
@click="openStageMove"
>
اعمال وضعیت
</a-button>
@@ -1082,7 +1173,13 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
:options="stages.map((s) => ({ value: s.id, label: s.name }))"
/>
</a-form-item>
<a-button block :disabled="busy" @click="changeStage">اعمال وضعیت</a-button>
<a-button
block
:disabled="busy || stageId === lead.stageId"
@click="openStageMove"
>
اعمال وضعیت
</a-button>
<template v-if="canAssignOthers">
<a-divider orientation="right">تخصیص کارشناس</a-divider>
@@ -1170,20 +1267,47 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
</a-button>
</a-form>
</a-drawer>
<SmsComposeModal
:open="smsOpen"
title="ارسال پیامک"
:endpoint="`/leads/${lead.id}/sms`"
:history-endpoint="`/leads/${lead.id}/sms-history`"
:name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''"
:record-title="lead.title"
:company="lead.trade ?? ''"
@close="smsOpen = false"
/>
</template>
</template>
</a-spin>
</a-col>
</a-row>
<a-modal
v-model:open="stageMoveOpen"
title="دلیل تغییر وضعیت"
ok-text="ثبت و انتقال"
cancel-text="انصراف"
destroy-on-close
:confirm-loading="busy"
:ok-button-props="{ disabled: !stageMoveReason.trim() }"
@ok="changeStage"
@cancel="cancelStageMove"
>
<a-flex vertical :gap="12">
<a-typography-text type="secondary">
انتقال از «{{ lead?.stageName || '—' }}» به «{{ stages.find((s) => s.id === stageId)?.name || '—' }}»
</a-typography-text>
<a-textarea
v-model:value="stageMoveReason"
:rows="4"
:maxlength="1000"
show-count
placeholder="دلیل تغییر وضعیت را بنویسید…"
/>
<a-alert v-if="stageMoveError" type="error" show-icon :message="stageMoveError" />
</a-flex>
</a-modal>
<SmsComposeModal
v-if="lead"
:open="smsOpen"
title="ارسال پیامک"
:endpoint="`/leads/${lead.id}/sms`"
:history-endpoint="`/leads/${lead.id}/sms-history`"
:name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''"
:record-title="lead.title"
:company="lead.trade ?? ''"
@close="smsOpen = false"
/>
</template>
+370 -134
View File
@@ -1,8 +1,10 @@
<script setup lang="ts">
import { computed, nextTick, onMounted, ref, watch, type Component } from 'vue';
import { RouterLink, useRoute, useRouter } from 'vue-router';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { api } from '@/lib/api';
import UiIcon from '@/components/UiIcon.vue';
import { UiButton, UiPageHeader } from '@/components/ui';
import type {
LeadFormDto,
LeadFormDuplicateMode,
@@ -16,99 +18,16 @@ import type {
OrgUserDto,
PipelineDto,
} from '@mento/shared';
import { ACTIVITY_EXPERIENCE_OPTIONS } from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
import { prepareFormCover } from '@/lib/form-cover';
import { useEscClose } from '@/lib/modal-stack';
import {
Affix as AAffix,
Alert as AAlert,
Button as AButton,
Card as ACard,
Checkbox as ACheckbox,
CheckboxGroup as ACheckboxGroup,
Col as ACol,
Collapse as ACollapse,
CollapsePanel as ACollapsePanel,
Descriptions as ADescriptions,
DescriptionsItem as ADescriptionsItem,
Divider as ADivider,
Drawer as ADrawer,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Input as AInput,
Modal as AModal,
Popover as APopover,
RadioGroup as ARadioGroup,
Rate as ARate,
Row as ARow,
Select as ASelect,
SelectOption as ASelectOption,
SelectOptGroup as ASelectOptGroup,
Space as ASpace,
Statistic as AStatistic,
Switch as ASwitch,
Tabs as ATabs,
TabPane as ATabPane,
Tag as ATag,
Textarea as ATextarea,
Typography,
Upload as AUpload,
theme,
} from 'ant-design-vue';
import { CrmSkeleton, CrmSkeletonCard } from '@/components/skeleton';
import type { UploadProps } from 'ant-design-vue';
import {
AppstoreOutlined,
BarChartOutlined,
CalendarOutlined,
CheckOutlined,
CommentOutlined,
CopyOutlined,
DeleteOutlined,
EditOutlined,
EyeOutlined,
FileOutlined,
HolderOutlined,
MailOutlined,
NotificationOutlined,
PhoneOutlined,
PlusOutlined,
SaveOutlined,
SendOutlined,
StarOutlined,
UnorderedListOutlined,
UserOutlined,
} from '@/icons/ant-bridge';
const { Title: ATypographyTitle, Text: ATypographyText, Link: ATypographyLink, Paragraph: ATypographyParagraph } =
Typography;
const ASpaceCompact = ASpace.Compact;
const ACheckableTag = ATag.CheckableTag;
const { token } = theme.useToken();
type Tab = 'edit' | 'settings' | 'share' | 'responses';
type IconName =
| 'user' | 'chat' | 'mail' | 'phone' | 'list' | 'layers' | 'calendar'
| 'check' | 'chart' | 'document' | 'star' | 'megaphone' | 'building';
const ICON_MAP: Record<IconName, Component> = {
user: UserOutlined,
chat: CommentOutlined,
mail: MailOutlined,
phone: PhoneOutlined,
list: UnorderedListOutlined,
layers: AppstoreOutlined,
calendar: CalendarOutlined,
check: CheckOutlined,
chart: BarChartOutlined,
document: FileOutlined,
star: StarOutlined,
megaphone: NotificationOutlined,
building: AppstoreOutlined,
};
const route = useRoute();
const router = useRouter();
const id = computed(() => String(route.params.id || ''));
@@ -121,7 +40,7 @@ const tab = ref<Tab>('edit');
const desktopPreviewOpen = ref(false);
const publishOpen = ref(false);
const advancedOpen = ref(false);
const readyOpen = ref<string[]>(['lead']);
const readyOpen = ref<string | null>('lead');
const editFieldKey = ref<string | null>(null);
const dragKey = ref<string | null>(null);
@@ -146,6 +65,7 @@ const users = ref<OrgUserDto[]>([]);
const pipelines = ref<PipelineDto[]>([]);
const leadStages = ref<LeadStageDto[]>([]);
const submissions = ref<LeadFormSubmissionDto[]>([]);
const coverInput = ref<HTMLInputElement | null>(null);
const toolbox: Array<{ type: LeadFormFieldType; label: string; icon: IconName }> = [
{ type: 'text', label: 'متن کوتاه', icon: 'user' },
@@ -177,6 +97,12 @@ const readyGroups = [
{ label: 'شهر', fieldType: 'text' as const, mapTo: 'lead.city' as const },
{ label: 'منطقه', fieldType: 'text' as const, mapTo: 'lead.region' as const },
{ label: 'صنف', fieldType: 'text' as const, mapTo: 'lead.trade' as const },
{
label: 'سابقه فعالیت',
fieldType: 'select' as const,
mapTo: 'lead.activityExperience' as const,
options: [...ACTIVITY_EXPERIENCE_OPTIONS],
},
{ label: 'توضیحات', fieldType: 'textarea' as const, mapTo: 'lead.notes' as const },
],
},
@@ -186,6 +112,12 @@ const readyGroups = [
{ label: 'نام و نام خانوادگی', fieldType: 'text' as const, mapTo: 'person.fullName' as const },
{ label: 'ایمیل', fieldType: 'email' as const, mapTo: 'person.email' as const },
{ label: 'موبایل', fieldType: 'phone' as const, mapTo: 'person.mobile' as const },
{
label: 'سابقه فعالیت',
fieldType: 'select' as const,
mapTo: 'person.activityExperience' as const,
options: [...ACTIVITY_EXPERIENCE_OPTIONS],
},
],
},
{
@@ -312,14 +244,7 @@ function applyHex() {
else hexDraft.value = submitColor.value;
}
const titleInput = ref<{ focus: () => void; $el?: HTMLElement } | null>(null);
function focusTitle() {
titleInput.value?.focus();
const el = titleInput.value?.$el?.querySelector?.('input') as HTMLInputElement | null | undefined;
el?.select?.();
}
const titleInput = ref<HTMLInputElement | null>(null);
const conversionRate = computed(() => {
const submits = form.value?.submitCount ?? 0;
const leads = form.value?.leadCreateCount ?? 0;
@@ -337,28 +262,6 @@ const crmSummary = computed(() => {
return parts.join(' · ') || 'اتصال CRM تنظیم نشده';
});
const leadStageOptions = computed(() => [
{ value: '', label: 'اولین مرحله فعال' },
...leadStages.value.map((s) => ({ value: s.id, label: s.name })),
]);
const pipelineOptions = computed(() => [
{ value: '', label: 'پیش‌فرض سازمان' },
...pipelines.value.map((p) => ({ value: p.id, label: p.name })),
]);
const duplicateOptions = [
{ value: 'update', label: 'به‌روزرسانی لید موجود' },
{ value: 'skip', label: 'رد کردن (ثبت نشود)' },
{ value: 'activity', label: 'فقط ثبت رویداد روی لید موجود' },
];
const settingsSummaryItems = computed(() => [
{ label: 'وضعیت', value: isActive.value ? 'فعال' : 'غیرفعال' },
{ label: 'ثبت لید', value: createLead.value ? 'بله' : 'خیر' },
{ label: 'ساخت شخص', value: createPerson.value ? 'بله' : 'خیر' },
{ label: 'ساخت معامله', value: createDeal.value ? 'بله' : 'خیر' },
{ label: 'منبع', value: source.value || '—' },
{ label: 'مسئولان', value: toFaDigits(assigneeIds.value.length) },
]);
function newKey(label: string) {
const base = label.replace(/\s+/g, '_').slice(0, 24) || 'field';
let key = `${base}_${Math.random().toString(36).slice(2, 6)}`;
@@ -496,7 +399,8 @@ async function load() {
if (route.query.new && !error.value) {
tab.value = 'edit';
await nextTick();
focusTitle();
titleInput.value?.focus();
titleInput.value?.select();
void router.replace({ query: {} });
}
}
@@ -518,7 +422,7 @@ async function save() {
if (!name.value.trim()) {
tab.value = 'edit';
await nextTick();
focusTitle();
titleInput.value?.focus();
}
return;
}
@@ -559,7 +463,11 @@ async function save() {
}
}
async function handleCoverFile(file: File) {
async function uploadCover(ev: Event) {
const input = ev.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
error.value = '';
coverUploading.value = true;
try {
@@ -576,11 +484,6 @@ async function handleCoverFile(file: File) {
}
}
const beforeCoverUpload: UploadProps['beforeUpload'] = (file) => {
void handleCoverFile(file as File);
return false;
};
async function clearCover() {
try {
const { data } = await api.delete<LeadFormDto>(`/lead-forms/${id.value}/cover`);
@@ -650,15 +553,6 @@ function toggleAssignee(uid: string) {
: [...assigneeIds.value, uid];
}
function onTabChange(key: string | number) {
const next = String(key) as Tab;
if (next === 'responses') {
void loadResponses();
return;
}
tab.value = next;
}
onMounted(load);
</script>
@@ -1428,3 +1322,345 @@ onMounted(load);
</a-modal>
</a-flex>
</template>
<style scoped>
.page { --teal: #14b8a6; display: grid; gap: 0.85rem; }
.top-ghosts { display: flex; gap: 0.45rem; flex-wrap: nowrap; }
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 0.3rem; min-height: var(--control-h); height: var(--control-h); padding: 0 0.9rem; border-radius: var(--radius); font: inherit; font-weight: 700; border: 1px solid transparent; cursor: pointer; text-decoration: none; box-sizing: border-box; white-space: nowrap; }
.btn.primary { background: var(--teal); color: #fff; }
.btn.ghost { background: #fff; color: #0f766e; border-color: #99f6e4; }
.banner { margin: 0; padding: 0.6rem 0.8rem; border-radius: var(--radius); }
.banner.err { background: #fef2f2; color: #b91c1c; }
.banner.ok { background: #ecfdf5; color: #047857; }
.tabs { display: flex; gap: 0.35rem; flex-wrap: wrap; background: #fff; padding: 0.35rem; border-radius: var(--radius); }
.tabs button { border: 0; background: transparent; min-height: 38px; padding: 0 0.85rem; border-radius: var(--radius); font: inherit; font-weight: 700; color: #0f766e; cursor: pointer; display: inline-flex; align-items: center; gap: 0.3rem; }
.tabs button.on { background: var(--teal); color: #fff; }
.workspace { display: grid; grid-template-columns: 280px minmax(0,1fr) 240px; gap: 0.85rem; align-items: start; }
.preview-col, .canvas, .toolbox, .panel { background: #fff; border-radius: var(--radius); padding: 0.9rem; box-shadow: 0 8px 22px rgba(15,23,42,.04); }
.device-toggle { display: flex; gap: 0.3rem; margin-bottom: 0.7rem; }
.device-toggle button { flex: 1; border: 0; min-height: 34px; border-radius: var(--radius); font: inherit; font-weight: 700; background: #f1f5f9; cursor: pointer; }
.device-toggle button.on { background: var(--teal); color: #fff; }
.phone { border: 8px solid #0f172a; border-radius: var(--radius); overflow: hidden; background: #fff; max-width: 260px; margin: 0 auto; }
.desk-overlay { padding: 1.2rem; }
.desk-sheet {
width: min(920px, 100%);
max-height: calc(100vh - 2.4rem);
overflow: auto;
background: #eef2f6;
border-radius: var(--radius);
padding: 1rem 1.1rem 1.2rem;
display: grid;
gap: 0.75rem;
}
.desk-sheet header { display: flex; justify-content: space-between; align-items: center; }
.desk-form { background: #fff; border-radius: var(--radius); overflow: hidden; box-shadow: 0 16px 40px rgba(15,23,42,.08); }
.desk-form .cover { height: auto; aspect-ratio: 3 / 1; max-height: 260px; }
.desk-body { padding: 1.2rem 1.4rem 1.4rem; }
.desk-body h3 { font-size: 1.35rem; }
.desk-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem 1rem; }
.desk-fields .wide { grid-column: 1 / -1; }
.desk-form .send { justify-self: start; min-width: 200px; }
.cover { aspect-ratio: 3 / 1; display: grid; place-items: center; color: #fff; overflow: hidden; }
.cover img { width: 100%; height: 100%; object-fit: cover; }
.preview-body { padding: 0.8rem; display: grid; gap: 0.5rem; }
.preview-body h3 { margin: 0; font-size: 1rem; }
.preview-body p, .preview-body small { margin: 0; color: #64748b; font-size: 0.78rem; }
.preview-body label { display: grid; gap: 0.25rem; font-size: 0.78rem; color: #475569; }
.preview-body input, .preview-body textarea, .preview-body select { border: 1px solid #e2e8f0; border-radius: var(--radius); padding: 0.45rem 0.6rem; font: inherit; background: #f8fafc; }
.send { border: 0; color: #fff; border-radius: var(--radius); min-height: var(--control-h); height: var(--control-h); font: inherit; font-weight: 700; display: inline-flex; align-items: center; justify-content: center; gap: 0.3rem; box-sizing: border-box; }
.opts, .stars { color: #64748b; font-size: 0.75rem; display: grid; gap: 0.2rem; }
.cover-box { position: relative; width: 100%; aspect-ratio: 3 / 1; max-height: 200px; border: 1.5px dashed #99f6e4; border-radius: var(--radius); background: #f0fdfa; color: #0f766e; font: inherit; font-weight: 700; cursor: pointer; overflow: hidden; display: grid; place-items: center; padding: 0; }
.cover-box.has { border-style: solid; border-color: transparent; }
.cover-box:disabled { cursor: progress; opacity: 0.75; }
.cover-box img { width: 100%; height: 100%; object-fit: cover; display: block; }
.cover-empty { display: grid; gap: 0.25rem; justify-items: center; padding: 0.5rem; }
.cover-empty small { font-weight: 500; font-size: 0.74rem; color: #64748b; }
.cover-change { position: absolute; inset-inline-start: 0.5rem; bottom: 0.5rem; background: rgba(15,23,42,.65); color: #fff; font-size: 0.74rem; padding: 0.2rem 0.55rem; border-radius: 999px; opacity: 0; transition: opacity .15s; }
.cover-box:hover .cover-change, .cover-box:disabled .cover-change { opacity: 1; }
.title-card, .field-card, .submit-card, .adv-box { border: 1px solid #eef2f7; border-radius: var(--radius); padding: 0.8rem; display: grid; gap: 0.45rem; }
.title { font: inherit; font-size: 1.1rem; font-weight: 700; color: #0f172a; border: 1px solid #e2e8f0; border-radius: var(--radius); padding: 0.55rem 0.7rem; background: #fff; width: 100%; box-sizing: border-box; }
.title:hover { border-color: #99f6e4; }
.title:focus { outline: none; border-color: var(--teal); box-shadow: 0 0 0 3px rgba(20,184,166,.15); }
.title-label { display: inline-flex; align-items: center; gap: 0.3rem; font-size: 0.78rem; font-weight: 700; color: #64748b; }
.color-row { display: flex; align-items: center; justify-content: space-between; gap: 0.6rem; font-size: 0.88rem; font-weight: 700; color: #334155; }
.color-pick { position: relative; }
.swatch-btn { display: inline-flex; align-items: center; gap: 0.45rem; border: 1px solid #e2e8f0; background: #fff; border-radius: var(--radius); padding: 0.3rem 0.5rem; font: inherit; cursor: pointer; }
.swatch-btn:hover { border-color: #99f6e4; }
.swatch { width: 26px; height: 26px; border-radius: 8px; box-shadow: inset 0 0 0 1px rgba(15,23,42,.12); }
.hex { font-size: 0.8rem; color: #475569; font-family: ui-monospace, monospace; }
.palette { position: absolute; inset-inline-end: 0; top: calc(100% + 6px); z-index: 30; width: 236px; background: #fff; border: 1px solid #e2e8f0; border-radius: var(--radius); box-shadow: 0 16px 40px rgba(15,23,42,.16); padding: 0.65rem; display: grid; gap: 0.6rem; }
.presets { display: grid; grid-template-columns: repeat(6, 1fr); gap: 0.35rem; }
.preset { width: 100%; aspect-ratio: 1; border: 0; border-radius: 8px; cursor: pointer; display: grid; place-items: center; color: #fff; box-shadow: inset 0 0 0 1px rgba(15,23,42,.1); }
.preset.on { outline: 2px solid #0f172a; outline-offset: 2px; }
.custom { display: flex; align-items: center; gap: 0.4rem; }
.native { display: inline-flex; align-items: center; gap: 0.3rem; font-size: 0.78rem; font-weight: 600; color: #475569; cursor: pointer; white-space: nowrap; }
.palette-backdrop { position: fixed; inset: 0; z-index: 29; }
.sheet-warn { font-size: 0.76rem; font-weight: 600; color: #b45309; }
.fbody { cursor: pointer; min-width: 0; }
.req { color: #ef4444; margin-inline-start: 0.15rem; }
.submit-card .native input { width: 28px; height: 28px; padding: 0; border: 0; background: none; cursor: pointer; }
.submit-card .hex-input { flex: 1; min-width: 0; padding: 0.35rem 0.5rem; font-family: ui-monospace, monospace; font-size: 0.82rem; }
.palette-done { border: 0; background: var(--teal); color: #fff; border-radius: var(--radius); min-height: 32px; font: inherit; font-weight: 700; cursor: pointer; }
.sheet-hint { font-size: 0.74rem; font-weight: 500; color: #94a3b8; }
.sheet-error { margin: 0; color: #b91c1c; font-size: 0.84rem; }
.title-card textarea, .submit-card input, .panel input, .panel select, .sheet input, .sheet select, .sheet textarea {
border: 1px solid #e2e8f0; border-radius: var(--radius); padding: 0.55rem 0.7rem; font: inherit; width: 100%;
}
.field-card { grid-template-columns: auto 1fr auto; align-items: center; cursor: grab; }
.field-card small { color: #94a3b8; display: block; }
.fops { display: flex; gap: 0.2rem; }
.fops button { width: 30px; height: 30px; border: 0; border-radius: var(--radius); background: #f8fafc; cursor: pointer; color: #64748b; }
.fops .danger { color: #dc2626; }
.add-field { width: 100%; min-height: var(--control-h); height: var(--control-h); border: 1.5px dashed #14b8a6; background: #f0fdfa; color: #0f766e; border-radius: var(--radius); font: inherit; font-weight: 700; cursor: pointer; box-sizing: border-box; }
.adv { background: none; border: 0; font: inherit; font-weight: 700; color: #0f766e; cursor: pointer; text-align: right; }
.toolbox h3 { margin: 0 0 0.5rem; font-size: 0.95rem; }
.tools { display: grid; grid-template-columns: 1fr 1fr; gap: 0.4rem; margin-bottom: 1rem; }
.tools button {
border: 1px solid #eef2f7;
background: #f8fafc;
border-radius: var(--radius);
min-height: 52px;
padding: 0.35rem 0.4rem;
font: inherit;
font-size: 0.75rem;
cursor: pointer;
display: grid;
place-items: center;
gap: 0.15rem;
color: #334155;
text-align: center;
}
.ready { margin-bottom: 0.35rem; }
.ready-toggle {
width: 100%;
background: none;
border: 0;
text-align: right;
font: inherit;
font-weight: 700;
padding: 0.45rem 0;
cursor: pointer;
color: #0f172a;
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.5rem;
}
.ready-caret { color: #94a3b8; font-size: 0.85rem; }
.ready-tools { margin: 0 0 0.65rem; }
.panel { display: grid; gap: 0.7rem; }
.panel label, .sheet label { display: grid; gap: 0.3rem; font-size: 0.88rem; font-weight: 700; color: #334155; }
.chk { display: flex !important; align-items: center; gap: 0.4rem; font-weight: 600 !important; }
.chips { display: flex; flex-wrap: wrap; gap: 0.35rem; }
.chip { border: 1px solid #e2e8f0; background: #fff; border-radius: 999px; padding: 0.3rem 0.7rem; font: inherit; cursor: pointer; }
.chip.on { background: #ccfbf1; border-color: #99f6e4; color: #0f766e; font-weight: 700; }
.row { display: flex; gap: 0.4rem; align-items: stretch; }
.row input { flex: 1; min-width: 0; }
.sub { border-bottom: 1px solid #f1f5f9; padding: 0.5rem 0; }
.overlay { position: fixed; inset: 0; background: rgba(15,23,42,.35); display: grid; place-items: center; z-index: 40; padding: 1rem; }
.sheet { width: min(420px,100%); max-height: calc(100dvh - 2rem); overflow-y: auto; background: #fff; border-radius: var(--radius); padding: 1rem; display: grid; gap: 0.65rem; box-sizing: border-box; }
.sheet-head { display: flex; align-items: center; justify-content: space-between; gap: 0.5rem; }
.sheet-head h3 { margin: 0; }
.sheet-actions { display: flex; gap: 0.5rem; }
.sheet-actions .btn { flex: 1; }
.x-btn { width: 36px; height: 36px; flex-shrink: 0; border: 1px solid #e2e8f0; border-radius: var(--radius); background: #fff; color: #64748b; display: grid; place-items: center; cursor: pointer; }
.x-btn:hover { background: #f8fafc; color: #0f172a; border-color: #cbd5e1; }
.link { background: none; border: 0; color: #0f766e; font: inherit; font-weight: 700; cursor: pointer; text-align: right; padding: 0; }
.panel-title {
margin: 0.2rem 0 0;
padding-top: 0.55rem;
border-top: 1px solid #f1f5f9;
font-size: 0.95rem;
color: #0f766e;
}
.panel > .panel-title:first-child {
border-top: 0;
padding-top: 0;
}
.settings-panel {
gap: 0.85rem;
background: transparent;
box-shadow: none;
padding: 0;
}
.settings-card {
background: #fff;
border: 1px solid #eef2f7;
border-radius: var(--radius);
padding: 1rem 1.05rem;
display: grid;
gap: 0.85rem;
box-shadow: 0 8px 22px rgba(15,23,42,.04);
}
.settings-card.optional {
background: #f8fafc;
border-style: dashed;
}
.settings-card-head h3 {
margin: 0;
font-size: 0.98rem;
font-weight: 700;
color: #0f172a;
}
.settings-card-head p {
margin: 0.2rem 0 0;
font-size: 0.8rem;
color: #64748b;
font-weight: 500;
}
.toggle-list { display: grid; gap: 0.45rem; }
.toggle-row {
display: flex !important;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.7rem 0.8rem;
border: 1px solid #eef2f7;
border-radius: var(--radius);
background: #fff;
font-weight: 600 !important;
}
.toggle-list.compact .toggle-row { padding: 0.55rem 0.7rem; }
.toggle-row span {
display: grid;
gap: 0.15rem;
min-width: 0;
}
.toggle-row strong {
font-size: 0.9rem;
color: #0f172a;
font-weight: 700;
}
.toggle-row small {
font-size: 0.75rem;
color: #64748b;
font-weight: 500;
line-height: 1.35;
}
.toggle-row input[type='checkbox'] {
width: 1.15rem;
height: 1.15rem;
flex: 0 0 auto;
accent-color: #14b8a6;
cursor: pointer;
}
.settings-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.75rem 0.85rem;
}
.settings-grid .field,
.settings-card .field {
display: grid;
gap: 0.3rem;
font-size: 0.84rem;
font-weight: 700;
color: #334155;
}
.settings-grid .span-2 { grid-column: 1 / -1; }
.settings-card .field input,
.settings-card .field select,
.settings-grid .field input,
.settings-grid .field select {
border: 1px solid #e2e8f0;
border-radius: var(--radius);
padding: 0.55rem 0.7rem;
font: inherit;
width: 100%;
background: #fff;
font-weight: 500;
color: #0f172a;
}
.settings-empty {
margin: 0;
font-size: 0.8rem;
color: #94a3b8;
}
.pipeline-field { margin-top: 0.15rem; }
.settings-actions {
display: flex;
justify-content: flex-end;
position: sticky;
bottom: 0.5rem;
padding-top: 0.25rem;
}
.settings-actions .btn { min-width: 160px; }
.share-actions { display: flex; gap: 0.4rem; }
.iframe-code { flex: 1; border: 1px solid #e2e8f0; border-radius: var(--radius); padding: 0.55rem 0.7rem; font: inherit; width: 100%; resize: vertical; min-width: 0; }
.row.col { flex-direction: column; align-items: stretch; }
.crm-hint {
margin: 0;
color: #64748b;
font-size: 0.85rem;
background: #f8fafc;
border: 1px solid #eef2f7;
border-radius: var(--radius);
padding: 0.65rem 0.75rem;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.5rem;
margin-bottom: 0.85rem;
}
.stat {
background: #f0fdfa;
border: 1px solid #ccfbf1;
border-radius: var(--radius);
padding: 0.6rem 0.55rem;
display: grid;
gap: 0.15rem;
text-align: center;
}
.stat b { font-size: 1.05rem; color: #0f766e; }
.stat span { font-size: 0.72rem; color: #64748b; line-height: 1.3; }
.publish-sheet { width: min(520px, 100%); gap: 0.75rem; max-height: calc(100vh - 2rem); overflow: auto; }
.publish-head { display: flex; justify-content: space-between; align-items: center; }
.publish-preview {
display: grid;
grid-template-columns: 72px 1fr;
gap: 0.75rem;
align-items: center;
padding: 0.65rem;
background: #f8fafc;
border: 1px solid #eef2f7;
border-radius: var(--radius);
}
.publish-preview h4 { margin: 0 0 0.25rem; }
.publish-preview p { margin: 0 0 0.35rem; color: #64748b; font-size: 0.82rem; }
.publish-preview a { color: #0f766e; font-weight: 700; font-size: 0.85rem; }
.mini-cover {
width: 108px;
aspect-ratio: 3 / 1;
border-radius: var(--radius);
overflow: hidden;
}
.mini-cover img { width: 100%; height: 100%; object-fit: cover; }
.publish-qr { justify-self: start; border-radius: 8px; border: 1px solid #eef2f7; }
@media (max-width: 1100px) {
.workspace { grid-template-columns: 1fr; }
.preview-col { order: 3; }
.toolbox { order: 1; }
.canvas { order: 2; }
.tools { grid-template-columns: repeat(3, 1fr); }
}
@media (max-width: 700px) {
.top-ghosts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.45rem;
width: 100%;
}
.top-ghosts :deep(.ui-btn) { width: 100%; }
.tabs { display: grid; grid-template-columns: 1fr 1fr; }
.stats-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.publish-preview { grid-template-columns: 56px 1fr; }
.mini-cover { width: 84px; }
.settings-grid { grid-template-columns: 1fr; }
.settings-grid .span-2 { grid-column: auto; }
.settings-card { padding: 0.85rem; }
.toggle-row { align-items: flex-start; }
.settings-actions { justify-content: stretch; }
.settings-actions .btn { width: 100%; min-width: 0; }
}
</style>
File diff suppressed because it is too large Load Diff
+23 -1
View File
@@ -36,7 +36,12 @@ import {
} from '@ant-design/icons-vue';
import { api } from '@/lib/api';
import type { CompanyDto, CreatePersonRequest, PersonDto, PersonGender, PersonMood } from '@mento/shared';
import { PERSON_GENDER_LABELS, PERSON_GENDERS, splitPersonHonorific } from '@mento/shared';
import {
ACTIVITY_EXPERIENCE_OPTIONS,
PERSON_GENDER_LABELS,
PERSON_GENDERS,
splitPersonHonorific,
} from '@mento/shared';
import { PERSON_MOOD_LABELS, PERSON_MOODS } from '@/lib/person-mood';
import { formatLocalDateInput, toFaDigits } from '@/lib/jalali';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
@@ -97,6 +102,7 @@ const website = ref('');
const instagram = ref('');
const birthDate = ref('');
const referrer = ref('');
const activityExperience = ref('');
const nationalId = ref('');
const city = ref('');
const rasteh = ref('');
@@ -279,6 +285,7 @@ function fill(p: PersonDto) {
instagram.value = p.instagram ?? '';
birthDate.value = p.birthDate ? formatLocalDateInput(new Date(p.birthDate)) : '';
referrer.value = p.referrer ?? '';
activityExperience.value = p.activityExperience ?? '';
addresses.value = p.addresses?.length ? [...p.addresses] : [''];
notes.value = p.notes ?? '';
tagsRaw.value = (p.tags ?? []).join('، ');
@@ -382,6 +389,7 @@ function payload(): CreatePersonRequest {
instagram: instagram.value || undefined,
birthDate: birthDate.value || null,
referrer: referrer.value || undefined,
activityExperience: activityExperience.value || null,
addresses: addresses.value.map((a) => a.trim()).filter(Boolean),
notes: notes.value || undefined,
tags: parseTags(tagsRaw.value),
@@ -570,6 +578,20 @@ onMounted(load);
<a-input v-model:value="referrer" placeholder="نام معرف" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="سابقه فعالیت">
<a-select
v-model:value="activityExperience"
allow-clear
placeholder="اختیاری"
style="width: 100%"
:options="[
{ value: '', label: '—' },
...ACTIVITY_EXPERIENCE_OPTIONS.map((value) => ({ value, label: value })),
]"
/>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="کد ملی">
<a-input v-model:value="nationalId" dir="ltr" placeholder="کد ملی (ته‌حساب)" />
+6
View File
@@ -454,6 +454,7 @@ const infoEmpty = computed(() => {
!p.position &&
!p.website &&
!p.instagram &&
!p.activityExperience &&
!p.birthDate &&
!p.referrer &&
!nationalIdLabel.value &&
@@ -829,6 +830,10 @@ watch(() => route.query.tab, readTab, { immediate: true });
<dt>اینستاگرام</dt>
<dd dir="ltr">{{ person.instagram }}</dd>
</div>
<div v-if="person.activityExperience" class="fact">
<dt>سابقه فعالیت</dt>
<dd>{{ person.activityExperience }}</dd>
</div>
<div v-if="person.addresses?.length" class="fact wide">
<dt>آدرس‌ها</dt>
<dd>
@@ -1145,6 +1150,7 @@ watch(() => route.query.tab, readTab, { immediate: true });
<div><dt>نام قبلی</dt><dd>{{ person.previousFullName || '—' }}</dd></div>
<div><dt>وب‌سایت</dt><dd>{{ person.website || '—' }}</dd></div>
<div><dt>اینستاگرام</dt><dd dir="ltr">{{ person.instagram || '—' }}</dd></div>
<div><dt>سابقه فعالیت</dt><dd>{{ person.activityExperience || '—' }}</dd></div>
<div><dt>معرف</dt><dd>{{ person.referrer || '—' }}</dd></div>
<div>
<dt>کد ملی</dt>
File diff suppressed because it is too large Load Diff
+1
View File
@@ -86,6 +86,7 @@ const PERMISSION_MODULES: Partial<Record<RolePermissionKey, OrgModuleKey[]>> = {
treasury_reports: ['treasury'],
treasury_audit: ['treasury'],
treasury_categories: ['treasury'],
treasury_documents_manage: ['treasury'],
behavior: ['behavior'],
};
@@ -24,7 +24,9 @@ import type { TableColumnsType } from 'ant-design-vue';
import { api } from '@/lib/api';
import type { FinancialAccountDto, FinancialMovementDto } from '@mento/shared';
import MoneyInput from '@/components/MoneyInput.vue';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
import { formatJalaliNumeric } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
@@ -43,6 +45,15 @@ const busy = ref(false);
const isMobile = useTreasuryMobile();
const AListItem = AList.Item;
const {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => items.value, 'treasury.account-ledger');
const columns: TableColumnsType<FinancialMovementDto> = [
{
title: 'تاریخ',
@@ -196,7 +207,7 @@ onUnmounted(() => {
<a-divider orientation="right">گردش حساب</a-divider>
<a-empty v-if="!items.length" description="گردشی ثبت نشده است." />
<a-list v-else-if="isMobile" :data-source="items">
<a-list v-else-if="isMobile" :data-source="pagedRows">
<template #renderItem="{ item }">
<a-list-item>
<a-card :title="formatJalaliNumeric(new Date(item.occurredAt))" style="width: 100%">
@@ -220,11 +231,19 @@ onUnmounted(() => {
<a-table
v-else-if="items.length"
:columns="columns"
:data-source="items"
:data-source="pagedRows"
:pagination="false"
row-key="id"
:scroll="{ x: true }"
/>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</a-card>
</a-flex>
</template>
@@ -26,7 +26,9 @@ import { api } from '@/lib/api';
import type { FinancialAccountDto, FinancialAccountType, OrgUserDto } from '@mento/shared';
import MoneyInput from '@/components/MoneyInput.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
import { parseMoneyNumber } from '@/lib/money';
@@ -40,6 +42,15 @@ const accounts = ref<FinancialAccountDto[]>([]);
const users = ref<OrgUserDto[]>([]);
const error = ref('');
const ok = ref('');
const {
page,
pageSize,
pageSizeOptions,
total: listTotal,
pagedRows,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => accounts.value, 'treasury.accounts');
const openForm = ref(false);
const editingId = ref<string | null>(null);
const responsibleKey = ref<string | undefined>(undefined);
@@ -422,7 +433,7 @@ onMounted(() => {
<a-divider orientation="right">فهرست حساب‌ها</a-divider>
<a-empty v-if="!accounts.length" description="حسابی ثبت نشده است." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="accounts">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedRows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -444,6 +455,14 @@ onMounted(() => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="page"
:total="listTotal"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</a-card>
</a-flex>
</template>
@@ -9,7 +9,9 @@ import {
Typography,
} from 'ant-design-vue';
import { api } from '@/lib/api';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { formatJalaliNumeric } from '@/lib/jalali';
import { useTreasuryListPaging } from './useTreasuryListPaging';
const { Paragraph: ATypographyParagraph } = Typography;
const AListItem = AList.Item;
@@ -26,6 +28,15 @@ type Row = {
const rows = ref<Row[]>([]);
const error = ref('');
const {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => rows.value, 'treasury.audit');
const actionLabel: Record<string, string> = {
settle: 'تسویه سند',
cash_post: 'نشستن وجه در حساب',
@@ -47,7 +58,7 @@ onMounted(async () => {
<a-card :bordered="false">
<a-empty v-if="!error && !rows.length" description="سابقه‌ای نیست." />
<a-list v-else item-layout="vertical" :data-source="rows">
<a-list v-else item-layout="vertical" :data-source="pagedRows">
<template #renderItem="{ item }">
<a-list-item>
<a-list-item-meta>
@@ -67,6 +78,14 @@ onMounted(async () => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</a-card>
</a-flex>
</template>
@@ -23,6 +23,8 @@ import {
} from 'ant-design-vue';
import { api } from '@/lib/api';
import type { FinancialCategoryDto } from '@mento/shared';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
const { Text: ATypographyText } = Typography;
@@ -42,6 +44,26 @@ const edit = ref({ id: '', name: '', isActive: true });
const incomeRows = computed(() => rows.value.filter((row) => row.kind === 'income'));
const expenseRows = computed(() => rows.value.filter((row) => row.kind === 'expense'));
const {
page: incomePage,
pageSize: incomePageSize,
pageSizeOptions: incomePageSizeOptions,
total: incomeTotal,
pagedRows: pagedIncomeRows,
onPageSizeChange: onIncomePageSizeChange,
showTotal: incomeShowTotal,
} = useTreasuryListPaging(() => incomeRows.value, 'treasury.categories-income');
const {
page: expensePage,
pageSize: expensePageSize,
pageSizeOptions: expensePageSizeOptions,
total: expenseTotal,
pagedRows: pagedExpenseRows,
onPageSizeChange: onExpensePageSizeChange,
showTotal: expenseShowTotal,
} = useTreasuryListPaging(() => expenseRows.value, 'treasury.categories-expense');
function apiMessage(e: unknown) {
if (!axios.isAxiosError(e)) return 'ذخیره ناموفق بود.';
const msg = (e.response?.data as { message?: string | string[] })?.message;
@@ -153,7 +175,11 @@ onMounted(() => {
<a-divider orientation="right">درآمد</a-divider>
<a-empty v-if="!incomeRows.length" description="دسته درآمدی نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="incomeRows">
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="pagedIncomeRows"
>
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -175,10 +201,22 @@ onMounted(() => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="incomePage"
:total="incomeTotal"
:page-size="incomePageSize"
:page-size-options="incomePageSizeOptions"
:show-total="incomeShowTotal"
@update:page-size="onIncomePageSizeChange"
/>
<a-divider orientation="right">هزینه</a-divider>
<a-empty v-if="!expenseRows.length" description="دسته هزینه‌ای نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="expenseRows">
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="pagedExpenseRows"
>
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -200,6 +238,14 @@ onMounted(() => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="expensePage"
:total="expenseTotal"
:page-size="expensePageSize"
:page-size-options="expensePageSizeOptions"
:show-total="expenseShowTotal"
@update:page-size="onExpensePageSizeChange"
/>
</a-card>
<a-modal
+179 -24
View File
@@ -6,15 +6,21 @@ import type { FinancialAccountDto, FinancialCategoryDto, FinancialDocumentDto }
import { UiButton, UiCard, UiField, UiInput, UiPageHeader } from '@/components/ui';
import MoneyInput from '@/components/MoneyInput.vue';
import TreasuryNav from '@/components/treasury/TreasuryNav.vue';
import { FormFileTooLargeError, prepareFormFieldFile } from '@/lib/form-file-compress';
import { toman } from './treasury-format';
const props = defineProps<{ kind: 'income' | 'expense' }>();
const PHOTO_LIMIT = 8;
type PendingPhoto = { localId: string; name: string; dataUrl: string; file: File };
const rows = ref<FinancialDocumentDto[]>([]);
const categories = ref<FinancialCategoryDto[]>([]);
const accounts = ref<FinancialAccountDto[]>([]);
const error = ref('');
const ok = ref('');
const saving = ref(false);
const photoBusy = ref(false);
const pendingPhotos = ref<PendingPhoto[]>([]);
const q = ref('');
const form = ref({
title: '',
@@ -43,6 +49,76 @@ function apiMessage(e: unknown) {
return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.';
}
function resetForm() {
form.value = {
title: '',
amount: '',
categoryId: '',
partyName: '',
accountId: '',
settleAmount: '',
method: 'transfer',
reference: '',
notes: '',
};
pendingPhotos.value = [];
}
async function prepareTreasuryImage(file: File) {
if (!file.type.startsWith('image/')) {
throw new Error('فقط فایل تصویری مجاز است.');
}
try {
return await prepareFormFieldFile(file);
} catch (e) {
if (e instanceof FormFileTooLargeError) {
throw new Error('حجم عکس باید زیر ۲۰۰ کیلوبایت باشد');
}
throw new Error('فشرده‌سازی عکس ناموفق بود.');
}
}
async function onPhotosPicked(event: Event) {
const input = event.target as HTMLInputElement;
const files = Array.from(input.files ?? []);
input.value = '';
if (!files.length) return;
error.value = '';
for (const file of files) {
if (pendingPhotos.value.length >= PHOTO_LIMIT) {
error.value = `حداکثر ${PHOTO_LIMIT} عکس برای هر سند.`;
break;
}
photoBusy.value = true;
try {
const prepared = await prepareTreasuryImage(file);
pendingPhotos.value = [
...pendingPhotos.value,
{
localId: crypto.randomUUID(),
name: prepared.name,
dataUrl: prepared.dataUrl,
file: prepared.file,
},
];
} catch (e) {
error.value = e instanceof Error ? e.message : 'افزودن عکس ناموفق بود.';
} finally {
photoBusy.value = false;
}
}
}
function removePendingPhoto(localId: string) {
pendingPhotos.value = pendingPhotos.value.filter((photo) => photo.localId !== localId);
}
async function uploadPreparedFile(documentId: string, file: File) {
const body = new FormData();
body.append('file', file);
await api.post(`/treasury/documents/${documentId}/attachments`, body);
}
async function load() {
const [docs, cats, acc] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind: props.kind, q: q.value || undefined } }),
@@ -59,7 +135,7 @@ async function createDoc() {
error.value = '';
ok.value = '';
try {
await api.post('/treasury/documents', {
const { data } = await api.post<FinancialDocumentDto>('/treasury/documents', {
kind: props.kind,
title: form.value.title,
amount: form.value.amount,
@@ -71,18 +147,22 @@ async function createDoc() {
reference: form.value.reference || null,
notes: form.value.notes || null,
});
form.value = {
title: '',
amount: '',
categoryId: '',
partyName: '',
accountId: '',
settleAmount: '',
method: 'transfer',
reference: '',
notes: '',
};
ok.value = 'سند ثبت شد. اگر مبلغ دریافت/پرداخت صفر باشد موجودی حساب تغییر نمی‌کند.';
const photos = [...pendingPhotos.value];
let attached = 0;
for (const photo of photos) {
try {
await uploadPreparedFile(data.id, photo.file);
attached += 1;
} catch (e) {
error.value = apiMessage(e);
break;
}
}
resetForm();
ok.value =
attached > 0
? `سند ثبت شد و ${attached} عکس پیوست شد.`
: 'سند ثبت شد. اگر مبلغ دریافت/پرداخت صفر باشد موجودی حساب تغییر نمی‌کند.';
await load();
} catch (e) {
error.value = apiMessage(e);
@@ -115,16 +195,22 @@ async function downloadAttachment(id: string, fileName: string) {
}
async function upload(id: string, event: Event) {
const file = (event.target as HTMLInputElement).files?.[0];
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
input.value = '';
if (!file) return;
const body = new FormData();
body.append('file', file);
error.value = '';
ok.value = '';
photoBusy.value = true;
try {
await api.post(`/treasury/documents/${id}/attachments`, body);
ok.value = 'پیوست ذخیره شد.';
const prepared = await prepareTreasuryImage(file);
await uploadPreparedFile(id, prepared.file);
ok.value = 'عکس پیوست ذخیره شد.';
await load();
} catch (e) {
error.value = apiMessage(e);
error.value = e instanceof Error && !(axios.isAxiosError(e)) ? e.message : apiMessage(e);
} finally {
photoBusy.value = false;
}
}
@@ -139,6 +225,9 @@ async function voidDoc(id: string) {
}
watch(() => props.kind, () => {
resetForm();
error.value = '';
ok.value = '';
void load();
});
@@ -184,8 +273,30 @@ onMounted(() => {
</UiField>
<UiField label="پیگیری"><UiInput v-model="form.reference" /></UiField>
</div>
<UiButton :loading="saving" @click="createDoc">ثبت</UiButton>
<UiButton variant="secondary" @click="downloadExcel">خروجی اکسل</UiButton>
<div class="photos">
<div class="photos-head">
<strong>عکس فاکتور / رسید</strong>
<small>اختیاری · فشرده‌سازی خودکار · حداکثر ۲۰۰ کیلوبایت برای هر عکس · تا {{ PHOTO_LIMIT }} عکس</small>
</div>
<div v-if="pendingPhotos.length" class="thumbs">
<figure v-for="photo in pendingPhotos" :key="photo.localId">
<img :src="photo.dataUrl" :alt="photo.name" />
<button type="button" :disabled="saving || photoBusy" @click="removePendingPhoto(photo.localId)">حذف</button>
</figure>
</div>
<label class="add-photo" :class="{ busy: photoBusy || saving || pendingPhotos.length >= PHOTO_LIMIT }">
{{ photoBusy ? 'در حال آماده‌سازی…' : 'افزودن عکس' }}
<input
type="file"
accept="image/*"
multiple
:disabled="saving || photoBusy || pendingPhotos.length >= PHOTO_LIMIT"
@change="onPhotosPicked"
/>
</label>
</div>
<UiButton :loading="saving || photoBusy" @click="createDoc">ثبت</UiButton>
<UiButton variant="secondary" :disabled="saving || photoBusy" @click="downloadExcel">خروجی اکسل</UiButton>
</UiCard>
<UiField label="جستجو"><UiInput v-model="q" @change="load" /></UiField>
<div class="list">
@@ -210,9 +321,9 @@ onMounted(() => {
>
{{ file.fileName }}
</button>
<label v-if="row.status !== 'void'" class="file">
پیوست
<input type="file" @change="upload(row.id, $event)" />
<label v-if="row.status !== 'void'" class="file" :class="{ busy: photoBusy }">
{{ photoBusy ? '…' : 'عکس پیوست' }}
<input type="file" accept="image/*" :disabled="photoBusy || saving" @change="upload(row.id, $event)" />
</label>
</div>
</article>
@@ -231,7 +342,51 @@ onMounted(() => {
.side { display: grid; justify-items: end; gap: 0.3rem; }
.side button, .file { border: 0; background: transparent; color: #b91c1c; cursor: pointer; font: inherit; }
.file { color: #0f766e; font-weight: 700; }
.file.busy { opacity: 0.6; pointer-events: none; }
.file input { display: none; }
.photos { display: grid; gap: 0.55rem; margin-bottom: 0.85rem; }
.photos-head { display: grid; gap: 0.15rem; }
.photos-head small { color: #64748b; font-size: 0.82rem; }
.thumbs { display: flex; flex-wrap: wrap; gap: 0.55rem; }
.thumbs figure {
margin: 0;
width: 88px;
display: grid;
gap: 0.25rem;
justify-items: center;
}
.thumbs img {
width: 88px;
height: 88px;
object-fit: cover;
border-radius: 12px;
border: 1px solid #e2e8f0;
background: #f8fafc;
}
.thumbs button {
border: 0;
background: transparent;
color: #b91c1c;
cursor: pointer;
font: inherit;
font-size: 0.8rem;
}
.add-photo {
display: inline-flex;
align-items: center;
justify-content: center;
width: fit-content;
min-height: var(--control-h);
padding: 0 0.9rem;
border: 1px dashed #94a3b8;
border-radius: 12px;
background: #fff;
color: #0f766e;
font-weight: 700;
cursor: pointer;
}
.add-photo.busy { opacity: 0.55; pointer-events: none; }
.add-photo input { display: none; }
.err { color: #b91c1c; font-weight: 700; }
.ok { color: #0f766e; font-weight: 700; }
</style>
@@ -6,13 +6,10 @@ import {
Button as AButton,
Card as ACard,
Col as ACol,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Input as AInput,
List as AList,
Row as ARow,
Segmented as ASegmented,
Select as ASelect,
@@ -30,16 +27,20 @@ import type {
} from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue';
import TreasuryDocPhotoField from '@/components/treasury/TreasuryDocPhotoField.vue';
import TreasuryDocumentsPanel from '@/components/treasury/TreasuryDocumentsPanel.vue';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
import { useSettleDefault } from '@/components/treasury/useSettleDefault';
import { partyNetPosition, toman } from './treasury-format';
import {
uploadTreasuryDocumentPhotos,
type TreasuryPendingPhoto,
} from '@/lib/treasury-doc-photos';
import { accountBalanceTone, partyNetPosition, toman } from './treasury-format';
import { useTreasuryMobile } from './useTreasuryMobile';
import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography;
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option;
const isMobile = useTreasuryMobile();
@@ -52,6 +53,7 @@ const accounts = ref<FinancialAccountDto[]>([]);
const error = ref('');
const ok = ref('');
const saving = ref(false);
const pendingPhotos = ref<TreasuryPendingPhoto[]>([]);
const q = ref('');
const form = ref({
title: '',
@@ -95,17 +97,6 @@ function apiMessage(e: unknown) {
return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.';
}
function docLine(item: FinancialDocumentDto) {
const parts = [
item.reference ? `پیگیری ${item.reference}` : '',
item.partyName || 'بدون طرف حساب',
statusLabel[item.status] ?? item.status,
`مانده ${toman(item.remaining)}`,
].filter(Boolean);
if (item.categoryName) parts.push(item.categoryName);
return parts.join(' · ');
}
async function load() {
const [docs, cats, acc, bals, receivables] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
@@ -202,7 +193,17 @@ async function createDoc() {
notes: form.value.notes || null,
bookedAt: form.value.bookedAt || undefined,
});
const photos = [...pendingPhotos.value];
let attached = 0;
if (photos.length) {
try {
attached = await uploadTreasuryDocumentPhotos(data.id, photos);
} catch (e) {
error.value = apiMessage(e);
}
}
settleMirror.reset();
pendingPhotos.value = [];
form.value = {
title: '',
amount: '',
@@ -215,11 +216,12 @@ async function createDoc() {
notes: '',
bookedAt: formatLocalDateInput(new Date()),
};
ok.value = collectsBalance
const base = collectsBalance
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
: data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.';
ok.value = attached > 0 ? `${base} ${attached} عکس پیوست شد.` : base;
await load();
} catch (e) {
error.value = apiMessage(e);
@@ -279,15 +281,13 @@ const partyPosition = computed(() => {
return partyNetPosition(receivable, payable);
});
async function voidDoc(id: string) {
if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return;
try {
await api.post(`/treasury/documents/${id}/void`, { reason: 'ابطال توسط مدیر' });
await load();
} catch (e) {
error.value = apiMessage(e);
}
}
const selectedAccountBalance = computed(() => {
const id = form.value.accountId;
if (!id) return null;
const account = accounts.value.find((row) => row.id === id);
if (!account) return null;
return accountBalanceTone(account.balance);
});
onMounted(() => {
void load().catch(() => {
@@ -298,190 +298,165 @@ onMounted(() => {
<template>
<a-flex vertical :gap="16">
<a-alert v-if="error" type="error" show-icon :message="error" />
<a-alert v-if="ok" type="success" show-icon :message="ok" />
<a-alert v-if="error" type="error" show-icon :message="error" />
<a-alert v-if="ok" type="success" show-icon :message="ok" />
<a-card :bordered="false">
<a-flex align="center" justify="space-between" wrap="wrap" gap="small">
<a-typography-text strong>سند جدید</a-typography-text>
<a-segmented v-model:value="entryMode" :options="entryOptions" />
</a-flex>
<a-form
layout="vertical"
:model="form"
@finish="createDoc"
@finishFailed="onFinishFailed"
>
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
<a-row :gutter="8" align="middle">
<a-col :span="partyPosition ? 16 : 24">
<TreasuryPartySelect
v-model:kind="form.partyKind"
v-model:party-id="form.partyId"
:allow-other="!isSettlement"
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
/>
</a-col>
<a-col v-if="partyPosition" :span="8">
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
</a-col>
</a-row>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="عنوان"
name="title"
:rules="[{ required: true, message: 'عنوان الزامی است' }]"
<a-card :bordered="false" title="سند جدید">
<template #extra>
<a-segmented v-model:value="entryMode" :options="entryOptions" />
</template>
<a-form
layout="vertical"
:model="form"
@finish="createDoc"
@finishFailed="onFinishFailed"
>
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
<a-row :gutter="8" align="middle">
<a-col :span="partyPosition ? 16 : 24">
<TreasuryPartySelect
v-model:kind="form.partyKind"
v-model:party-id="form.partyId"
:allow-other="!isSettlement"
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
/>
</a-col>
<a-col v-if="partyPosition" :span="8">
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
</a-col>
</a-row>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="عنوان"
name="title"
:rules="[{ required: true, message: 'عنوان الزامی است' }]"
>
<a-input v-model:value="form.title" />
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item
label="مبلغ کل"
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item
:label="settleLabel"
name="settleAmount"
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
>
<MoneyInput
addon-after="تومان"
v-model="form.settleAmount"
:decimals="0"
:disabled="!isSettlement && form.partyKind === 'other'"
/>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="مانده این سند">
<MoneyInput
addon-after="تومان"
:model-value="remainingAmount"
:decimals="0"
disabled
/>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId">
<a-select
show-search
option-filter-prop="label"
v-model:value="form.categoryId"
allow-clear
style="width: 100%"
placeholder="بدون دسته"
>
<a-input v-model:value="form.title" />
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item
label="مبلغ کل"
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item
:label="settleLabel"
name="settleAmount"
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
>
<MoneyInput
addon-after="تومان"
v-model="form.settleAmount"
:decimals="0"
:disabled="!isSettlement && form.partyKind === 'other'"
/>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="مانده این سند">
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId">
<a-select show-search option-filter-prop="label"
v-model:value="form.categoryId"
allow-clear
style="width: 100%"
placeholder="بدون دسته"
>
<a-select-option v-for="cat in categories" :key="cat.id" :value="cat.id" :label="cat.name">
{{ cat.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="حساب" name="accountId" :rules="accountRules">
<a-select show-search option-filter-prop="label"
v-model:value="form.accountId"
allow-clear
style="width: 100%"
placeholder="انتخاب حساب"
>
<a-select-option v-for="account in accounts" :key="account.id" :value="account.id" :label="account.name">
{{ account.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="روش" name="method">
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%">
<a-select-option v-for="opt in methodOptions" :key="opt.value" :value="opt.value" :label="opt.label">
{{ opt.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="تاریخ" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" />
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :span="24">
<a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" />
</a-form-item>
</a-col>
</a-row>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-form>
<a-divider orientation="right">مانده پرداختنی</a-divider>
<TreasuryPartyBalanceTable :rows="balances" settled-label="پرداخت‌شده" />
<a-divider orientation="right">فهرست اسناد</a-divider>
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="جستجو">
<a-input
v-model:value="q"
allow-clear
placeholder="عنوان یا شماره پیگیری"
@press-enter="load"
@change="load"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-empty v-if="!rows.length" description="سندی نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
<template #renderItem="{ item }">
<a-list-item>
<template v-if="!isMobile" #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
type="link"
danger
@click="voidDoc(item.id)"
>
ابطال
</a-button>
</template>
<a-flex v-if="isMobile" vertical :gap="4" style="width: 100%">
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
<a-typography-text strong>{{ item.title }}</a-typography-text>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</a-flex>
<a-typography-text type="secondary">
{{ item.partyName || 'بدون طرف حساب' }} · {{ statusLabel[item.status] ?? item.status }}
</a-typography-text>
<a-typography-text v-if="item.reference" type="secondary">پیگیری {{ item.reference }}</a-typography-text>
<a-typography-text v-if="item.categoryName" type="secondary">{{ item.categoryName }}</a-typography-text>
<a-flex justify="space-between" align="center">
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
type="link"
danger
@click="voidDoc(item.id)"
<a-select-option v-for="cat in categories" :key="cat.id" :value="cat.id" :label="cat.name">
{{ cat.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item name="accountId" :rules="accountRules">
<template #label>
<a-flex align="center" justify="space-between" gap="small" style="width: 100%">
<span>حساب</span>
<a-typography-text
v-if="selectedAccountBalance"
:type="selectedAccountBalance.type"
>
ابطال
</a-button>
{{ selectedAccountBalance.text }}
</a-typography-text>
</a-flex>
</a-flex>
<a-list-item-meta v-else>
<template #title>{{ item.title }}</template>
<template #description>{{ docLine(item) }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</template>
<a-select
show-search
option-filter-prop="label"
v-model:value="form.accountId"
allow-clear
style="width: 100%"
placeholder="انتخاب حساب"
>
<a-select-option v-for="account in accounts" :key="account.id" :value="account.id" :label="account.name">
{{ account.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="روش" name="method">
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%">
<a-select-option v-for="opt in methodOptions" :key="opt.value" :value="opt.value" :label="opt.label">
{{ opt.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تاریخ" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="عکس فاکتور / رسید">
<TreasuryDocPhotoField v-model="pendingPhotos" :disabled="saving" />
</a-form-item>
</a-col>
</a-row>
<a-space>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-space>
</a-form>
</a-card>
<a-card :bordered="false" title="مانده پرداختنی">
<TreasuryPartyBalanceTable :rows="balances" settled-label="پرداخت‌شده" />
</a-card>
<TreasuryDocumentsPanel
v-model:q="q"
:rows="rows"
:categories="categories"
:status-label="statusLabel"
@reload="load"
/>
</a-flex>
</template>
@@ -14,7 +14,9 @@ import {
} from 'ant-design-vue';
import { api } from '@/lib/api';
import type { TreasuryDashboardDto } from '@mento/shared';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
const { Text: ATypographyText } = Typography;
@@ -36,6 +38,42 @@ const cards = [
{ key: 'totalBalance', label: 'موجودی حساب‌ها', hint: 'صندوق و بانک' },
] as const;
const {
page: installmentPage,
pageSize: installmentPageSize,
pageSizeOptions: installmentPageSizeOptions,
total: installmentTotal,
pagedRows: pagedInstallments,
onPageSizeChange: onInstallmentPageSizeChange,
showTotal: installmentShowTotal,
} = useTreasuryListPaging(
() => data.value?.upcomingInstallments ?? [],
'treasury.home-installments',
);
const {
page: payablePage,
pageSize: payablePageSize,
pageSizeOptions: payablePageSizeOptions,
total: payableTotal,
pagedRows: pagedPayables,
onPageSizeChange: onPayablePageSizeChange,
showTotal: payableShowTotal,
} = useTreasuryListPaging(
() => data.value?.upcomingPayables ?? [],
'treasury.home-payables',
);
const {
page: recentPage,
pageSize: recentPageSize,
pageSizeOptions: recentPageSizeOptions,
total: recentTotal,
pagedRows: pagedRecent,
onPageSizeChange: onRecentPageSizeChange,
showTotal: recentShowTotal,
} = useTreasuryListPaging(() => data.value?.recent ?? [], 'treasury.home-recent');
onMounted(async () => {
try {
const res = await api.get<TreasuryDashboardDto>('/treasury/dashboard');
@@ -78,7 +116,7 @@ onMounted(async () => {
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="data.upcomingInstallments"
:data-source="pagedInstallments"
>
<template #renderItem="{ item }">
<a-list-item>
@@ -94,6 +132,14 @@ onMounted(async () => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="installmentPage"
:total="installmentTotal"
:page-size="installmentPageSize"
:page-size-options="installmentPageSizeOptions"
:show-total="installmentShowTotal"
@update:page-size="onInstallmentPageSizeChange"
/>
</a-col>
<a-col :xs="24" :lg="12">
@@ -105,7 +151,7 @@ onMounted(async () => {
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="data.upcomingPayables"
:data-source="pagedPayables"
>
<template #renderItem="{ item }">
<a-list-item>
@@ -119,6 +165,14 @@ onMounted(async () => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="payablePage"
:total="payableTotal"
:page-size="payablePageSize"
:page-size-options="payablePageSizeOptions"
:show-total="payableShowTotal"
@update:page-size="onPayablePageSizeChange"
/>
</a-col>
</a-row>
@@ -130,7 +184,7 @@ onMounted(async () => {
<a-list
v-else
:item-layout="isMobile ? 'vertical' : 'horizontal'"
:data-source="data.recent"
:data-source="pagedRecent"
>
<template #renderItem="{ item }">
<a-list-item>
@@ -146,6 +200,14 @@ onMounted(async () => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="recentPage"
:total="recentTotal"
:page-size="recentPageSize"
:page-size-options="recentPageSizeOptions"
:show-total="recentShowTotal"
@update:page-size="onRecentPageSizeChange"
/>
</a-card>
</template>
</a-flex>
@@ -6,14 +6,11 @@ import {
Button as AButton,
Card as ACard,
Col as ACol,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex,
Form as AForm,
FormItem as AFormItem,
Grid,
Input as AInput,
List as AList,
Row as ARow,
Segmented as ASegmented,
Select as ASelect,
@@ -31,15 +28,19 @@ import type {
} from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue';
import TreasuryDocPhotoField from '@/components/treasury/TreasuryDocPhotoField.vue';
import TreasuryDocumentsPanel from '@/components/treasury/TreasuryDocumentsPanel.vue';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
import { useSettleDefault } from '@/components/treasury/useSettleDefault';
import { partyNetPosition, toman } from './treasury-format';
import {
uploadTreasuryDocumentPhotos,
type TreasuryPendingPhoto,
} from '@/lib/treasury-doc-photos';
import { accountBalanceTone, partyNetPosition, toman } from './treasury-format';
import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography;
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option;
const screens = Grid.useBreakpoint();
const isMobile = computed(() => !screens.value.md);
@@ -53,6 +54,7 @@ const accounts = ref<FinancialAccountDto[]>([]);
const error = ref('');
const ok = ref('');
const saving = ref(false);
const pendingPhotos = ref<TreasuryPendingPhoto[]>([]);
const q = ref('');
function emptyForm() {
@@ -130,6 +132,14 @@ const partyPosition = computed(() => {
return partyNetPosition(receivable, payable);
});
const selectedAccountBalance = computed(() => {
const id = form.value.accountId;
if (!id) return null;
const account = accounts.value.find((row) => row.id === id);
if (!account) return null;
return accountBalanceTone(account.balance);
});
watch(entryMode, () => {
settleMirror.reset();
form.value.amount = '';
@@ -156,17 +166,6 @@ function apiMessage(e: unknown) {
return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.';
}
function docLine(item: FinancialDocumentDto) {
const parts = [
item.reference ? `پیگیری ${item.reference}` : '',
item.partyName || 'بدون طرف حساب',
statusLabel[item.status] ?? item.status,
`مانده ${toman(item.remaining)}`,
].filter(Boolean);
if (item.categoryName) parts.push(item.categoryName);
return parts.join(' · ');
}
async function load() {
const [docs, cats, acc, bals, payables] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
@@ -201,6 +200,7 @@ async function load() {
function resetForm() {
settleMirror.reset();
form.value = emptyForm();
pendingPhotos.value = [];
error.value = '';
ok.value = '';
}
@@ -266,12 +266,22 @@ async function createDoc() {
notes: form.value.notes || null,
bookedAt: form.value.bookedAt || undefined,
});
const photos = [...pendingPhotos.value];
let attached = 0;
if (photos.length) {
try {
attached = await uploadTreasuryDocumentPhotos(data.id, photos);
} catch (e) {
error.value = apiMessage(e);
}
}
resetForm();
ok.value = collectsBalance
const base = collectsBalance
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
: data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.';
ok.value = attached > 0 ? `${base} ${attached} عکس پیوست شد.` : base;
await load();
} catch (e) {
error.value = apiMessage(e);
@@ -280,16 +290,6 @@ async function createDoc() {
}
}
async function voidDoc(id: string) {
if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return;
try {
await api.post(`/treasury/documents/${id}/void`, { reason: 'ابطال توسط مدیر' });
await load();
} catch (e) {
error.value = apiMessage(e);
}
}
onMounted(() => {
void load().catch(() => {
error.value = 'بارگذاری ناموفق بود.';
@@ -299,199 +299,175 @@ onMounted(() => {
<template>
<a-flex vertical :gap="16">
<a-alert v-if="error" type="error" show-icon :message="error" />
<a-alert v-if="ok" type="success" show-icon :message="ok" />
<a-alert v-if="error" type="error" show-icon :message="error" />
<a-alert v-if="ok" type="success" show-icon :message="ok" />
<a-card :bordered="false">
<a-flex align="center" justify="space-between" wrap="wrap" gap="small">
<a-typography-text strong>سند جدید</a-typography-text>
<a-segmented v-model:value="entryMode" :options="entryOptions" />
</a-flex>
<a-form
layout="vertical"
:model="form"
@finish="createDoc"
@finishFailed="onFinishFailed"
>
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
<a-row :gutter="8" align="middle">
<a-col :span="partyPosition ? 16 : 24">
<TreasuryPartySelect
v-model:kind="form.partyKind"
v-model:party-id="form.partyId"
:allow-other="!isSettlement"
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
/>
</a-col>
<a-col v-if="partyPosition" :span="8">
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
</a-col>
</a-row>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="عنوان"
name="title"
:rules="[{ required: true, message: 'عنوان الزامی است' }]"
>
<a-input v-model:value="form.title" />
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item
label="مبلغ کل"
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item
:label="settleLabel"
name="settleAmount"
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
>
<MoneyInput
addon-after="تومان"
v-model="form.settleAmount"
:decimals="0"
:disabled="!isSettlement && form.partyKind === 'other'"
<a-card :bordered="false" title="سند جدید">
<template #extra>
<a-segmented v-model:value="entryMode" :options="entryOptions" />
</template>
<a-form
layout="vertical"
:model="form"
@finish="createDoc"
@finishFailed="onFinishFailed"
>
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="طرف حساب" name="partyKind" :rules="partyRules">
<a-row :gutter="8" align="middle">
<a-col :span="partyPosition ? 16 : 24">
<TreasuryPartySelect
v-model:kind="form.partyKind"
v-model:party-id="form.partyId"
:allow-other="!isSettlement"
:placeholder="isSettlement ? 'مشتری، شرکت یا کاربر' : undefined"
/>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="مانده این سند">
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId">
<a-select show-search option-filter-prop="label"
v-model:value="form.categoryId"
allow-clear
style="width: 100%"
placeholder="بدون دسته"
>
<a-select-option v-for="cat in categories" :key="cat.id" :value="cat.id" :label="cat.name">
{{ cat.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="حساب" name="accountId" :rules="accountRules">
<a-select show-search option-filter-prop="label"
v-model:value="form.accountId"
allow-clear
style="width: 100%"
placeholder="انتخاب حساب"
>
<a-select-option
v-for="account in accounts"
:key="account.id"
:value="account.id"
:label="account.name"
>
{{ account.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="روش" name="method">
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%">
<a-select-option
v-for="opt in methodOptions"
:key="opt.value"
:value="opt.value"
:label="opt.label"
>
{{ opt.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :md="8">
<a-form-item label="تاریخ" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" />
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :md="16">
<a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" />
</a-form-item>
</a-col>
</a-row>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-form>
</a-col>
<a-col v-if="partyPosition" :span="8">
<a-typography-text :type="partyPosition.type">{{ partyPosition.text }}</a-typography-text>
</a-col>
</a-row>
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item
label="عنوان"
name="title"
:rules="[{ required: true, message: 'عنوان الزامی است' }]"
>
<a-input v-model:value="form.title" />
</a-form-item>
</a-col>
<a-divider orientation="right">مانده دریافتنی</a-divider>
<TreasuryPartyBalanceTable :rows="balances" settled-label="دریافت‌شده" />
<a-divider orientation="right">فهرست اسناد</a-divider>
<a-form layout="vertical">
<a-row :gutter="[16, 0]">
<a-col :xs="24" :md="12">
<a-form-item label="جستجو">
<a-input
v-model:value="q"
allow-clear
placeholder="عنوان یا شماره پیگیری"
@press-enter="load"
@change="load"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item
label="مبلغ کل"
name="amount"
:rules="[{ required: true, message: 'مبلغ الزامی است' }]"
>
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item
:label="settleLabel"
name="settleAmount"
:rules="isSettlement ? [{ required: true, message: 'مبلغ را وارد کنید' }] : []"
>
<MoneyInput
addon-after="تومان"
v-model="form.settleAmount"
:decimals="0"
:disabled="!isSettlement && form.partyKind === 'other'"
/>
</a-form-item>
</a-col>
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="مانده این سند">
<MoneyInput
addon-after="تومان"
:model-value="remainingAmount"
:decimals="0"
disabled
/>
</a-form-item>
</a-col>
<a-empty v-if="!rows.length" description="سندی نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
<template #renderItem="{ item }">
<a-list-item>
<template v-if="!isMobile" #actions>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
type="link"
danger
@click="voidDoc(item.id)"
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId">
<a-select
show-search
option-filter-prop="label"
v-model:value="form.categoryId"
allow-clear
style="width: 100%"
placeholder="بدون دسته"
>
<a-select-option v-for="cat in categories" :key="cat.id" :value="cat.id" :label="cat.name">
{{ cat.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item name="accountId" :rules="accountRules">
<template #label>
<a-flex align="center" justify="space-between" gap="small" style="width: 100%">
<span>حساب</span>
<a-typography-text
v-if="selectedAccountBalance"
:type="selectedAccountBalance.type"
>
ابطال
</a-button>
</template>
<a-flex v-if="isMobile" vertical :gap="4" style="width: 100%">
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
<a-typography-text strong>{{ item.title }}</a-typography-text>
<a-typography-text strong>{{ toman(item.amount) }}</a-typography-text>
</a-flex>
<a-typography-text type="secondary">
{{ item.partyName || 'بدون طرف حساب' }} · {{ statusLabel[item.status] ?? item.status }}
{{ selectedAccountBalance.text }}
</a-typography-text>
<a-typography-text v-if="item.reference" type="secondary">پیگیری {{ item.reference }}</a-typography-text>
<a-typography-text v-if="item.categoryName" type="secondary">{{ item.categoryName }}</a-typography-text>
<a-flex justify="space-between" align="center">
<a-typography-text>مانده {{ toman(item.remaining) }}</a-typography-text>
<a-button
v-if="item.status !== 'void'"
type="link"
danger
@click="voidDoc(item.id)"
>
ابطال
</a-button>
</a-flex>
</a-flex>
<a-list-item-meta v-else>
<template #title>{{ item.title }}</template>
<template #description>{{ docLine(item) }}</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
</a-card>
</template>
<a-select
show-search
option-filter-prop="label"
v-model:value="form.accountId"
allow-clear
style="width: 100%"
placeholder="انتخاب حساب"
>
<a-select-option
v-for="account in accounts"
:key="account.id"
:value="account.id"
:label="account.name"
>
{{ account.name }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="روش" name="method">
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%">
<a-select-option
v-for="opt in methodOptions"
:key="opt.value"
:value="opt.value"
:label="opt.label"
>
{{ opt.label }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تاریخ" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" />
</a-form-item>
</a-col>
<a-col :xs="24" :sm="12" :md="8">
<a-form-item label="عکس فاکتور / رسید">
<TreasuryDocPhotoField v-model="pendingPhotos" :disabled="saving" />
</a-form-item>
</a-col>
</a-row>
<a-space>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-space>
</a-form>
</a-card>
<a-card :bordered="false" title="مانده دریافتنی">
<TreasuryPartyBalanceTable :rows="balances" settled-label="دریافت‌شده" />
</a-card>
<TreasuryDocumentsPanel
v-model:q="q"
:rows="rows"
:categories="categories"
:status-label="statusLabel"
@reload="load"
/>
</a-flex>
</template>
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import {
Alert as AAlert,
@@ -42,7 +42,9 @@ import {
toFaDigits,
formatJalaliNumeric,
} from '@/lib/jalali';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography;
@@ -189,6 +191,31 @@ const filtered = computed(() => {
});
});
const {
page: reportPage,
pageSize: reportPageSize,
pageSizeOptions: reportPageSizeOptions,
total: reportTotal,
pagedRows: pagedReportRows,
onPageSizeChange: onReportPageSizeChange,
showTotal: reportShowTotal,
resetPage: resetReportPage,
} = useTreasuryListPaging(() => filtered.value, 'treasury.payroll-report');
const {
page: paymentPage,
pageSize: paymentPageSize,
pageSizeOptions: paymentPageSizeOptions,
total: paymentTotal,
pagedRows: pagedPayments,
onPageSizeChange: onPaymentPageSizeChange,
showTotal: paymentShowTotal,
resetPage: resetPaymentPage,
} = useTreasuryListPaging(() => selectedPay.value?.payments ?? [], 'treasury.payroll-payments');
watch(selectedPay, () => resetPaymentPage());
watch(filtered, () => resetReportPage());
const moneyKeys = ['baseAmount', 'benefits', 'bonus', 'deductions', 'payable', 'paidAmount', 'remaining'] as const;
const reportColumns: TableColumnsType<PayrollRow> = [
@@ -653,7 +680,7 @@ onMounted(() => {
</a-space>
</a-form>
<a-list v-if="isMobile && selectedPay?.payments.length" :data-source="selectedPay.payments">
<a-list v-if="isMobile && selectedPay?.payments.length" :data-source="pagedPayments">
<template #renderItem="{ item }">
<a-list-item>
<a-card style="width: 100%">
@@ -672,7 +699,7 @@ onMounted(() => {
<a-table
v-else-if="selectedPay?.payments.length"
:columns="paymentColumns"
:data-source="selectedPay.payments"
:data-source="pagedPayments"
:pagination="false"
row-key="id"
>
@@ -700,6 +727,15 @@ onMounted(() => {
</template>
</template>
</a-table>
<TreasuryListPagination
v-if="selectedPay?.payments.length"
v-model:page="paymentPage"
:total="paymentTotal"
:page-size="paymentPageSize"
:page-size-options="paymentPageSizeOptions"
:show-total="paymentShowTotal"
@update:page-size="onPaymentPageSizeChange"
/>
</a-flex>
</a-card>
@@ -765,7 +801,7 @@ onMounted(() => {
<a-empty v-if="!filtered.length" description="رکوردی با این فیلتر نیست." />
<a-flex v-else vertical :gap="8">
<a-card
v-for="row in filtered"
v-for="row in pagedReportRows"
:key="row.id"
hoverable
@click="detail = row"
@@ -851,7 +887,8 @@ onMounted(() => {
<a-col :xs="0" :md="24">
<a-table
:columns="reportColumns"
:data-source="filtered"
:data-source="pagedReportRows"
:pagination="false"
row-key="id"
:scroll="{ x: 'max-content' }"
:locale="{ emptyText: 'رکوردی با این فیلتر نیست.' }"
@@ -907,6 +944,14 @@ onMounted(() => {
</a-table>
</a-col>
</a-row>
<TreasuryListPagination
v-model:page="reportPage"
:total="reportTotal"
:page-size="reportPageSize"
:page-size-options="reportPageSizeOptions"
:show-total="reportShowTotal"
@update:page-size="onReportPageSizeChange"
/>
</a-card>
<a-modal
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref } from 'vue';
import axios from 'axios';
import {
Alert as AAlert,
@@ -29,10 +29,13 @@ import { api } from '@/lib/api';
import type { FinancialAccountDto, FinancialReceivableDto } from '@mento/shared';
import MoneyInput from '@/components/MoneyInput.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
import { formatJalaliNumeric } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize';
const { Text: ATypographyText } = Typography;
const ASelectOption = ASelect.Option;
@@ -44,6 +47,25 @@ const accounts = ref<FinancialAccountDto[]>([]);
const error = ref('');
const ok = ref('');
const saving = ref(false);
const {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => rows.value, 'treasury.receivables');
const installmentPageSize = usePageSize('treasury.receivables-installments', 10);
const installmentPageSizeOptions = PAGE_SIZE_OPTIONS.map(String);
const installmentTablePagination = computed(() => ({
pageSize: installmentPageSize.value,
showSizeChanger: true,
pageSizeOptions: installmentPageSizeOptions,
onShowSizeChange: (_current: number, size: number) => {
installmentPageSize.value = size;
},
}));
const form = ref({
title: '',
partyName: '',
@@ -361,7 +383,7 @@ onMounted(() => {
<a-divider orientation="right">قراردادها</a-divider>
<a-empty v-if="!rows.length" description="قراردادی ثبت نشده است." />
<template v-else>
<div v-for="row in rows" :key="row.id">
<div v-for="row in pagedRows" :key="row.id">
<a-flex justify="space-between" align="flex-start" wrap="wrap" :gap="8">
<div>
<a-typography-text strong>{{ row.title }}</a-typography-text>
@@ -372,7 +394,11 @@ onMounted(() => {
</div>
<a-typography-text strong>{{ toman(row.totalAmount) }}</a-typography-text>
</a-flex>
<a-list v-if="isMobile" :data-source="row.installments">
<a-list
v-if="isMobile"
:data-source="row.installments"
:pagination="installmentTablePagination"
>
<template #renderItem="{ item }">
<a-list-item>
<a-card :title="`قسط ${item.position}`" style="width: 100%">
@@ -401,7 +427,7 @@ onMounted(() => {
v-else
:columns="installmentColumns"
:data-source="row.installments"
:pagination="false"
:pagination="installmentTablePagination"
row-key="id"
:scroll="{ x: true }"
>
@@ -422,6 +448,14 @@ onMounted(() => {
</a-table>
<a-divider />
</div>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</template>
</a-card>
</a-flex>
@@ -21,7 +21,9 @@ import {
import { api } from '@/lib/api';
import MoneyInput from '@/components/MoneyInput.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
import { formatJalaliNumeric } from '@/lib/jalali';
import { parseMoneyNumber } from '@/lib/money';
@@ -45,6 +47,15 @@ const rows = ref<Row[]>([]);
const error = ref('');
const ok = ref('');
const saving = ref(false);
const {
page,
pageSize,
pageSizeOptions,
total,
pagedRows,
onPageSizeChange,
showTotal,
} = useTreasuryListPaging(() => rows.value, 'treasury.recurring');
const form = ref({ title: '', kind: 'expense', amount: '', interval: 'monthly', startDate: '' });
async function load() {
@@ -148,7 +159,7 @@ onMounted(() => {
<a-divider orientation="right">فهرست الگوها</a-divider>
<a-empty v-if="!rows.length" description="الگویی ثبت نشده است." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="rows">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedRows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -165,6 +176,14 @@ onMounted(() => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="page"
:total="total"
:page-size="pageSize"
:page-size-options="pageSizeOptions"
:show-total="showTotal"
@update:page-size="onPageSizeChange"
/>
</a-card>
</a-flex>
</template>
@@ -20,8 +20,10 @@ import { DownloadOutlined } from '@ant-design/icons-vue';
import * as XLSX from 'xlsx';
import type { TreasuryPartyBalanceDto } from '@mento/shared';
import { api } from '@/lib/api';
import TreasuryListPagination from '@/components/treasury/TreasuryListPagination.vue';
import TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import { toman } from './treasury-format';
import { useTreasuryListPaging } from './useTreasuryListPaging';
import { useTreasuryMobile } from './useTreasuryMobile';
const { Text: ATypographyText } = Typography;
@@ -92,6 +94,39 @@ const metricRows = computed<MetricRow[]>(() => {
}));
});
const {
page: partyPage,
pageSize: partyPageSize,
pageSizeOptions: partyPageSizeOptions,
total: partyTotal,
pagedRows: pagedPartyRows,
onPageSizeChange: onPartyPageSizeChange,
showTotal: partyShowTotal,
} = useTreasuryListPaging(() => receivablesByParty.value, 'treasury.reports-party');
const {
page: monthPage,
pageSize: monthPageSize,
pageSizeOptions: monthPageSizeOptions,
total: monthTotal,
pagedRows: pagedMonthRows,
onPageSizeChange: onMonthPageSizeChange,
showTotal: monthShowTotal,
} = useTreasuryListPaging(() => payablesByMonth.value, 'treasury.reports-month');
const {
page: expenseCatPage,
pageSize: expenseCatPageSize,
pageSizeOptions: expenseCatPageSizeOptions,
total: expenseCatTotal,
pagedRows: pagedExpenseCats,
onPageSizeChange: onExpenseCatPageSizeChange,
showTotal: expenseCatShowTotal,
} = useTreasuryListPaging(
() => current.value?.expenseCategories ?? [],
'treasury.reports-expense-cats',
);
async function load() {
const { data } = await api.get<{
current: Period;
@@ -213,7 +248,7 @@ onMounted(() => {
<a-divider orientation="right">مطالبات به تفکیک طرف حساب</a-divider>
<a-empty v-if="!receivablesByParty.length" description="مورد بازی نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="receivablesByParty">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedPartyRows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -225,10 +260,18 @@ onMounted(() => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="partyPage"
:total="partyTotal"
:page-size="partyPageSize"
:page-size-options="partyPageSizeOptions"
:show-total="partyShowTotal"
@update:page-size="onPartyPageSizeChange"
/>
<a-divider orientation="right">تعهدات به تفکیک ماه</a-divider>
<a-empty v-if="!payablesByMonth.length" description="تعهد بازی نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="payablesByMonth">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedMonthRows">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -240,11 +283,19 @@ onMounted(() => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="monthPage"
:total="monthTotal"
:page-size="monthPageSize"
:page-size-options="monthPageSizeOptions"
:show-total="monthShowTotal"
@update:page-size="onMonthPageSizeChange"
/>
<template v-if="current">
<a-divider orientation="right">سهم هزینه‌ها</a-divider>
<a-empty v-if="!current.expenseCategories.length" description="دسته‌ای نیست." />
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="current.expenseCategories">
<a-list v-else :item-layout="isMobile ? 'vertical' : 'horizontal'" :data-source="pagedExpenseCats">
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
@@ -258,6 +309,14 @@ onMounted(() => {
</a-list-item>
</template>
</a-list>
<TreasuryListPagination
v-model:page="expenseCatPage"
:total="expenseCatTotal"
:page-size="expenseCatPageSize"
:page-size-options="expenseCatPageSizeOptions"
:show-total="expenseCatShowTotal"
@update:page-size="onExpenseCatPageSizeChange"
/>
</template>
</a-flex>
</a-tab-pane>
@@ -11,3 +11,13 @@ export function partyNetPosition(receivable: number, payable: number) {
if (net < 0) return { text: `بس ${toman(-net)}`, type: 'success' as const };
return { text: `مانده ${toman(0)}`, type: 'secondary' as const };
}
/** موجودی حساب: مثبت سبز، منفی قرمز، صفر خاکستری. */
export function accountBalanceTone(balance: string | number | null | undefined) {
const n = Number(balance ?? 0);
if (!Number.isFinite(n) || n === 0) {
return { text: `موجودی ${toman(0)}`, type: 'secondary' as const };
}
if (n > 0) return { text: `موجودی ${toman(n)}`, type: 'success' as const };
return { text: `موجودی ${toman(n)}`, type: 'danger' as const };
}
@@ -0,0 +1,47 @@
import { computed, ref, watch, type Ref } from 'vue';
import { toFaDigits } from '@/lib/jalali';
import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize';
/** صفحه‌بندی مشترک فهرست‌ها و جداول مدیریت مالی (۱۰/۲۰/۵۰/۱۰۰). */
export function useTreasuryListPaging<T>(getRows: () => readonly T[], storageKey: string, fallback = 10) {
const page = ref(1);
const pageSize = usePageSize(storageKey, fallback);
const pageSizeOptions = PAGE_SIZE_OPTIONS.map(String);
const total = computed(() => getRows().length);
const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value) || 1));
const pagedRows = computed(() => {
const start = (page.value - 1) * pageSize.value;
return getRows().slice(start, start + pageSize.value) as T[];
});
watch([total, pageSize], () => {
if (page.value > pageCount.value) page.value = pageCount.value;
if (page.value < 1) page.value = 1;
});
function resetPage() {
page.value = 1;
}
function onPageSizeChange(size: number) {
pageSize.value = size;
page.value = 1;
}
function showTotal(count: number) {
return `مجموع: ${toFaDigits(count)} مورد (صفحه ${toFaDigits(page.value)} از ${toFaDigits(pageCount.value)})`;
}
return {
page,
pageSize: pageSize as Ref<number>,
pageSizeOptions,
total,
pageCount,
pagedRows,
resetPage,
onPageSizeChange,
showTotal,
};
}