30 Commits
Author SHA1 Message Date
MahdiandCursor 70524f4f2c Allow treasury payments when account balance goes negative.
Remove insufficient-balance blocks on document create, settle, and party collection so income/expense posting can overdraw an account.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 16:43:25 +03:30
MahdiandCursor 1b08ab1230 Show selected account balance beside the treasury account field.
Color the balance green, red, or gray on income and expense forms so users see cash position before posting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 13:48:30 +03:30
MahdiandCursor 4409ded0ab Add treasury document photos, table list, and manage permission.
Income/expense lists are table-or-card with detail, edit, void, and delete; edit/delete require owner, admin, or the new finance manage permission.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 12:42:01 +03:30
MahdiandCursor 3696713443 Fix routines manage select popup typing for vue-tsc.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 20:48:48 +03:30
MahdiandCursor d282627af7 Add searchable assignee and creator filters on the routines manage toolbar.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 20:45:37 +03:30
MahdiandCursor fb6aa77465 Omit createdBy relation when duplicating a routine so API types still compile.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 20:16:12 +03:30
MahdiandCursor 54d360ded8 Show routine creator in the manage list so managers can see who defined each routine.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 20:07:41 +03:30
MahdiandCursor 717a41e94b Substitute org name and balance tokens in outbound SMS so templates no longer leave {از طرف} literal.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 17:12:31 +03:30
MahdiandCursor f36fddc23b Allow inserting dynamic field tokens while creating SMS templates.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 14:55:25 +03:30
MahdiandCursor e04aa14b84 Add org-scoped reusable SMS templates in the compose modal.
Users can save, pick, and delete prepared messages shared across the organization.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 14:15:42 +03:30
MahdiandCursor 3c27fae626 Apply overdue/today/upcoming date colors on sales deal cards as well.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 13:13:40 +03:30
MahdiandCursor 33eeb3242a Add activity priority desk filter and keep detail browsing inside the same column after stage changes.
When done/reopen/stage moves leave a column, advance to the next activity there or return to the list if empty.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 12:02:13 +03:30
MahdiandCursor ae16e43013 Clarify activity card due tones: overdue as عقب افتاده, done as انجام شده, and today in warning yellow.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 21:52:56 +03:30
MahdiandCursor 7a55b84b81 Add org-scoped activity priority labels/colors and apply them across forms, boards, and routines.
Also fix activity leave-without-save confirm, kanban due-date labels with tone-colored peek chevron, and rename the types manager button.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 21:39:15 +03:30
MahdiandCursor a1ac677b3a Combine data-access and contact list facets with OR so each selected dimension grants visibility.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 20:15:21 +03:30
MahdiandCursor b00465439e Drop groupIds from customer data-access filters; keep visibility via group assignees only.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 19:50:02 +03:30
MahdiandCursor 9af0e9e94e Fix customer groups modal scroll nesting and make assignees removable via chips.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 19:07:36 +03:30
MahdiandCursor b745b6d460 Tighten team users table with a compact row-number column and fixed layout.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 18:30:49 +03:30
MahdiandCursor fec5ece255 Improve deal board activity cues with relative dates and a quick activity list popup.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 16:27:32 +03:30
MahdiandCursor f4f2311ae4 Improve team settings responsive layout, narrower role panel, and mobile pagination.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 15:31:58 +03:30
MahdiandCursor 57e0fdd600 Improve team settings search, user sorting, and role badge layout.
EOF

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 14:01:08 +03:30
MahdiandCursor b583858088 feat(customers): add optional group assignees with OR visibility for people, companies, and birthdays
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 12:59:49 +03:30
MahdiandCursor 453ff1a5f6 fix(activities): allow assignees to attach files when commenting under creator-only edit
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 09:49:22 +03:30
MahdiandCursor 68fcece743 fix(activities): keep comment and postpone open for assignees under creator-only edit
Allow dueAt/description patches for collaborators when editPolicy is creator-only, and show the no-edit warning only when they try to change locked fields—not as a permanent banner.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 09:23:10 +03:30
MahdiandCursor de77066cb0 feat(tahesab): add manual sync to refresh linked customer profiles
Expose sync/customers-now and a settings button so existing linked people get national id, address, city, and rasteh without waiting for the schedule.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 18:54:59 +03:30
MahdiandCursor d23dd20237 feat(tahesab): sync full customer profile fields into CRM people
Pull national id, address, city, and rasteh on import/refresh so person records match Tahesab, and surface them on the person form and profile.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 18:31:47 +03:30
MahdiandCursor 8a4bd70ad4 fix(boards): keep kanban card drag from locking after a few moves
Reset hung move queues, defer drag visuals past dragstart, and prefer card drop identity so HTML5 DnD no longer dies mid-drag.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 16:58:19 +03:30
MahdiandCursor d87321c7bf fix(activities): type ActivityRow with editPolicy for API builds
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 16:01:16 +03:30
MahdiandCursor 1a05eee46d feat(activities): let creators lock edit and delete to themselves
Add editPolicy (default creator-only), enforce it in the API, surface clear permission messages, and drop the redundant edit menu now that detail is editable.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 15:56:36 +03:30
MahdiandCursor ec9a7cf9c9 feat(deals): plan activities on the deal and create them from the board
Show related activities on deal detail, prefill dealId on activity create, and add a side-panel quick create from pipeline cards.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-11 15:06:20 +03:30
89 changed files with 7356 additions and 1422 deletions
@@ -0,0 +1,5 @@
-- CreateEnum
CREATE TYPE "ActivityEditPolicy" AS ENUM ('creator', 'assignees');
-- AlterTable
ALTER TABLE "Activity" ADD COLUMN "editPolicy" "ActivityEditPolicy" NOT NULL DEFAULT 'creator';
@@ -0,0 +1,28 @@
-- مسئولان اختیاری روی گروه‌های مشتری
CREATE TABLE IF NOT EXISTS "_CustomerGroupAssignees" (
"A" TEXT NOT NULL,
"B" TEXT NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS "_CustomerGroupAssignees_AB_unique" ON "_CustomerGroupAssignees"("A", "B");
CREATE INDEX IF NOT EXISTS "_CustomerGroupAssignees_B_index" ON "_CustomerGroupAssignees"("B");
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = '_CustomerGroupAssignees_A_fkey'
) THEN
ALTER TABLE "_CustomerGroupAssignees"
ADD CONSTRAINT "_CustomerGroupAssignees_A_fkey"
FOREIGN KEY ("A") REFERENCES "CustomerGroup"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
END IF;
IF NOT EXISTS (
SELECT 1 FROM pg_constraint WHERE conname = '_CustomerGroupAssignees_B_fkey'
) THEN
ALTER TABLE "_CustomerGroupAssignees"
ADD CONSTRAINT "_CustomerGroupAssignees_B_fkey"
FOREIGN KEY ("B") REFERENCES "User"("id")
ON DELETE CASCADE ON UPDATE CASCADE;
END IF;
END $$;
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Organization" ADD COLUMN "activityPriorities" JSONB NOT NULL DEFAULT '{}';
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Organization" ADD COLUMN "smsTemplates" JSONB NOT NULL DEFAULT '[]';
+15
View File
@@ -38,6 +38,12 @@ enum ActivityCompletionMode {
all all
} }
/// چه کسانی می‌توانند فعالیت را ویرایش/حذف کنند (علاوه بر owner/admin)
enum ActivityEditPolicy {
creator
assignees
}
enum ActivityPriority { enum ActivityPriority {
low low
medium medium
@@ -156,6 +162,10 @@ model Organization {
enabledCurrencies String[] @default(["IRR", "USD", "EUR"]) enabledCurrencies String[] @default(["IRR", "USD", "EUR"])
/// ماژول‌های فعال منو برای این محیط /// ماژول‌های فعال منو برای این محیط
enabledModules String[] @default([]) enabledModules String[] @default([])
/// برچسب/رنگ اولویت فعالیت و روتین (کلیدهای enum ثابت؛ فقط ظاهر)
activityPriorities Json @default("{}")
/// قالب‌های آمادهٔ پیامک دستی ([{ id, name, body }, …])
smsTemplates Json @default("[]")
/// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخاب‌شده)؛ null = بدون فیلتر /// تاریخ قطع بایگانی اطلاعات قبل (شروع روز انتخاب‌شده)؛ null = بدون فیلتر
priorArchiveEnabledAt DateTime? priorArchiveEnabledAt DateTime?
isActive Boolean @default(true) isActive Boolean @default(true)
@@ -300,6 +310,7 @@ model User {
ownedInvoices Invoice[] @relation("InvoiceOwner") ownedInvoices Invoice[] @relation("InvoiceOwner")
ownedPeople Person[] @relation("PersonOwner") ownedPeople Person[] @relation("PersonOwner")
ownedCompanies Company[] @relation("CompanyOwner") ownedCompanies Company[] @relation("CompanyOwner")
assignedCustomerGroups CustomerGroup[] @relation("CustomerGroupAssignees")
financialPartyDocuments FinancialDocument[] @relation("FinancialDocumentParty") financialPartyDocuments FinancialDocument[] @relation("FinancialDocumentParty")
ownedProjectCards ProjectCard[] @relation("ProjectCardOwner") ownedProjectCards ProjectCard[] @relation("ProjectCardOwner")
activities Activity[] @relation("ActivityAssignee") activities Activity[] @relation("ActivityAssignee")
@@ -570,6 +581,8 @@ model CustomerGroup {
children CustomerGroup[] @relation("CustomerGroupTree") children CustomerGroup[] @relation("CustomerGroupTree")
people PersonGroupLink[] people PersonGroupLink[]
companies CompanyGroupLink[] companies CompanyGroupLink[]
/// مسئولان گروه — اختیاری؛ اعضای گروه را مثل مشتریان خود می‌بینند
assignees User[] @relation("CustomerGroupAssignees")
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@ -892,6 +905,8 @@ model Activity {
completionMode ActivityCompletionMode @default(any) completionMode ActivityCompletionMode @default(any)
/// مسئولانی که سهم خود را در حالت all ثبت کرده‌اند /// مسئولانی که سهم خود را در حالت all ثبت کرده‌اند
completedByIds String[] @default([]) completedByIds String[] @default([])
/// creator = فقط ایجادکننده؛ assignees = ایجادکننده + همهٔ مسئولان
editPolicy ActivityEditPolicy @default(creator)
tags String[] @default([]) tags String[] @default([])
personId String? personId String?
person Person? @relation(fields: [personId], references: [id], onDelete: SetNull) person Person? @relation(fields: [personId], references: [id], onDelete: SetNull)
@@ -7,6 +7,7 @@ import {
Param, Param,
Patch, Patch,
Post, Post,
Put,
Query, Query,
Res, Res,
StreamableFile, StreamableFile,
@@ -40,6 +41,7 @@ import {
ReorderActivityTypesDto, ReorderActivityTypesDto,
UpdateActivityBoardDto, UpdateActivityBoardDto,
UpdateActivityDto, UpdateActivityDto,
UpdateActivityPrioritiesDto,
UpdateActivityStageDto, UpdateActivityStageDto,
UpdateActivityTypeDto, UpdateActivityTypeDto,
} from './dto'; } from './dto';
@@ -139,6 +141,18 @@ export class ActivitiesController {
return { ok: true }; return { ok: true };
} }
@Get('priorities')
listPriorities(@CurrentUser() user: Actor) {
return this.typesService.listPriorities(user.organizationId);
}
@Put('priorities')
@UseGuards(RolesGuard)
@Roles('owner', 'admin')
updatePriorities(@CurrentUser() user: Actor, @Body() dto: UpdateActivityPrioritiesDto) {
return this.typesService.updatePriorities(user.organizationId, dto.items);
}
@Get('types') @Get('types')
listTypes(@CurrentUser() user: Actor) { listTypes(@CurrentUser() user: Actor) {
return this.typesService.list(user.organizationId); return this.typesService.list(user.organizationId);
@@ -196,6 +210,7 @@ export class ActivitiesController {
title: query.title, title: query.title,
customer: query.customer, customer: query.customer,
due: query.due, due: query.due,
priority: query.priority,
boardId: query.boardId, boardId: query.boardId,
}, },
); );
@@ -232,6 +247,7 @@ export class ActivitiesController {
title: query.title, title: query.title,
customer: query.customer, customer: query.customer,
due: query.due, due: query.due,
priority: query.priority,
boardId: query.boardId, boardId: query.boardId,
}, },
query.stageId ? { stageId: query.stageId } : undefined, query.stageId ? { stageId: query.stageId } : undefined,
@@ -265,6 +281,7 @@ export class ActivitiesController {
title: query.title, title: query.title,
customer: query.customer, customer: query.customer,
due: query.due, due: query.due,
priority: query.priority,
boardId: query.boardId, boardId: query.boardId,
}, },
query.stageId ? { stageId: query.stageId } : undefined, query.stageId ? { stageId: query.stageId } : undefined,
@@ -68,6 +68,43 @@ function canForceClose(
return actor.role === 'owner' || actor.role === 'admin' || actor.userId === createdById; return actor.role === 'owner' || actor.role === 'admin' || actor.userId === createdById;
} }
function canMutateActivity(
actor: { userId: string; role: string },
row: {
createdById?: string | null;
editPolicy?: 'creator' | 'assignees' | null;
assigneeId?: string | null;
assignees?: Array<{ id: string }>;
},
): boolean {
if (actor.role === 'owner' || actor.role === 'admin') return true;
if (row.createdById && actor.userId === row.createdById) return true;
if ((row.editPolicy ?? 'creator') !== 'assignees') return false;
return assigneeIdList(row).includes(actor.userId);
}
/** ثبت نظر / تعویق — برای همهٔ مسئولان، حتی وقتی ویرایش فقط با ایجادکننده است */
function canCollaborateActivity(
actor: { userId: string; role: string },
row: {
createdById?: string | null;
assigneeId?: string | null;
assignees?: Array<{ id: string }>;
},
): boolean {
if (actor.role === 'owner' || actor.role === 'admin') return true;
if (row.createdById && actor.userId === row.createdById) return true;
return assigneeIdList(row).includes(actor.userId);
}
/** فقط dueAt / description → تعویق و ثبت نظر */
function isCollaboratorPatch(dto: UpdateActivityRequest): boolean {
const keys = Object.keys(dto).filter(
(key) => (dto as Record<string, unknown>)[key] !== undefined,
);
return keys.length > 0 && keys.every((key) => key === 'dueAt' || key === 'description');
}
function reconcileAllShares(assigneeIds: string[], completedByIds: string[]) { function reconcileAllShares(assigneeIds: string[], completedByIds: string[]) {
const kept = [...new Set(completedByIds.filter((id) => assigneeIds.includes(id)))]; const kept = [...new Set(completedByIds.filter((id) => assigneeIds.includes(id)))];
const done = assigneeIds.length > 0 && assigneeIds.every((id) => kept.includes(id)); const done = assigneeIds.length > 0 && assigneeIds.every((id) => kept.includes(id));
@@ -86,6 +123,7 @@ type ListFacets = {
customer?: string; customer?: string;
/** set = زمان شروع دارد، unset = ندارد */ /** set = زمان شروع دارد، unset = ندارد */
due?: 'set' | 'unset'; due?: 'set' | 'unset';
priority?: ActivityDto['priority'];
/** گروه فعالیت؛ خالی = همهٔ گروه‌ها */ /** گروه فعالیت؛ خالی = همهٔ گروه‌ها */
boardId?: string; boardId?: string;
}; };
@@ -106,6 +144,7 @@ type ActivityRow = {
completedAt: Date | null; completedAt: Date | null;
completionMode?: 'any' | 'all'; completionMode?: 'any' | 'all';
completedByIds?: string[]; completedByIds?: string[];
editPolicy?: 'creator' | 'assignees';
importSource?: string; importSource?: string;
promotedFromPriorAt?: Date | null; promotedFromPriorAt?: Date | null;
tags: string[]; tags: string[];
@@ -737,6 +776,7 @@ export class ActivitiesService {
: undefined, : undefined,
completionMode: dto.completionMode === 'all' ? 'all' : 'any', completionMode: dto.completionMode === 'all' ? 'all' : 'any',
completedByIds: [], completedByIds: [],
editPolicy: dto.editPolicy === 'assignees' ? 'assignees' : 'creator',
createdById: userId, createdById: userId,
}, },
include, include,
@@ -813,10 +853,23 @@ export class ActivitiesService {
participantIds: true, participantIds: true,
completionMode: true, completionMode: true,
completedByIds: true, completedByIds: true,
editPolicy: true,
createdById: true,
assigneeId: true, assigneeId: true,
assignees: { select: { id: true } }, assignees: { select: { id: true } },
}, },
}); });
if (!existing) {
throw new ForbiddenException('شما مجوز ویرایش این فعالیت را ندارید');
}
const collabOnly = isCollaboratorPatch(dto);
if (collabOnly) {
if (!canCollaborateActivity(actor, existing)) {
throw new ForbiddenException('شما مجوز ثبت نظر یا تعویق این فعالیت را ندارید');
}
} else if (!canMutateActivity(actor, existing)) {
throw new ForbiddenException('شما مجوز ویرایش این فعالیت را ندارید');
}
const data: Prisma.ActivityUncheckedUpdateInput = {}; const data: Prisma.ActivityUncheckedUpdateInput = {};
if (dto.title !== undefined) data.title = dto.title.trim(); if (dto.title !== undefined) data.title = dto.title.trim();
if ('boardId' in dto) { if ('boardId' in dto) {
@@ -932,6 +985,9 @@ export class ActivitiesService {
const modeChanged = dto.completionMode === 'any' || dto.completionMode === 'all'; const modeChanged = dto.completionMode === 'any' || dto.completionMode === 'all';
const nextMode = modeChanged ? dto.completionMode! : (existing?.completionMode ?? 'any'); const nextMode = modeChanged ? dto.completionMode! : (existing?.completionMode ?? 'any');
if (modeChanged) data.completionMode = nextMode; if (modeChanged) data.completionMode = nextMode;
if (dto.editPolicy === 'creator' || dto.editPolicy === 'assignees') {
data.editPolicy = dto.editPolicy;
}
const prevAssigneeIds = assigneeIdList(existing ?? {}); const prevAssigneeIds = assigneeIdList(existing ?? {});
const nextIds = nextAssigneeIds ?? prevAssigneeIds; const nextIds = nextAssigneeIds ?? prevAssigneeIds;
const explicitDone = dto.status === 'done'; const explicitDone = dto.status === 'done';
@@ -1105,6 +1161,18 @@ export class ActivitiesService {
actor: ActivityActor, actor: ActivityActor,
): Promise<void> { ): Promise<void> {
await this.ensureExists(organizationId, id, actor); await this.ensureExists(organizationId, id, actor);
const existing = await this.prisma.activity.findFirst({
where: { id, organizationId },
select: {
createdById: true,
editPolicy: true,
assigneeId: true,
assignees: { select: { id: true } },
},
});
if (!existing || !canMutateActivity(actor, existing)) {
throw new ForbiddenException('شما مجوز حذف این فعالیت را ندارید');
}
const images = await this.prisma.activityImage.findMany({ const images = await this.prisma.activityImage.findMany({
where: { activityId: id, organizationId }, where: { activityId: id, organizationId },
select: { storageKey: true, sizeBytes: true }, select: { storageKey: true, sizeBytes: true },
@@ -1125,6 +1193,19 @@ export class ActivitiesService {
actor: ActivityActor, actor: ActivityActor,
): Promise<ActivityImageDto> { ): Promise<ActivityImageDto> {
await this.ensureExists(organizationId, activityId, actor); await this.ensureExists(organizationId, activityId, actor);
const gate = await this.prisma.activity.findFirst({
where: { id: activityId, organizationId },
select: {
createdById: true,
editPolicy: true,
assigneeId: true,
assignees: { select: { id: true } },
},
});
// پیوست در مسیر ثبت نظر — مسئولان هم مجازند حتی با editPolicy=creator
if (!gate || !canCollaborateActivity(actor, gate)) {
throw new ForbiddenException('شما مجوز ثبت نظر یا پیوست برای این فعالیت را ندارید');
}
if (!file?.buffer?.length) { if (!file?.buffer?.length) {
throw new BadRequestException('فایلی ارسال نشده است'); throw new BadRequestException('فایلی ارسال نشده است');
} }
@@ -1219,10 +1300,27 @@ export class ActivitiesService {
actor: ActivityActor, actor: ActivityActor,
): Promise<void> { ): Promise<void> {
await this.ensureExists(organizationId, activityId, actor); await this.ensureExists(organizationId, activityId, actor);
const gate = await this.prisma.activity.findFirst({
where: { id: activityId, organizationId },
select: {
createdById: true,
editPolicy: true,
assigneeId: true,
assignees: { select: { id: true } },
},
});
const row = await this.prisma.activityImage.findFirst({ const row = await this.prisma.activityImage.findFirst({
where: { id: imageId, activityId, organizationId }, where: { id: imageId, activityId, organizationId },
}); });
if (!row) throw new NotFoundException('فایل پیدا نشد'); if (!row) throw new NotFoundException('فایل پیدا نشد');
const canMutate = !!gate && canMutateActivity(actor, gate);
const canRemoveOwn =
!!gate &&
canCollaborateActivity(actor, gate) &&
row.uploadedById === actor.userId;
if (!canMutate && !canRemoveOwn) {
throw new ForbiddenException('شما مجوز حذف این پیوست را ندارید');
}
await this.files.remove(row.storageKey); await this.files.remove(row.storageKey);
await this.prisma.activityImage.delete({ where: { id: row.id } }); await this.prisma.activityImage.delete({ where: { id: row.id } });
await this.storage.addLocal(organizationId, -row.sizeBytes); await this.storage.addLocal(organizationId, -row.sizeBytes);
@@ -1272,11 +1370,13 @@ export class ActivitiesService {
const facetTypeDef = facets?.typeDefId?.trim(); const facetTypeDef = facets?.typeDefId?.trim();
const facetTitle = facets?.title?.trim(); const facetTitle = facets?.title?.trim();
const facetCustomer = facets?.customer?.trim(); const facetCustomer = facets?.customer?.trim();
const facetPriority = facets?.priority;
const andParts: Prisma.ActivityWhereInput[] = [ const andParts: Prisma.ActivityWhereInput[] = [
scope, scope,
...(facets?.type ? [{ type: facets.type }] : []), ...(facets?.type ? [{ type: facets.type }] : []),
...(facetTypeDef ? [this.types.whereForType(typeRows, facetTypeDef)] : []), ...(facetTypeDef ? [this.types.whereForType(typeRows, facetTypeDef)] : []),
...(facets?.status ? [{ status: facets.status }] : []), ...(facets?.status ? [{ status: facets.status }] : []),
...(facetPriority ? [{ priority: facetPriority }] : []),
...(facetTitle ? [{ title: ci(facetTitle) }] : []), ...(facetTitle ? [{ title: ci(facetTitle) }] : []),
...(facetCustomer ? [this.customerWhere(facetCustomer)] : []), ...(facetCustomer ? [this.customerWhere(facetCustomer)] : []),
...(facetAssignee ...(facetAssignee
@@ -1570,6 +1670,7 @@ export class ActivitiesService {
completedAt: row.completedAt?.toISOString() ?? null, completedAt: row.completedAt?.toISOString() ?? null,
completionMode: row.completionMode ?? 'any', completionMode: row.completionMode ?? 'any',
completedByIds: row.completedByIds ?? [], completedByIds: row.completedByIds ?? [],
editPolicy: row.editPolicy ?? 'creator',
importSource: row.importSource ?? 'manual', importSource: row.importSource ?? 'manual',
promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null, promotedFromPriorAt: row.promotedFromPriorAt?.toISOString() ?? null,
tags: row.tags ?? [], tags: row.tags ?? [],
@@ -6,6 +6,8 @@ import type {
ActivityFieldValue, ActivityFieldValue,
ActivityFieldValues, ActivityFieldValues,
ActivityParticipantsValue, ActivityParticipantsValue,
ActivityPriority,
ActivityPrioritySetting,
ActivityStageColor, ActivityStageColor,
ActivityType, ActivityType,
ActivityTypeDefDto, ActivityTypeDefDto,
@@ -17,8 +19,11 @@ import type {
import { import {
ACTIVITY_FIELD_TYPES, ACTIVITY_FIELD_TYPES,
ACTIVITY_FIELD_TYPES_WITH_OPTIONS, ACTIVITY_FIELD_TYPES_WITH_OPTIONS,
ACTIVITY_PRIORITY_KEYS,
ACTIVITY_STAGE_COLORS, ACTIVITY_STAGE_COLORS,
ACTIVITY_TYPE_ICONS, ACTIVITY_TYPE_ICONS,
DEFAULT_ACTIVITY_PRIORITY_SETTINGS,
parseActivityPrioritySettings,
} from '@mento/shared'; } from '@mento/shared';
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
@@ -619,6 +624,43 @@ export class ActivityTypesService {
: 'green'; : 'green';
} }
async listPriorities(organizationId: string): Promise<ActivityPrioritySetting[]> {
const row = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { activityPriorities: true },
});
return parseActivityPrioritySettings(row?.activityPriorities);
}
async updatePriorities(
organizationId: string,
items: Array<{ key: ActivityPriority; label: string; color: string }>,
): Promise<ActivityPrioritySetting[]> {
const byKey = new Map(items.map((i) => [i.key, i]));
if (ACTIVITY_PRIORITY_KEYS.some((k) => !byKey.has(k))) {
throw new BadRequestException('هر پنج سطح اولویت باید ارسال شوند');
}
const hex = /^#[0-9a-fA-F]{6}$/;
const stored: Record<string, { label: string; color: string }> = {};
for (const key of ACTIVITY_PRIORITY_KEYS) {
const item = byKey.get(key)!;
const label = item.label.trim().slice(0, 40);
const color = item.color.trim();
if (!label) throw new BadRequestException(`عنوان اولویت «${key}» خالی است`);
if (!hex.test(color)) throw new BadRequestException(`رنگ اولویت «${key}» نامعتبر است`);
const def = DEFAULT_ACTIVITY_PRIORITY_SETTINGS.find((d) => d.key === key)!;
// فقط تفاوت با پیش‌فرض را نگه می‌داریم تا JSON جمع‌وجور بماند
if (label !== def.label || color.toLowerCase() !== def.color.toLowerCase()) {
stored[key] = { label, color };
}
}
await this.prisma.organization.update({
where: { id: organizationId },
data: { activityPriorities: stored as Prisma.InputJsonValue },
});
return parseActivityPrioritySettings(stored);
}
private mapError(e: unknown) { private mapError(e: unknown) {
if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') { if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
return new BadRequestException('نوع فعالیتی با این نام وجود دارد'); return new BadRequestException('نوع فعالیتی با این نام وجود دارد');
+38
View File
@@ -9,11 +9,13 @@ import {
IsObject, IsObject,
IsOptional, IsOptional,
IsString, IsString,
Matches,
Max, Max,
MaxLength, MaxLength,
Min, Min,
MinLength, MinLength,
ValidateIf, ValidateIf,
ValidateNested,
} from 'class-validator'; } from 'class-validator';
import type { ActivityFieldDef, ActivityFieldValues, ActivityTypeIcon } from '@mento/shared'; import type { ActivityFieldDef, ActivityFieldValues, ActivityTypeIcon } from '@mento/shared';
import { ACTIVITY_TYPE_ICONS } from '@mento/shared'; import { ACTIVITY_TYPE_ICONS } from '@mento/shared';
@@ -91,6 +93,11 @@ export class ListActivitiesQueryDto {
@IsString() @IsString()
typeDefId?: string; typeDefId?: string;
/** اولویت فعالیت (کلید ثابت؛ برچسب در تنظیمات سازمان) */
@IsOptional()
@IsIn(ACTIVITY_PRIORITIES)
priority?: (typeof ACTIVITY_PRIORITIES)[number];
/** شناسهٔ مرحله یا 'all' — حالت تب/کانبان مراحل */ /** شناسهٔ مرحله یا 'all' — حالت تب/کانبان مراحل */
@IsOptional() @IsOptional()
@IsString() @IsString()
@@ -388,6 +395,10 @@ export class CreateActivityDto {
@IsOptional() @IsOptional()
@IsIn(['any', 'all']) @IsIn(['any', 'all'])
completionMode?: 'any' | 'all'; completionMode?: 'any' | 'all';
@IsOptional()
@IsIn(['creator', 'assignees'])
editPolicy?: 'creator' | 'assignees';
} }
export class UpdateActivityDto { export class UpdateActivityDto {
@@ -492,4 +503,31 @@ export class UpdateActivityDto {
@IsOptional() @IsOptional()
@IsIn(['any', 'all']) @IsIn(['any', 'all'])
completionMode?: 'any' | 'all'; completionMode?: 'any' | 'all';
@IsOptional()
@IsIn(['creator', 'assignees'])
editPolicy?: 'creator' | 'assignees';
}
const PRIORITY_KEYS = ['very_low', 'low', 'medium', 'high', 'very_high'] as const;
export class ActivityPriorityItemDto {
@IsIn(PRIORITY_KEYS)
key!: (typeof PRIORITY_KEYS)[number];
@IsString()
@MinLength(1)
@MaxLength(40)
label!: string;
@IsString()
@Matches(/^#[0-9a-fA-F]{6}$/)
color!: string;
}
export class UpdateActivityPrioritiesDto {
@IsArray()
@ValidateNested({ each: true })
@Type(() => ActivityPriorityItemDto)
items!: ActivityPriorityItemDto[];
} }
+106 -77
View File
@@ -105,29 +105,33 @@ export function resolveAllSectionAccess(input: {
return out; return out;
} }
/** ابعاد پرشدهٔ یک قانون با OR؛ خالی = null */
function unionFacets<T>(facets: T[]): T | { OR: T[] } | null {
if (!facets.length) return null;
return facets.length === 1 ? facets[0]! : { OR: facets };
}
export function buildContactRuleWhere( export function buildContactRuleWhere(
rule: DataAccessRule, rule: DataAccessRule,
ctx: { userId: string; teamPeerIds: string[] | null }, ctx: { userId: string; teamPeerIds: string[] | null },
): Prisma.PersonWhereInput | null { ): Prisma.PersonWhereInput | null {
const and: Prisma.PersonWhereInput[] = []; const facets: Prisma.PersonWhereInput[] = [];
const ids = ownerIdList(rule, ctx);
if (rule.owners?.length) { if (rule.owners?.length) {
if (!ids.length) return null; const ids = ownerIdList(rule, ctx);
and.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } }); if (ids.length) {
facets.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } });
} }
if (rule.groupIds?.length) {
and.push({ groupLinks: { some: { groupId: { in: rule.groupIds } } } });
} }
// groupIds دیگر فیلتر دسترسی نیست؛ دید گروه فقط از مسئول‌گروه (personViaGroupAssignee)
if (rule.sources?.length) { if (rule.sources?.length) {
and.push({ facets.push({
OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }], OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }],
}); });
} }
if (rule.moods?.length) { if (rule.moods?.length) {
and.push({ mood: { in: rule.moods } }); facets.push({ mood: { in: rule.moods } });
} }
if (!and.length) return null; return unionFacets(facets);
return and.length === 1 ? and[0]! : { AND: and };
} }
function orParts<T>(parts: T[]): T | { OR: T[] } | { id: string } { function orParts<T>(parts: T[]): T | { OR: T[] } | { id: string } {
@@ -135,6 +139,23 @@ function orParts<T>(parts: T[]): T | { OR: T[] } | { id: string } {
return parts.length === 1 ? parts[0]! : { OR: parts }; return parts.length === 1 ? parts[0]! : { OR: parts };
} }
/** اعضای گروه‌هایی که کاربر مسئولشان است */
function personViaGroupAssignee(userId: string): Prisma.PersonWhereInput {
return {
groupLinks: {
some: { group: { assignees: { some: { id: userId } } } },
},
};
}
function companyViaGroupAssignee(userId: string): Prisma.CompanyWhereInput {
return {
groupLinks: {
some: { group: { assignees: { some: { id: userId } } } },
},
};
}
export function customersPersonWhere( export function customersPersonWhere(
actor: Pick<Actor, 'userId' | 'role' | 'customersAccess' | 'teamPeerIds'>, actor: Pick<Actor, 'userId' | 'role' | 'customersAccess' | 'teamPeerIds'>,
): Prisma.PersonWhereInput { ): Prisma.PersonWhereInput {
@@ -149,6 +170,8 @@ export function customersPersonWhere(
}); });
if (w) parts.push(w); if (w) parts.push(w);
} }
// مسئول گروه: اتحاد با محدودیت نقش (مالک خودم یا عضو گروه تحت مسئولیت)
parts.push(personViaGroupAssignee(actor.userId));
return orParts(parts); return orParts(parts);
} }
@@ -160,34 +183,28 @@ export function customersCompanyWhere(
if (!sectionHasDataAccessLimits(section)) return {}; if (!sectionHasDataAccessLimits(section)) return {};
const parts: Prisma.CompanyWhereInput[] = []; const parts: Prisma.CompanyWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.CompanyWhereInput[] = []; // حال مشتری روی شرکت معنا ندارد؛ فقط مالک/منبع
if (rule.moods?.length && !rule.owners?.length && !rule.sources?.length) continue;
const facets: Prisma.CompanyWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } }); facets.push(ids.length === 1 ? { ownerId: ids[0]! } : { ownerId: { in: ids } });
} }
if (rule.groupIds?.length) {
and.push({ groupLinks: { some: { groupId: { in: rule.groupIds } } } });
} }
// groupIds دیگر فیلتر دسترسی نیست؛ دید گروه فقط از مسئول‌گروه (companyViaGroupAssignee)
if (rule.sources?.length) { if (rule.sources?.length) {
and.push({ facets.push({
OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }], OR: [{ importSource: { in: rule.sources } }, { sourceRef: { in: rule.sources } }],
}); });
} }
if ( const w = unionFacets(facets);
rule.moods?.length && if (w) parts.push(w);
!rule.owners?.length &&
!rule.groupIds?.length &&
!rule.sources?.length
) {
continue;
}
if (!and.length) continue;
parts.push(and.length === 1 ? and[0]! : { AND: and });
} }
parts.push(companyViaGroupAssignee(actor.userId));
return orParts(parts); return orParts(parts);
} }
@@ -199,27 +216,28 @@ export function leadsDeepWhere(
if (!sectionHasDataAccessLimits(section)) return {}; if (!sectionHasDataAccessLimits(section)) return {};
const parts: Prisma.LeadWhereInput[] = []; const parts: Prisma.LeadWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.LeadWhereInput[] = []; const facets: Prisma.LeadWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } }); facets.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } });
}
} }
if (rule.stageIds?.length) { if (rule.stageIds?.length) {
and.push({ stageId: { in: rule.stageIds } }); facets.push({ stageId: { in: rule.stageIds } });
} }
if (rule.sources?.length) { if (rule.sources?.length) {
and.push({ facets.push({
OR: rule.sources.map((s) => ({ OR: rule.sources.map((s) => ({
source: { equals: s, mode: 'insensitive' as const }, source: { equals: s, mode: 'insensitive' as const },
})), })),
}); });
} }
if (!and.length) continue; const w = unionFacets(facets);
parts.push(and.length === 1 ? and[0]! : { AND: and }); if (w) parts.push(w);
} }
return orParts(parts); return orParts(parts);
} }
@@ -232,28 +250,29 @@ export function dealsDeepWhere(
if (!sectionHasDataAccessLimits(section)) return {}; if (!sectionHasDataAccessLimits(section)) return {};
const parts: Prisma.DealWhereInput[] = []; const parts: Prisma.DealWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.DealWhereInput[] = []; const facets: Prisma.DealWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push({ facets.push({
OR: [ OR: [
{ ownerId: { in: ids } }, { ownerId: { in: ids } },
{ assignees: { some: { id: { in: ids } } } }, { assignees: { some: { id: { in: ids } } } },
], ],
}); });
} }
}
if (rule.pipelineIds?.length) { if (rule.pipelineIds?.length) {
and.push({ pipelineId: { in: rule.pipelineIds } }); facets.push({ pipelineId: { in: rule.pipelineIds } });
} }
if (rule.stageIds?.length) { if (rule.stageIds?.length) {
and.push({ stageId: { in: rule.stageIds } }); facets.push({ stageId: { in: rule.stageIds } });
} }
if (!and.length) continue; const w = unionFacets(facets);
parts.push(and.length === 1 ? and[0]! : { AND: and }); if (w) parts.push(w);
} }
return orParts(parts); return orParts(parts);
} }
@@ -266,14 +285,14 @@ export function activitiesDeepWhere(
if (!sectionHasDataAccessLimits(section)) return {}; if (!sectionHasDataAccessLimits(section)) return {};
const parts: Prisma.ActivityWhereInput[] = []; const parts: Prisma.ActivityWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.ActivityWhereInput[] = []; const facets: Prisma.ActivityWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push({ facets.push({
OR: [ OR: [
{ assigneeId: { in: ids } }, { assigneeId: { in: ids } },
{ assignees: { some: { id: { in: ids } } } }, { assignees: { some: { id: { in: ids } } } },
@@ -281,17 +300,18 @@ export function activitiesDeepWhere(
], ],
}); });
} }
}
if (rule.boardIds?.length) { if (rule.boardIds?.length) {
and.push({ boardId: { in: rule.boardIds } }); facets.push({ boardId: { in: rule.boardIds } });
} }
if (rule.stageIds?.length) { if (rule.stageIds?.length) {
and.push({ stageId: { in: rule.stageIds } }); facets.push({ stageId: { in: rule.stageIds } });
} }
if (rule.typeIds?.length) { if (rule.typeIds?.length) {
and.push({ typeDefId: { in: rule.typeIds } }); facets.push({ typeDefId: { in: rule.typeIds } });
} }
if (!and.length) continue; const w = unionFacets(facets);
parts.push(and.length === 1 ? and[0]! : { AND: and }); if (w) parts.push(w);
} }
return orParts(parts); return orParts(parts);
} }
@@ -310,14 +330,14 @@ export function notesDeepWhere(
if (!sectionHasDataAccessLimits(section)) return personalGate; if (!sectionHasDataAccessLimits(section)) return personalGate;
const parts: Prisma.NoteWhereInput[] = []; const parts: Prisma.NoteWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.NoteWhereInput[] = []; const facets: Prisma.NoteWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push({ facets.push({
OR: [ OR: [
{ authorId: { in: ids } }, { authorId: { in: ids } },
{ {
@@ -333,11 +353,12 @@ export function notesDeepWhere(
], ],
}); });
} }
if (rule.sources?.length) {
and.push({ noteType: { in: rule.sources } });
} }
if (!and.length) continue; if (rule.sources?.length) {
parts.push(and.length === 1 ? and[0]! : { AND: and }); facets.push({ noteType: { in: rule.sources } });
}
const w = unionFacets(facets);
if (w) parts.push(w);
} }
return { return {
AND: [personalGate, orParts(parts)], AND: [personalGate, orParts(parts)],
@@ -352,26 +373,27 @@ export function ticketsDeepWhere(
if (!sectionHasDataAccessLimits(section)) return {}; if (!sectionHasDataAccessLimits(section)) return {};
const parts: Prisma.TicketWhereInput[] = []; const parts: Prisma.TicketWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.TicketWhereInput[] = []; const facets: Prisma.TicketWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push({ facets.push({
OR: [{ assigneeId: { in: ids } }, { reporterId: { in: ids } }], OR: [{ assigneeId: { in: ids } }, { reporterId: { in: ids } }],
}); });
} }
}
if (rule.sources?.length) { if (rule.sources?.length) {
and.push({ facets.push({
status: { status: {
in: rule.sources as Array<'open' | 'in_progress' | 'waiting' | 'resolved' | 'closed'>, in: rule.sources as Array<'open' | 'in_progress' | 'waiting' | 'resolved' | 'closed'>,
}, },
}); });
} }
if (!and.length) continue; const w = unionFacets(facets);
parts.push(and.length === 1 ? and[0]! : { AND: and }); if (w) parts.push(w);
} }
return orParts(parts); return orParts(parts);
} }
@@ -384,28 +406,29 @@ export function projectsDeepWhere(
if (!sectionHasDataAccessLimits(section)) return {}; if (!sectionHasDataAccessLimits(section)) return {};
const parts: Prisma.ProjectCardWhereInput[] = []; const parts: Prisma.ProjectCardWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.ProjectCardWhereInput[] = []; const facets: Prisma.ProjectCardWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push({ facets.push({
OR: [ OR: [
{ ownerId: { in: ids } }, { ownerId: { in: ids } },
{ assignees: { some: { id: { in: ids } } } }, { assignees: { some: { id: { in: ids } } } },
], ],
}); });
} }
}
if (rule.boardIds?.length) { if (rule.boardIds?.length) {
and.push({ boardId: { in: rule.boardIds } }); facets.push({ boardId: { in: rule.boardIds } });
} }
if (rule.stageIds?.length) { if (rule.stageIds?.length) {
and.push({ stageId: { in: rule.stageIds } }); facets.push({ stageId: { in: rule.stageIds } });
} }
if (!and.length) continue; const w = unionFacets(facets);
parts.push(and.length === 1 ? and[0]! : { AND: and }); if (w) parts.push(w);
} }
return orParts(parts); return orParts(parts);
} }
@@ -418,20 +441,21 @@ export function routinesDeepWhere(
if (!sectionHasDataAccessLimits(section)) return {}; if (!sectionHasDataAccessLimits(section)) return {};
const parts: Prisma.RoutineTaskWhereInput[] = []; const parts: Prisma.RoutineTaskWhereInput[] = [];
for (const rule of section.rules ?? []) { for (const rule of section.rules ?? []) {
const and: Prisma.RoutineTaskWhereInput[] = []; const facets: Prisma.RoutineTaskWhereInput[] = [];
if (rule.owners?.length) { if (rule.owners?.length) {
const ids = ownerIdList(rule, { const ids = ownerIdList(rule, {
userId: actor.userId, userId: actor.userId,
teamPeerIds: actor.teamPeerIds ?? null, teamPeerIds: actor.teamPeerIds ?? null,
}); });
if (!ids.length) continue; if (ids.length) {
and.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } }); facets.push(ids.length === 1 ? { assigneeId: ids[0]! } : { assigneeId: { in: ids } });
}
} }
if (rule.typeIds?.length) { if (rule.typeIds?.length) {
and.push({ categoryId: { in: rule.typeIds } }); facets.push({ categoryId: { in: rule.typeIds } });
} }
if (!and.length) continue; const w = unionFacets(facets);
parts.push(and.length === 1 ? and[0]! : { AND: and }); if (w) parts.push(w);
} }
return orParts(parts); return orParts(parts);
} }
@@ -449,9 +473,14 @@ export function sectionOwnerIdUnion(
if (rule.owners?.length) { if (rule.owners?.length) {
sawOwnerRule = true; sawOwnerRule = true;
for (const id of ownerIdList(rule, ctx)) ids.add(id); for (const id of ownerIdList(rule, ctx)) ids.add(id);
} else if (rule.groupIds?.length || rule.sources?.length || rule.moods?.length || } else if (
rule.stageIds?.length || rule.pipelineIds?.length || rule.boardIds?.length || rule.sources?.length ||
rule.typeIds?.length) { rule.moods?.length ||
rule.stageIds?.length ||
rule.pipelineIds?.length ||
rule.boardIds?.length ||
rule.typeIds?.length
) {
sawNonOwnerRule = true; sawNonOwnerRule = true;
} }
} }
+68 -1
View File
@@ -21,15 +21,82 @@ function tehranJalaliLong(d: Date) {
return `${toFaDigits(j.jd)} ${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`; return `${toFaDigits(j.jd)} ${jalaliMonthName(j.jm)} ${toFaDigits(j.jy)}`;
} }
/** قالب بس/بد مثل UI ته‌حساب — برای توکن‌های مانده در پیامک */
export function formatSmsBedBes(v: unknown, maximumFractionDigits = 3): string {
if (v == null) return '';
const s = String(v).trim();
if (!s || s === 'null' || s === 'undefined' || s === 'NaN') return '';
const n = Number(s.replace(/,/g, ''));
if (!Number.isFinite(n)) return toFaDigits(s);
const abs = toFaDigits(
new Intl.NumberFormat('en-US', { maximumFractionDigits }).format(Math.abs(n)),
);
if (n === 0) return abs;
return `${abs} ${n < 0 ? 'بد' : 'بس'}`;
}
const METAL_FIELD_LABELS: Record<string, string> = {
MandeyeVazni: 'طلا',
MandeyeVazniNoghre: 'نقره',
MandeyeKolBeTALA: 'کل به طلا',
MandeMenhayeSeke: 'منهای سکه',
};
function isMetalMandehKey(key: string) {
if (METAL_FIELD_LABELS[key]) return true;
if (key.startsWith('Seke_')) return true;
return /Vazni|طلا|نقره|فلز|Gold|Silver/i.test(key);
}
function metalFieldLabel(key: string) {
if (METAL_FIELD_LABELS[key]) return METAL_FIELD_LABELS[key]!;
if (key.startsWith('Seke_')) return `سکه ${key.slice(5)}`;
return key;
}
/** از فیلدهای مانده ته‌حساب، متن مانده ریالی و فلزی می‌سازد */
export function smsBalanceTexts(input: {
mandehFields?: Array<{ key: string; value: string | null }> | null;
rialBalance?: number | null;
goldBalance?: number | null;
}): { rialBalance: string; metalBalance: string } {
const fields = input.mandehFields ?? [];
const mali = fields.find((f) => f.key === 'MandeyeMali' || f.key === 'MandeyeKolBePool');
const rial =
formatSmsBedBes(mali?.value ?? input.rialBalance) ||
formatSmsBedBes(input.rialBalance);
const metalParts = fields
.filter((f) => isMetalMandehKey(f.key) && f.value != null && String(f.value).trim() !== '')
.map((f) => `${metalFieldLabel(f.key)} ${formatSmsBedBes(f.value)}`.trim())
.filter(Boolean);
const metal =
metalParts.join('، ') ||
(input.goldBalance != null && formatSmsBedBes(input.goldBalance)
? `طلا ${formatSmsBedBes(input.goldBalance)}`
: '');
return { rialBalance: rial, metalBalance: metal };
}
export function renderSmsText( export function renderSmsText(
text: string, text: string,
vars: { name?: string; phone?: string; title?: string; company?: string }, vars: {
name?: string;
phone?: string;
title?: string;
company?: string;
from?: string;
rialBalance?: string;
metalBalance?: string;
},
) { ) {
return applyMessageTemplate(text, { return applyMessageTemplate(text, {
name: vars.name, name: vars.name,
phone: vars.phone, phone: vars.phone,
title: vars.title, title: vars.title,
company: vars.company, company: vars.company,
from: vars.from,
rialBalance: vars.rialBalance,
metalBalance: vars.metalBalance,
date: tehranJalaliLong(new Date()), date: tehranJalaliLong(new Date()),
}).trim(); }).trim();
} }
+1
View File
@@ -60,6 +60,7 @@ export function selectMonthBirthdays(people: BirthdayRow[], now = new Date(), pr
const upcoming = matched.filter((row) => row.day >= today.jd).sort(byDay); const upcoming = matched.filter((row) => row.day >= today.jd).sort(byDay);
const passed = matched.filter((row) => row.day < today.jd).sort(byDay); const passed = matched.filter((row) => row.day < today.jd).sort(byDay);
return { return {
year: today.jy,
month: today.jm, month: today.jm,
monthName: jalaliMonthName(today.jm), monthName: jalaliMonthName(today.jm),
today: today.jd, today: today.jd,
@@ -169,6 +169,7 @@ export class CompaniesService {
fromTahesab: Boolean(g.tahesabGid), fromTahesab: Boolean(g.tahesabGid),
personCount: 0, personCount: 0,
companyCount: countMap.get(g.id) ?? 0, companyCount: countMap.get(g.id) ?? 0,
assignees: [],
})); }));
} }
+2
View File
@@ -3,6 +3,7 @@ import { LoyaltyModule } from '../loyalty/loyalty.module';
import { AutomationsModule } from '../automations/automations.module'; import { AutomationsModule } from '../automations/automations.module';
import { MessageAutomationsModule } from '../message-automations/message-automations.module'; import { MessageAutomationsModule } from '../message-automations/message-automations.module';
import { PublicApiModule } from '../public-api/public-api.module'; import { PublicApiModule } from '../public-api/public-api.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { CompaniesController } from './companies.controller'; import { CompaniesController } from './companies.controller';
import { CompaniesService } from './companies.service'; import { CompaniesService } from './companies.service';
import { PeopleController } from './people.controller'; import { PeopleController } from './people.controller';
@@ -20,6 +21,7 @@ import { CustomerGroupsModule } from '../customer-groups/customer-groups.module'
PublicApiModule, PublicApiModule,
BehaviorModule, BehaviorModule,
CustomerGroupsModule, CustomerGroupsModule,
NotificationsModule,
], ],
controllers: [PeopleController, CompaniesController], controllers: [PeopleController, CompaniesController],
providers: [PeopleService, CompaniesService, ContactsExcelService, SameMobileMergeService], providers: [PeopleService, CompaniesService, ContactsExcelService, SameMobileMergeService],
+5
View File
@@ -23,6 +23,11 @@ export class BirthdaySmsDto {
@MinLength(1) @MinLength(1)
@MaxLength(500) @MaxLength(500)
text!: string; text!: string;
/** تأیید ارسال مجدد وقتی قبلاً مسئول دیگری تبریک فرستاده */
@IsOptional()
@IsBoolean()
force?: boolean;
} }
export class BulkDeletePeopleDto { export class BulkDeletePeopleDto {
+2 -1
View File
@@ -139,6 +139,7 @@ export class PeopleController {
} }
@Get('birthdays') @Get('birthdays')
@RequirePermission('customers', { reads: true })
birthdays(@CurrentUser() user: Actor) { birthdays(@CurrentUser() user: Actor) {
return this.peopleService.birthdaysThisMonth(user); return this.peopleService.birthdaysThisMonth(user);
} }
@@ -171,7 +172,7 @@ export class PeopleController {
@Param('id') id: string, @Param('id') id: string,
@Body() dto: BirthdaySmsDto, @Body() dto: BirthdaySmsDto,
) { ) {
return this.peopleService.sendBirthdaySms(user, id, dto.text); return this.peopleService.sendBirthdaySms(user, id, dto.text, Boolean(dto.force));
} }
@Get(':id') @Get(':id')
+190 -51
View File
@@ -22,6 +22,7 @@ import {
FILTERED_IDS_MAX, FILTERED_IDS_MAX,
PERSON_MOODS, PERSON_MOODS,
applyPersonGenderTitle, applyPersonGenderTitle,
canViewAllRecords,
splitPersonHonorific, splitPersonHonorific,
} from '@mento/shared'; } from '@mento/shared';
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
@@ -48,13 +49,15 @@ import {
import { actorCanAssignToOthers, assertAssigneeSet } from '../common/assign-access'; import { actorCanAssignToOthers, assertAssigneeSet } from '../common/assign-access';
import { LoyaltyService } from '../loyalty/loyalty.service'; import { LoyaltyService } from '../loyalty/loyalty.service';
import { AutomationsService } from '../automations/automations.service'; import { AutomationsService } from '../automations/automations.service';
import { NotificationsService } from '../notifications/notifications.service';
import { MessageAutomationsService } from '../message-automations/message-automations.service'; import { MessageAutomationsService } from '../message-automations/message-automations.service';
import { WebhooksService } from '../public-api/webhooks.service'; import { WebhooksService } from '../public-api/webhooks.service';
import { GamificationService } from '../gamification/gamification.service'; import { GamificationService } from '../gamification/gamification.service';
import { parseBirthDate } from '../common/excel'; import { parseBirthDate } from '../common/excel';
import { SmsGatewayService } from '../sms-billing/sms-gateway.service'; import { SmsGatewayService } from '../sms-billing/sms-gateway.service';
import { selectMonthBirthdays } from './birthday-month'; import { selectMonthBirthdays } from './birthday-month';
import { renderSmsText } from '../common/sms-text'; import { renderSmsText, smsBalanceTexts } from '../common/sms-text';
import { extractMandehRaw } from '../integrations/tahesab/tahesab-methods';
import { normalizeTags } from '../common/tags'; import { normalizeTags } from '../common/tags';
import { buildSearchWhere, ci, splitCsv } from '../common/search'; import { buildSearchWhere, ci, splitCsv } from '../common/search';
import { import {
@@ -157,6 +160,7 @@ export class PeopleService implements OnModuleInit {
private readonly outboundSms: OutboundSmsLogService, private readonly outboundSms: OutboundSmsLogService,
private readonly behaviorAccess: BehaviorAccessService, private readonly behaviorAccess: BehaviorAccessService,
private readonly groups: CustomerGroupsService, private readonly groups: CustomerGroupsService,
private readonly notifications: NotificationsService,
) {} ) {}
private personListWhere( private personListWhere(
@@ -216,15 +220,25 @@ export class PeopleService implements OnModuleInit {
} }
const disc = discFilter(opts?.disc); const disc = discFilter(opts?.disc);
if (disc) and.push(disc); if (disc) and.push(disc);
if (groupIds.length) and.push({ groupLinks: { some: { groupId: { in: groupIds } } } }); // گروه / منبع / حال: اتحاد (هر بُعد کافی است)؛ داخل هر بُعد چند مقدار با in = OR
const facets: Prisma.PersonWhereInput[] = [];
if (groupIds.length) {
facets.push({ groupLinks: { some: { groupId: { in: groupIds } } } });
}
if (moods.length) {
facets.push({ mood: { in: moods } });
}
if (sources.length) {
facets.push({ importSource: { in: sources } });
}
if (facets.length === 1) and.push(facets[0]!);
else if (facets.length > 1) and.push({ OR: facets });
return { return {
AND: [ AND: [
{ {
organizationId: actor.organizationId, organizationId: actor.organizationId,
...customersPersonWhere(actor), ...customersPersonWhere(actor),
}, },
...(moods.length ? [{ mood: { in: moods } }] : []),
...(sources.length ? [{ importSource: { in: sources } }] : []),
...and, ...and,
], ],
}; };
@@ -349,6 +363,7 @@ export class PeopleService implements OnModuleInit {
fromTahesab: Boolean(g.tahesabGid), fromTahesab: Boolean(g.tahesabGid),
personCount: countMap.get(g.id) ?? 0, personCount: countMap.get(g.id) ?? 0,
companyCount: 0, companyCount: 0,
assignees: [],
})); }));
} }
@@ -684,8 +699,8 @@ export class PeopleService implements OnModuleInit {
const rows = await this.prisma.person.findMany({ const rows = await this.prisma.person.findMany({
where: { where: {
organizationId: actor.organizationId, organizationId: actor.organizationId,
ownerId: actor.userId,
birthDate: { not: null }, birthDate: { not: null },
...customersPersonWhere(actor),
}, },
select: { select: {
id: true, id: true,
@@ -732,27 +747,50 @@ export class PeopleService implements OnModuleInit {
}; };
} }
async sendBirthdaySms(actor: Actor, personId: string, text: string) { async sendBirthdaySms(actor: Actor, personId: string, text: string, force = false) {
const body = text.trim(); const body = text.trim();
if (!body || body.length > 500) { if (!body || body.length > 500) {
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.'); throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.');
} }
const person = await this.prisma.person.findFirst({ const person = await this.prisma.person.findFirst({
where: { id: personId, organizationId: actor.organizationId }, where: {
id: personId,
organizationId: actor.organizationId,
...customersPersonWhere(actor),
},
select: { select: {
id: true, id: true,
firstName: true, firstName: true,
lastName: true, lastName: true,
mobile: true, mobile: true,
phone: true, phone: true,
position: true,
ownerId: true, ownerId: true,
birthDate: true, birthDate: true,
company: { select: { name: true } }, company: { select: { name: true } },
groupLinks: {
select: {
group: {
select: {
assignees: { select: { id: true, fullName: true } },
},
},
},
},
}, },
}); });
if (!person) throw new NotFoundException('مشتری پیدا نشد'); if (!person) throw new NotFoundException('مشتری پیدا نشد');
if (person.ownerId !== actor.userId) { const assigneeIds = new Set(
throw new ForbiddenException('فقط مسئول این مشتری می‌تواند پیامک تبریک بفرستد.'); person.groupLinks.flatMap((link) => link.group.assignees.map((a) => a.id)),
);
const canSend =
canViewAllRecords(actor.role) ||
person.ownerId === actor.userId ||
assigneeIds.has(actor.userId);
if (!canSend) {
throw new ForbiddenException(
'فقط مالک مشتری یا مسئول گروه او می‌تواند پیامک تبریک بفرستد.',
);
} }
if (!person.birthDate) { if (!person.birthDate) {
throw new BadRequestException('برای این مشتری تاریخ تولد ثبت نشده است.'); throw new BadRequestException('برای این مشتری تاریخ تولد ثبت نشده است.');
@@ -774,12 +812,110 @@ export class PeopleService implements OnModuleInit {
const mobile = person.mobile || person.phone; const mobile = person.mobile || person.phone;
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.'); if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
const fullName = `${person.firstName} ${person.lastName}`.trim(); const fullName = `${person.firstName} ${person.lastName}`.trim();
const message = renderSmsText(body, { const birthdayKey = `birthday:${inMonth.year}-${inMonth.month}`;
if (!force) {
const prior = await this.prisma.outboundSmsLog.findFirst({
where: {
organizationId: actor.organizationId,
personId: person.id,
status: 'sent',
sourceId: birthdayKey,
NOT: { actorUserId: actor.userId },
},
orderBy: { createdAt: 'desc' },
select: { actorUserId: true },
});
if (prior) {
const priorUser = prior.actorUserId
? await this.prisma.user.findFirst({
where: { id: prior.actorUserId },
select: { fullName: true },
})
: null;
const who = priorUser?.fullName?.trim() || 'مسئول دیگری';
throw new ConflictException(
`${who} قبلاً پیامک تبریک این مشتری را فرستاده است. آیا می‌خواهید دوباره بفرستید؟`,
);
}
}
const message = renderSmsText(
body,
await this.personSmsVars(actor.organizationId, person.id, {
name: fullName, name: fullName,
phone: mobile, phone: mobile,
title: fullName, title: person.position?.trim() || '',
company: person.company?.name ?? '', company: person.company?.name ?? '',
}),
);
if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({
organizationId: actor.organizationId,
phone: mobile,
text: message,
source: 'manual',
}); });
await this.outboundSms.record({
organizationId: actor.organizationId,
personId: person.id,
mobile,
body: message,
source: 'manual',
sourceId: birthdayKey,
status: result.ok ? 'sent' : 'failed',
error: result.ok ? null : result.reason,
actorUserId: actor.userId,
});
if (!result.ok) {
throw new ServiceUnavailableException(
result.blocked
? 'ارسال پیامک به‌خاطر محدودیت اعتبار مسدود است.'
: result.reason === 'SMS not configured'
? 'ارسال پیامک روی سرور فعال نیست.'
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
);
}
const senderName = (
await this.prisma.user.findFirst({
where: { id: actor.userId },
select: { fullName: true },
})
)?.fullName?.trim() || 'یکی از مسئولان';
const peers = [...assigneeIds].filter((id) => id !== actor.userId);
await Promise.all(
peers.map((userId) =>
this.notifications.create({
organizationId: actor.organizationId,
userId,
type: 'birthday_sms_sent',
title: 'پیامک تبریک تولد ارسال شد',
body: `${senderName} برای «${fullName}» پیامک تبریک فرستاد. اگر لازم است می‌توانید دوباره بفرستید.`,
link: `/contacts/people/${person.id}`,
entityType: 'person',
entityId: person.id,
dedupe: false,
}),
),
);
return { ok: true };
}
async sendSms(actor: Actor, personId: string, text: string) {
const body = text.trim();
if (!body || body.length > 500) {
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.');
}
const person = await this.get(actor, personId);
const mobile = person.mobile || person.phone;
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.');
const message = renderSmsText(
body,
await this.personSmsVars(actor.organizationId, person.id, {
name: person.fullName,
phone: mobile,
title: person.position?.trim() || '',
company: person.company?.name ?? '',
}),
);
if (!message) throw new BadRequestException('متن پیامک خالی است.'); if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({ const result = await this.sms.send({
organizationId: actor.organizationId, organizationId: actor.organizationId,
@@ -809,47 +945,50 @@ export class PeopleService implements OnModuleInit {
return { ok: true }; return { ok: true };
} }
async sendSms(actor: Actor, personId: string, text: string) { /** نام سازمان + مانده‌های کش‌شدهٔ ته‌حساب برای توکن‌های پیامک */
const body = text.trim(); private async personSmsVars(
if (!body || body.length > 500) { organizationId: string,
throw new BadRequestException('متن پیامک را تا ۵۰۰ نویسه بنویسید.'); personId: string,
base: {
name: string;
phone: string;
title: string;
company: string;
},
) {
const [org, link] = await Promise.all([
this.prisma.organization.findUnique({
where: { id: organizationId },
select: { name: true },
}),
this.prisma.personAccountingLink.findFirst({
where: { personId, connection: { organizationId } },
orderBy: [
{ connection: { isDefault: 'desc' } },
{ linkedAt: 'desc' },
],
include: { balanceCache: true },
}),
]);
let rialBalance = '';
let metalBalance = '';
const cache = link?.balanceCache;
if (cache) {
const rawView = extractMandehRaw(cache.rawResponse);
const bal = smsBalanceTexts({
mandehFields: rawView.fields,
rialBalance: cache.rialBalance,
goldBalance: cache.goldBalance,
});
rialBalance = bal.rialBalance;
metalBalance = bal.metalBalance;
} }
const person = await this.get(actor, personId); return {
const mobile = person.mobile || person.phone; ...base,
if (!mobile) throw new BadRequestException('برای این مشتری شماره موبایل ثبت نشده است.'); from: org?.name?.trim() || '',
const message = renderSmsText(body, { rialBalance,
name: person.fullName, metalBalance,
phone: mobile, };
title: person.fullName,
company: person.company?.name ?? '',
});
if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({
organizationId: actor.organizationId,
phone: mobile,
text: message,
source: 'manual',
});
await this.outboundSms.record({
organizationId: actor.organizationId,
personId: person.id,
mobile,
body: message,
source: 'manual',
status: result.ok ? 'sent' : 'failed',
error: result.ok ? null : result.reason,
actorUserId: actor.userId,
});
if (!result.ok) {
throw new ServiceUnavailableException(
result.blocked
? 'ارسال پیامک به‌خاطر محدودیت اعتبار مسدود است.'
: result.reason === 'SMS not configured'
? 'ارسال پیامک روی سرور فعال نیست.'
: 'پیامک ارسال نشد. کمی بعد دوباره تلاش کنید.',
);
}
return { ok: true };
} }
listSmsHistory(actor: Actor, personId: string, limit?: number) { listSmsHistory(actor: Actor, personId: string, limit?: number) {
@@ -8,7 +8,14 @@ import {
Post, Post,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { IsIn, IsOptional, IsString, MaxLength, MinLength } from 'class-validator'; import {
IsArray,
IsIn,
IsOptional,
IsString,
MaxLength,
MinLength,
} from 'class-validator';
import { CUSTOMER_GROUP_COLORS, type CustomerGroupColor } from '@mento/shared'; import { CUSTOMER_GROUP_COLORS, type CustomerGroupColor } from '@mento/shared';
import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard'; import { RolesGuard } from '../auth/roles.guard';
@@ -26,6 +33,11 @@ class CreateCustomerGroupDto {
@IsOptional() @IsOptional()
@IsIn([...CUSTOMER_GROUP_COLORS]) @IsIn([...CUSTOMER_GROUP_COLORS])
color?: CustomerGroupColor; color?: CustomerGroupColor;
@IsOptional()
@IsArray()
@IsString({ each: true })
assigneeIds?: string[];
} }
class UpdateCustomerGroupDto { class UpdateCustomerGroupDto {
@@ -43,6 +55,11 @@ class UpdateCustomerGroupDto {
@IsOptional() @IsOptional()
@IsString() @IsString()
parentId?: string | null; parentId?: string | null;
@IsOptional()
@IsArray()
@IsString({ each: true })
assigneeIds?: string[];
} }
@Controller('customer-groups') @Controller('customer-groups')
@@ -51,26 +51,21 @@ export class CustomerGroupsService {
include: { include: {
_count: { select: { people: true, companies: true } }, _count: { select: { people: true, companies: true } },
parent: { select: { name: true } }, parent: { select: { name: true } },
assignees: { select: { id: true, fullName: true }, orderBy: { fullName: 'asc' } },
}, },
}); });
return rows.map((r) => ({ return rows.map((r) => this.toDto(r));
id: r.id,
name: r.name,
color: r.color,
position: r.position,
fromTahesab: Boolean(r.tahesabGid),
personCount: r._count.people,
companyCount: r._count.companies,
parentId: r.parentId,
parentName: r.parent?.name ?? null,
}));
} }
async create( async create(
organizationId: string, organizationId: string,
dto: { name: string; color?: CustomerGroupColor }, dto: { name: string; color?: CustomerGroupColor; assigneeIds?: string[] },
): Promise<CustomerGroupDto> { ): Promise<CustomerGroupDto> {
const name = this.cleanName(dto.name); const name = this.cleanName(dto.name);
const assigneeIds =
dto.assigneeIds !== undefined
? await this.validAssigneeIds(organizationId, dto.assigneeIds)
: [];
const max = await this.prisma.customerGroup.aggregate({ const max = await this.prisma.customerGroup.aggregate({
where: { organizationId }, where: { organizationId },
_max: { position: true }, _max: { position: true },
@@ -82,6 +77,9 @@ export class CustomerGroupsService {
name, name,
color: this.cleanColor(dto.color), color: this.cleanColor(dto.color),
position: (max._max.position ?? -1) + 1, position: (max._max.position ?? -1) + 1,
...(assigneeIds.length
? { assignees: { connect: assigneeIds.map((id) => ({ id })) } }
: {}),
}, },
}); });
} catch (e) { } catch (e) {
@@ -93,7 +91,12 @@ export class CustomerGroupsService {
async update( async update(
organizationId: string, organizationId: string,
id: string, id: string,
dto: { name?: string; color?: CustomerGroupColor; parentId?: string | null }, dto: {
name?: string;
color?: CustomerGroupColor;
parentId?: string | null;
assigneeIds?: string[];
},
): Promise<CustomerGroupDto> { ): Promise<CustomerGroupDto> {
await this.require(organizationId, id); await this.require(organizationId, id);
const parentId = const parentId =
@@ -101,6 +104,10 @@ export class CustomerGroupsService {
if (parentId !== undefined) { if (parentId !== undefined) {
await this.assertParent(organizationId, id, parentId); await this.assertParent(organizationId, id, parentId);
} }
const assigneeIds =
dto.assigneeIds !== undefined
? await this.validAssigneeIds(organizationId, dto.assigneeIds)
: undefined;
try { try {
await this.prisma.customerGroup.update({ await this.prisma.customerGroup.update({
where: { id }, where: { id },
@@ -108,6 +115,9 @@ export class CustomerGroupsService {
...(dto.name != null ? { name: this.cleanName(dto.name) } : {}), ...(dto.name != null ? { name: this.cleanName(dto.name) } : {}),
...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}), ...(dto.color != null ? { color: this.cleanColor(dto.color) } : {}),
...(parentId !== undefined ? { parentId } : {}), ...(parentId !== undefined ? { parentId } : {}),
...(assigneeIds !== undefined
? { assignees: { set: assigneeIds.map((uid) => ({ id: uid })) } }
: {}),
}, },
}); });
} catch (e) { } catch (e) {
@@ -317,6 +327,48 @@ export class CustomerGroupsService {
return link?.group.name ?? null; return link?.group.name ?? null;
} }
private toDto(r: {
id: string;
name: string;
color: string;
position: number;
tahesabGid: string | null;
parentId: string | null;
parent?: { name: string } | null;
_count: { people: number; companies: number };
assignees: Array<{ id: string; fullName: string }>;
}): CustomerGroupDto {
return {
id: r.id,
name: r.name,
color: r.color,
position: r.position,
fromTahesab: Boolean(r.tahesabGid),
personCount: r._count.people,
companyCount: r._count.companies,
parentId: r.parentId,
parentName: r.parent?.name ?? null,
assignees: r.assignees.map((a) => ({ id: a.id, fullName: a.fullName })),
};
}
private async validAssigneeIds(organizationId: string, ids: string[]): Promise<string[]> {
const unique = [...new Set((ids ?? []).map((id) => id?.trim()).filter(Boolean))];
if (!unique.length) return [];
const rows = await this.prisma.user.findMany({
where: {
id: { in: unique },
isActive: true,
memberships: { some: { organizationId, isActive: true } },
},
select: { id: true },
});
if (rows.length !== unique.length) {
throw new BadRequestException('یکی از مسئولان انتخاب‌شده معتبر نیست');
}
return rows.map((r) => r.id);
}
private async require(organizationId: string, id: string) { private async require(organizationId: string, id: string) {
const row = await this.prisma.customerGroup.findFirst({ const row = await this.prisma.customerGroup.findFirst({
where: { id, organizationId }, where: { id, organizationId },
@@ -1,4 +1,11 @@
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'; import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
import {
pickAddress,
pickCity,
pickNationalId,
pickRasteh,
tahesabProfilePatch,
} from '../moshtari-profile';
import { import {
assertFactorCode, assertFactorCode,
buildFactorCode, buildFactorCode,
@@ -116,12 +123,52 @@ function testSanadBuilders() {
assert(bank[12] === fc, 'bank factor index'); assert(bank[12] === fc, 'bank factor index');
} }
function testMoshtariProfile() {
const row = {
CodeMelli: '00112312311',
Address: 'خیابان ولیعصر',
City: 'تهران',
Rasteh: 2,
BDate: null,
};
assert(pickNationalId(row) === '00112312311', 'national id');
assert(pickAddress(row) === 'خیابان ولیعصر', 'address');
assert(pickCity(row) === 'تهران', 'city');
assert(pickRasteh(row) === 2, 'rasteh');
assert(pickNationalId({ CodeMelli: '-1' }) == null, 'skip -1 national');
const patch = tahesabProfilePatch(row, {
birthDate: null,
addresses: [],
customFields: { keep: true },
});
assert(Array.isArray(patch.addresses) && patch.addresses[0] === 'خیابان ولیعصر، تهران', 'addr+city');
const fields = patch.customFields as Record<string, unknown>;
assert(fields.nationalId === '00112312311', 'cf national');
assert(fields.city === 'تهران', 'cf city');
assert(fields.rasteh === 2, 'cf rasteh');
assert(fields.keep === true, 'cf merge');
const emptyKeep = tahesabProfilePatch(
{ CodeMelli: '', Address: '', City: '', Rasteh: '' },
{
birthDate: new Date('2000-01-01'),
addresses: ['قدیمی'],
customFields: { nationalId: '111' },
},
);
assert(emptyKeep.addresses == null, 'empty does not wipe address');
assert(emptyKeep.customFields == null, 'empty does not wipe custom');
assert(emptyKeep.birthDate == null, 'existing birth kept');
}
function main() { function main() {
testCryptoRoundtrip(); testCryptoRoundtrip();
testFactorCode(); testFactorCode();
testMobile(); testMobile();
testMandehNormalize(); testMandehNormalize();
testSanadBuilders(); testSanadBuilders();
testMoshtariProfile();
console.log('tahesab unit checks: OK'); console.log('tahesab unit checks: OK');
} }
+6
View File
@@ -205,6 +205,12 @@ export class SyncGroupsPageDto {
pageSize?: number; pageSize?: number;
} }
/** اجرای دستی همگام‌سازی همهٔ مشتریان (وارد + به‌روز کردن لینک‌شده‌ها) */
export class SyncAllCustomersDto {
@IsString()
connectionId!: string;
}
export class ExportPeopleToTahesabDto { export class ExportPeopleToTahesabDto {
@IsString() @IsString()
connectionId!: string; connectionId!: string;
@@ -0,0 +1,113 @@
import { Prisma } from '@prisma/client';
import { parseBirthDate } from '../../common/excel';
export function pickBirthDate(row: Record<string, unknown>): Date | null {
const raw =
row.BDate ??
row.bDate ??
row.Tarikh_Tavalod ??
row.tarikh_tavalod ??
row.BirthDate;
if (raw == null) return null;
return parseBirthDate(String(raw));
}
function trimStr(raw: unknown): string | null {
if (raw == null) return null;
const s = String(raw).trim();
if (!s || s === '-1') return null;
return s;
}
/** کد ملی از پاسخ لیست مشتری ته‌حساب */
export function pickNationalId(row: Record<string, unknown>): string | null {
return (
trimStr(row.CodeMelli) ??
trimStr(row.CodeMeli) ??
trimStr(row.codeMeli) ??
trimStr(row.NationalId) ??
null
);
}
export function pickAddress(row: Record<string, unknown>): string | null {
return trimStr(row.Address) ?? trimStr(row.address) ?? null;
}
export function pickCity(row: Record<string, unknown>): string | null {
return trimStr(row.City) ?? trimStr(row.city) ?? trimStr(row.Shahr) ?? null;
}
/** رسته حساب در ته‌حساب (عدد یا رشته) */
export function pickRasteh(row: Record<string, unknown>): string | number | null {
const raw = row.Rasteh ?? row.rasteh ?? row.Raste;
if (raw == null || raw === '') return null;
if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
const s = String(raw).trim();
if (!s || s === '-1') return null;
const n = Number(s);
return Number.isFinite(n) && String(n) === s ? n : s;
}
function asCustomFieldRecord(raw: unknown): Record<string, unknown> {
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
return { ...(raw as Record<string, unknown>) };
}
return {};
}
function asAddressList(raw: unknown): string[] {
if (!Array.isArray(raw)) return [];
return raw
.map((a) => (typeof a === 'string' ? a.trim() : ''))
.filter(Boolean);
}
/**
* فیلدهای پروفایل قابل‌دریافت از DoListMoshtari را روی شخص می‌نشاند.
* مقدار خالی ته‌حساب، دادهٔ موجود CRM را پاک نمی‌کند.
*/
export function tahesabProfilePatch(
row: Record<string, unknown>,
existing: {
birthDate: Date | null;
addresses: unknown;
customFields: unknown;
},
): Prisma.PersonUpdateInput {
const data: Prisma.PersonUpdateInput = {};
const birthDate = pickBirthDate(row);
if (!existing.birthDate && birthDate) data.birthDate = birthDate;
const address = pickAddress(row);
const city = pickCity(row);
if (address) {
const line = city ? `${address}، ${city}` : address;
data.addresses = [line] as Prisma.InputJsonValue;
} else if (city && asAddressList(existing.addresses).length === 0) {
data.addresses = [city] as Prisma.InputJsonValue;
}
const fields = asCustomFieldRecord(existing.customFields);
let fieldsChanged = false;
const nationalId = pickNationalId(row);
if (nationalId) {
fields.nationalId = nationalId;
fieldsChanged = true;
}
if (city) {
fields.city = city;
fieldsChanged = true;
}
if (address) {
fields.address = address;
fieldsChanged = true;
}
const rasteh = pickRasteh(row);
if (rasteh != null) {
fields.rasteh = rasteh;
fieldsChanged = true;
}
if (fieldsChanged) data.customFields = fields as Prisma.InputJsonValue;
return data;
}
@@ -26,8 +26,9 @@ import {
SearchTahesabDto, SearchTahesabDto,
SyncGroupsPageDto, SyncGroupsPageDto,
} from './dto'; } from './dto';
import { formatJalaliDate, parseBirthDate } from '../../common/excel'; import { formatJalaliDate } from '../../common/excel';
import { CustomerGroupsService } from '../../customer-groups/customer-groups.service'; import { CustomerGroupsService } from '../../customer-groups/customer-groups.service';
import { pickBirthDate, tahesabProfilePatch } from './moshtari-profile';
import { normalizeIranMobile, SanadBuilders, type TahesabApi } from './tahesab-methods'; import { normalizeIranMobile, SanadBuilders, type TahesabApi } from './tahesab-methods';
/** موبایل ته‌حساب را به شکل 0912… ذخیره می‌کند، حتی اگر قبلاً 912… یا +98912… بوده باشد. */ /** موبایل ته‌حساب را به شکل 0912… ذخیره می‌کند، حتی اگر قبلاً 912… یا +98912… بوده باشد. */
@@ -83,17 +84,6 @@ function pickTel(row: Record<string, unknown>): string {
return String(row.Tel ?? row.Phone ?? row.Mobile ?? row.tel ?? ''); return String(row.Tel ?? row.Phone ?? row.Mobile ?? row.tel ?? '');
} }
function pickBirthDate(row: Record<string, unknown>): Date | null {
const raw =
row.BDate ??
row.bDate ??
row.Tarikh_Tavalod ??
row.tarikh_tavalod ??
row.BirthDate;
if (raw == null) return null;
return parseBirthDate(String(raw));
}
function firstAddress(raw: unknown): string | undefined { function firstAddress(raw: unknown): string | undefined {
if (!Array.isArray(raw)) return undefined; if (!Array.isArray(raw)) return undefined;
const first = raw.find((a) => typeof a === 'string' && a.trim()); const first = raw.find((a) => typeof a === 'string' && a.trim());
@@ -710,8 +700,8 @@ export class TahesabPersonLinkService {
...carryPreviousSource(existing, 'tahesab'), ...carryPreviousSource(existing, 'tahesab'),
importSource: 'tahesab', importSource: 'tahesab',
sourceRef, sourceRef,
...(!existing.birthDate && pickBirthDate(row) ? { birthDate: pickBirthDate(row) } : {}),
...canonicalMobileUpdate(mobile, existing), ...canonicalMobileUpdate(mobile, existing),
...tahesabProfilePatch(row, existing),
}, },
}); });
} else { } else {
@@ -772,12 +762,17 @@ export class TahesabPersonLinkService {
...carryPreviousSource(byMobile, 'tahesab'), ...carryPreviousSource(byMobile, 'tahesab'),
importSource: 'tahesab', importSource: 'tahesab',
sourceRef, sourceRef,
...(!byMobile.birthDate && pickBirthDate(row) ? { birthDate: pickBirthDate(row) } : {}),
...canonicalMobileUpdate(mobile, byMobile), ...canonicalMobileUpdate(mobile, byMobile),
...tahesabProfilePatch(row, byMobile),
}, },
}); });
personId = byMobile.id; personId = byMobile.id;
} else { } else {
const profile = tahesabProfilePatch(row, {
birthDate: null,
addresses: [],
customFields: {},
});
const created = await this.prisma.person.create({ const created = await this.prisma.person.create({
data: { data: {
organizationId, organizationId,
@@ -790,7 +785,9 @@ export class TahesabPersonLinkService {
notes: `واردشده از ته‌حساب (کد ${dto.moshtariCode})`, notes: `واردشده از ته‌حساب (کد ${dto.moshtariCode})`,
importSource: 'tahesab', importSource: 'tahesab',
sourceRef, sourceRef,
birthDate: pickBirthDate(row), birthDate: (profile.birthDate as Date | undefined) ?? null,
addresses: (profile.addresses as Prisma.InputJsonValue) ?? [],
customFields: (profile.customFields as Prisma.InputJsonValue) ?? {},
}, },
}); });
personId = created.id; personId = created.id;
@@ -837,7 +834,7 @@ export class TahesabPersonLinkService {
return { personId, link: this.linkDto(link) }; return { personId, link: this.linkDto(link) };
} }
/** نام، موبایل و گروه مشتریِ از قبل لینک‌شده را با ردیف ته‌حساب تازه می‌کند. */ /** پروفایل و گروه مشتریِ از قبل لینک‌شده را با ردیف ته‌حساب تازه می‌کند. */
private async refreshLinkedCustomer( private async refreshLinkedCustomer(
organizationId: string, organizationId: string,
connectionId: string, connectionId: string,
@@ -878,10 +875,8 @@ export class TahesabPersonLinkService {
...carryPreviousSource(existing, 'tahesab'), ...carryPreviousSource(existing, 'tahesab'),
importSource: 'tahesab', importSource: 'tahesab',
sourceRef: String(moshtariCode), sourceRef: String(moshtariCode),
...(!existing.birthDate && pickBirthDate(row)
? { birthDate: pickBirthDate(row) }
: {}),
...canonicalMobileUpdate(storedPhoneNumber(pickTel(row)), existing), ...canonicalMobileUpdate(storedPhoneNumber(pickTel(row)), existing),
...tahesabProfilePatch(row, existing),
}, },
}); });
await this.applyTahesabGroup(organizationId, connectionId, personId, row); await this.applyTahesabGroup(organizationId, connectionId, personId, row);
@@ -974,6 +969,7 @@ export class TahesabPersonLinkService {
...(duplicate ? [`${duplicate} شماره تکراری`] : []), ...(duplicate ? [`${duplicate} شماره تکراری`] : []),
`${failed} خطا`, `${failed} خطا`,
].join('، '); ].join('، ');
const error = errors.length ? errors.join('؛ ') : null;
await this.prisma.accountingSyncJob.create({ await this.prisma.accountingSyncJob.create({
data: { data: {
organizationId, organizationId,
@@ -983,6 +979,14 @@ export class TahesabPersonLinkService {
result: { imported, updated, duplicate, failed, pages: page - 1 } as Prisma.InputJsonValue, result: { imported, updated, duplicate, failed, pages: page - 1 } as Prisma.InputJsonValue,
}, },
}); });
await this.prisma.accountingConnection.update({
where: { id: connectionId },
data: {
customerSyncLastRunAt: new Date(),
customerSyncLastSummary: summary,
customerSyncLastError: error,
},
});
this.logger.log(`همگام‌سازی مشتریان ته‌حساب ${connectionId}: ${summary}`); this.logger.log(`همگام‌سازی مشتریان ته‌حساب ${connectionId}: ${summary}`);
return { return {
imported, imported,
@@ -990,7 +994,7 @@ export class TahesabPersonLinkService {
duplicate, duplicate,
failed, failed,
summary, summary,
error: errors.length ? errors.join('؛ ') : null, error,
}; };
} }
@@ -1086,19 +1090,16 @@ export class TahesabPersonLinkService {
try { try {
const linkedPersonId = linkedByCode.get(moshtariCode); const linkedPersonId = linkedByCode.get(moshtariCode);
if (linkedPersonId) { if (linkedPersonId) {
const birthDate = pickBirthDate(rowsByCode.get(moshtariCode) ?? {}); const row = rowsByCode.get(moshtariCode);
if (birthDate) { if (row) {
await this.prisma.person.updateMany({ await this.refreshLinkedCustomer(
where: { id: linkedPersonId, birthDate: null },
data: { birthDate },
});
}
await this.applyTahesabGroup(
organizationId, organizationId,
dto.connectionId, dto.connectionId,
linkedPersonId, linkedPersonId,
rowsByCode.get(moshtariCode), moshtariCode,
row,
); );
}
items.push({ items.push({
moshtariCode, moshtariCode,
ok: true, ok: true,
@@ -37,6 +37,7 @@ import {
SearchTahesabDto, SearchTahesabDto,
SearchTahesabProductsDto, SearchTahesabProductsDto,
SyncAsnadReportDto, SyncAsnadReportDto,
SyncAllCustomersDto,
SyncGroupsPageDto, SyncGroupsPageDto,
UpdateTahesabConnectionDto, UpdateTahesabConnectionDto,
UpdateTahesabInvoiceSettingsDto, UpdateTahesabInvoiceSettingsDto,
@@ -237,6 +238,16 @@ export class TahesabController {
return this.links.syncGroupsPage(user.organizationId, dto); return this.links.syncGroupsPage(user.organizationId, dto);
} }
/** همهٔ مشتریان ته‌حساب: تازه‌ها وارد، لینک‌شده‌ها (نام/موبایل/کدملی/آدرس/شهر/رسته/گروه) به‌روز */
@Post('sync/customers-now')
@Roles('owner', 'admin')
syncCustomersNow(
@CurrentUser() user: { organizationId: string },
@Body() dto: SyncAllCustomersDto,
) {
return this.links.syncAllCustomers(user.organizationId, dto.connectionId);
}
@Get('sync/unlinked-people') @Get('sync/unlinked-people')
@Roles('owner', 'admin') @Roles('owner', 'admin')
unlinkedPeople( unlinkedPeople(
+6 -1
View File
@@ -1572,11 +1572,16 @@ export class LeadsService {
const mobile = lead.mobile || lead.phone; const mobile = lead.mobile || lead.phone;
if (!mobile) throw new BadRequestException('برای این لید شماره موبایل ثبت نشده است.'); if (!mobile) throw new BadRequestException('برای این لید شماره موبایل ثبت نشده است.');
const name = (lead.contactName || lead.title).trim(); const name = (lead.contactName || lead.title).trim();
const org = await this.prisma.organization.findUnique({
where: { id: actor.organizationId },
select: { name: true },
});
const message = renderSmsText(body, { const message = renderSmsText(body, {
name, name,
phone: mobile, phone: mobile,
title: lead.title, title: lead.title,
company: lead.contactName ? lead.title : '', company: lead.trade?.trim() || '',
from: org?.name?.trim() || '',
}); });
if (!message) throw new BadRequestException('متن پیامک خالی است.'); if (!message) throw new BadRequestException('متن پیامک خالی است.');
const result = await this.sms.send({ const result = await this.sms.send({
@@ -56,7 +56,19 @@ function testTemplate() {
}) === 'سلام علی 0912', }) === 'سلام علی 0912',
'name phone vars', 'name phone vars',
); );
assert(clipSms('الف'.repeat(200)).length === 200, 'sms is not clipped'); assert(
applyMessageTemplate('تبریک {از طرف}', { from: 'هنراندیشه' }) ===
'تبریک هنراندیشه',
'from org var',
);
assert(
applyMessageTemplate('مانده {مانده ریالی} / {مانده فلزی}', {
rialBalance: '۱۰۰۰ بس',
metalBalance: 'طلا ۲',
}) === 'مانده ۱۰۰۰ بس / طلا ۲',
'balance vars',
);
assert(clipSms('ا'.repeat(200)).length === 200, 'sms is not clipped');
} }
testDelay(); testDelay();
@@ -77,6 +77,17 @@ export function buildSendAts(
return times; return times;
} }
/** یکسان‌سازی کلید توکن‌های قالب (فاصله/ZWNJ/ی عربی). */
export function normalizeTemplateKey(key: string): string {
return String(key ?? '')
.normalize('NFKC')
.replace(/[\u200c\u200d\u200e\u200f\ufeff]/g, '')
.replace(/ي/g, 'ی')
.replace(/ك/g, 'ک')
.replace(/\s+/g, ' ')
.trim();
}
export function applyMessageTemplate( export function applyMessageTemplate(
text: string, text: string,
vars: { vars: {
@@ -85,22 +96,44 @@ export function applyMessageTemplate(
phone?: string; phone?: string;
date?: string; date?: string;
company?: string; company?: string;
/** نام سازمان فرستنده */
from?: string;
/** مانده مالی قالب‌بندی‌شده */
rialBalance?: string;
/** مانده‌های وزنی/فلزی قالب‌بندی‌شده */
metalBalance?: string;
}, },
): string { ): string {
const map: Record<string, string> = { const from = vars.from ?? '';
title: vars.title ?? '', const rial = vars.rialBalance ?? '';
عنوان: vars.title ?? '', const metal = vars.metalBalance ?? '';
نام: vars.name ?? '', const entries: Array<[string, string]> = [
name: vars.name ?? '', ['title', vars.title ?? ''],
شماره: vars.phone ?? '', ['عنوان', vars.title ?? ''],
phone: vars.phone ?? '', ['نام', vars.name ?? ''],
تاریخ: vars.date ?? '', ['name', vars.name ?? ''],
date: vars.date ?? '', ['شماره', vars.phone ?? ''],
شرکت: vars.company ?? '', ['phone', vars.phone ?? ''],
company: vars.company ?? '', ['تاریخ', vars.date ?? ''],
}; ['date', vars.date ?? ''],
['شرکت', vars.company ?? ''],
['company', vars.company ?? ''],
['از طرف', from],
['ازطرف', from],
['from', from],
['مانده ریالی', rial],
['ماندهریالی', rial],
['rialBalance', rial],
['مانده فلزی', metal],
['ماندهفلزی', metal],
['metalBalance', metal],
];
const map: Record<string, string> = {};
for (const [key, value] of entries) {
map[normalizeTemplateKey(key)] = value;
}
return text.replace(/\{([^}]+)\}/g, (full, key: string) => { return text.replace(/\{([^}]+)\}/g, (full, key: string) => {
const next = map[key.trim()]; const next = map[normalizeTemplateKey(key)];
return next === undefined ? full : next; return next === undefined ? full : next;
}); });
} }
@@ -356,6 +356,10 @@ export class MessageAutomationsService {
}) })
: null; : null;
const lead = await this.lookupLead(job); const lead = await this.lookupLead(job);
const org = await this.prisma.organization.findUnique({
where: { id: job.organizationId },
select: { name: true },
});
const personName = person const personName = person
? [person.firstName, person.lastName].filter(Boolean).join(' ').trim() ? [person.firstName, person.lastName].filter(Boolean).join(' ').trim()
: ''; : '';
@@ -366,6 +370,7 @@ export class MessageAutomationsService {
phone, phone,
date: formatJalaliDayFa(new Date()), date: formatJalaliDayFa(new Date()),
company: person?.company?.name ?? '', company: person?.company?.name ?? '',
from: org?.name?.trim() || '',
}; };
const title = applyMessageTemplate(job.rule.title, vars).slice(0, 200); const title = applyMessageTemplate(job.rule.title, vars).slice(0, 200);
const body = applyMessageTemplate(job.rule.body, vars); const body = applyMessageTemplate(job.rule.body, vars);
@@ -1,9 +1,12 @@
import { Global, Module } from '@nestjs/common'; import { Global, Module } from '@nestjs/common';
import { OutboundSmsLogService } from './outbound-sms-log.service'; import { OutboundSmsLogService } from './outbound-sms-log.service';
import { SmsTemplatesController } from './sms-templates.controller';
import { SmsTemplatesService } from './sms-templates.service';
@Global() @Global()
@Module({ @Module({
providers: [OutboundSmsLogService], controllers: [SmsTemplatesController],
exports: [OutboundSmsLogService], providers: [OutboundSmsLogService, SmsTemplatesService],
exports: [OutboundSmsLogService, SmsTemplatesService],
}) })
export class OutboundSmsModule {} export class OutboundSmsModule {}
@@ -0,0 +1,48 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import type { Actor } from '../common/record-scope';
import {
CreateSmsTemplateDto,
UpdateSmsTemplateDto,
} from './sms-templates.dto';
import { SmsTemplatesService } from './sms-templates.service';
@Controller('sms-templates')
@UseGuards(JwtAuthGuard)
export class SmsTemplatesController {
constructor(private readonly templates: SmsTemplatesService) {}
@Get()
list(@CurrentUser() user: Actor) {
return this.templates.list(user.organizationId);
}
@Post()
create(@CurrentUser() user: Actor, @Body() dto: CreateSmsTemplateDto) {
return this.templates.create(user.organizationId, dto);
}
@Patch(':id')
update(
@CurrentUser() user: Actor,
@Param('id') id: string,
@Body() dto: UpdateSmsTemplateDto,
) {
return this.templates.update(user.organizationId, id, dto);
}
@Delete(':id')
remove(@CurrentUser() user: Actor, @Param('id') id: string) {
return this.templates.remove(user.organizationId, id);
}
}
@@ -0,0 +1,28 @@
import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
import { SMS_TEMPLATE_BODY_MAX, SMS_TEMPLATE_NAME_MAX } from '@mento/shared';
export class CreateSmsTemplateDto {
@IsString()
@MinLength(1)
@MaxLength(SMS_TEMPLATE_NAME_MAX)
name!: string;
@IsString()
@MinLength(2)
@MaxLength(SMS_TEMPLATE_BODY_MAX)
body!: string;
}
export class UpdateSmsTemplateDto {
@IsOptional()
@IsString()
@MinLength(1)
@MaxLength(SMS_TEMPLATE_NAME_MAX)
name?: string;
@IsOptional()
@IsString()
@MinLength(2)
@MaxLength(SMS_TEMPLATE_BODY_MAX)
body?: string;
}
@@ -0,0 +1,92 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import type { Prisma } from '@prisma/client';
import {
parseSmsTemplates,
SMS_TEMPLATE_MAX,
type SmsTemplateDto,
} from '@mento/shared';
import { PrismaService } from '../prisma/prisma.service';
import type {
CreateSmsTemplateDto,
UpdateSmsTemplateDto,
} from './sms-templates.dto';
@Injectable()
export class SmsTemplatesService {
constructor(private readonly prisma: PrismaService) {}
async list(organizationId: string): Promise<SmsTemplateDto[]> {
const row = await this.prisma.organization.findUnique({
where: { id: organizationId },
select: { smsTemplates: true },
});
return parseSmsTemplates(row?.smsTemplates);
}
async create(
organizationId: string,
dto: CreateSmsTemplateDto,
): Promise<SmsTemplateDto[]> {
const current = await this.list(organizationId);
if (current.length >= SMS_TEMPLATE_MAX) {
throw new BadRequestException(
`حداکثر ${SMS_TEMPLATE_MAX} پیامک آماده می‌توانید داشته باشید.`,
);
}
const next: SmsTemplateDto[] = [
...current,
{
id: randomUUID(),
name: dto.name.trim(),
body: dto.body.trim(),
},
];
return this.persist(organizationId, next);
}
async update(
organizationId: string,
id: string,
dto: UpdateSmsTemplateDto,
): Promise<SmsTemplateDto[]> {
const current = await this.list(organizationId);
const idx = current.findIndex((item) => item.id === id);
if (idx < 0) throw new NotFoundException('پیامک آماده پیدا نشد.');
const prev = current[idx]!;
const next = [...current];
next[idx] = {
id: prev.id,
name: dto.name !== undefined ? dto.name.trim() : prev.name,
body: dto.body !== undefined ? dto.body.trim() : prev.body,
};
return this.persist(organizationId, next);
}
async remove(organizationId: string, id: string): Promise<SmsTemplateDto[]> {
const current = await this.list(organizationId);
if (!current.some((item) => item.id === id)) {
throw new NotFoundException('پیامک آماده پیدا نشد.');
}
return this.persist(
organizationId,
current.filter((item) => item.id !== id),
);
}
private async persist(
organizationId: string,
items: SmsTemplateDto[],
): Promise<SmsTemplateDto[]> {
const stored = parseSmsTemplates(items);
await this.prisma.organization.update({
where: { id: organizationId },
data: { smsTemplates: stored as unknown as Prisma.InputJsonValue },
});
return stored;
}
}
+115 -1
View File
@@ -4,6 +4,10 @@ import {
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import type { import type {
ActivityStatus,
ActivityType,
DealActivityCue,
DealActivitySummaryDto,
DealDto, DealDto,
MergePipelineResultDto, MergePipelineResultDto,
PipelineBoardDto, PipelineBoardDto,
@@ -374,12 +378,23 @@ export class PipelinesService {
}); });
const rateMap = await loadOrgRates(this.prisma, organizationId); const rateMap = await loadOrgRates(this.prisma, organizationId);
const activityHints = await this.loadDealActivityHints(
organizationId,
deals.map((deal) => deal.id),
);
const byStage = new Map<string, DealDto[]>(); const byStage = new Map<string, DealDto[]>();
for (const stage of resolved.stages) byStage.set(stage.id, []); for (const stage of resolved.stages) byStage.set(stage.id, []);
for (const deal of deals) { for (const deal of deals) {
const list = byStage.get(deal.stageId); const list = byStage.get(deal.stageId);
if (list) list.push(this.toDealDto(deal)); if (list) {
const hint = activityHints.get(deal.id);
list.push({
...this.toDealDto(deal),
activityCue: hint?.cue ?? 'none',
activitySummaries: hint?.summaries ?? [],
});
}
} }
return { return {
@@ -597,6 +612,105 @@ export class PipelinesService {
}; };
} }
private async loadDealActivityHints(
organizationId: string,
dealIds: string[],
): Promise<
Map<string, { cue: DealActivityCue; summaries: DealActivitySummaryDto[] }>
> {
const hints = new Map<
string,
{ cue: DealActivityCue; summaries: DealActivitySummaryDto[] }
>();
if (!dealIds.length) return hints;
const rows = await this.prisma.activity.findMany({
where: {
organizationId,
dealId: { in: dealIds },
status: { in: ['open', 'done'] },
},
select: {
id: true,
dealId: true,
title: true,
type: true,
status: true,
dueAt: true,
completedAt: true,
},
});
type Row = {
id: string;
title: string;
type: string;
status: 'open' | 'done';
dueAt: Date | null;
completedAt: Date | null;
};
const byDeal = new Map<string, Row[]>();
for (const row of rows) {
if (!row.dealId) continue;
const list = byDeal.get(row.dealId) ?? [];
list.push({
id: row.id,
title: row.title,
type: row.type,
status: row.status === 'done' ? 'done' : 'open',
dueAt: row.dueAt,
completedAt: row.completedAt,
});
byDeal.set(row.dealId, list);
}
const now = Date.now();
const cueOf = (item: Row): Exclude<DealActivityCue, 'none'> => {
if (item.status === 'done') return 'done';
if (item.dueAt && item.dueAt.getTime() < now) return 'overdue';
return 'upcoming';
};
const rank = (cue: Exclude<DealActivityCue, 'none'>) =>
cue === 'overdue' ? 0 : cue === 'upcoming' ? 1 : 2;
for (const dealId of dealIds) {
const list = byDeal.get(dealId) ?? [];
const summaries = list
.map((item) => {
const cue = cueOf(item);
return {
id: item.id,
title: item.title,
type: item.type as ActivityType,
status: item.status as ActivityStatus,
dueAt: item.dueAt?.toISOString() ?? null,
cue,
_due: item.dueAt?.getTime() ?? Number.POSITIVE_INFINITY,
_done: item.completedAt?.getTime() ?? 0,
};
})
.sort((a, b) => {
const byRank = rank(a.cue) - rank(b.cue);
if (byRank) return byRank;
if (a.cue === 'done' && b.cue === 'done') return b._done - a._done;
return a._due - b._due;
})
.map(({ _due: _d, _done: _c, ...summary }) => summary);
const open = list.filter((item) => item.status === 'open');
let cue: DealActivityCue = 'none';
if (open.some((item) => item.dueAt && item.dueAt.getTime() < now)) {
cue = 'overdue';
} else if (open.length) {
cue = 'upcoming';
} else if (list.some((item) => item.status === 'done')) {
cue = 'done';
}
hints.set(dealId, { cue, summaries });
}
return hints;
}
toDealDto(row: DealRow): DealDto { toDealDto(row: DealRow): DealDto {
return { return {
id: row.id, id: row.id,
+2
View File
@@ -41,6 +41,7 @@ export type RoutineTaskRow = Prisma.RoutineTaskGetPayload<{
export const routineInclude = { export const routineInclude = {
category: true, category: true,
assignee: userSelect, assignee: userSelect,
createdBy: userSelect,
team: { select: { id: true, name: true } }, team: { select: { id: true, name: true } },
} satisfies Prisma.RoutineInclude; } satisfies Prisma.RoutineInclude;
@@ -186,6 +187,7 @@ export function toRoutineDto(
reminderMinutesBefore: row.reminderMinutesBefore, reminderMinutesBefore: row.reminderMinutesBefore,
isActive: row.isActive, isActive: row.isActive,
createdById: row.createdById, createdById: row.createdById,
createdBy: row.createdBy,
recurrenceLabel: describeRecurrence(rule), recurrenceLabel: describeRecurrence(rule),
executionRate: execution.total ? Math.round((execution.done / execution.total) * 100) : null, executionRate: execution.total ? Math.round((execution.done / execution.total) * 100) : null,
executionTotal: execution.total, executionTotal: execution.total,
@@ -273,6 +273,7 @@ export class RoutinesService {
category: _cat, category: _cat,
assignee: _a, assignee: _a,
team: _t, team: _t,
createdBy: _cb,
deletedAt: _d, deletedAt: _d,
...rest ...rest
} = src; } = src;
@@ -511,7 +511,7 @@ export class SmsCampaignsService {
const leadIds = batch const leadIds = batch
.map((r) => r.leadId) .map((r) => r.leadId)
.filter((id): id is string => Boolean(id)); .filter((id): id is string => Boolean(id));
const [people, leads] = await Promise.all([ const [people, leads, org] = await Promise.all([
personIds.length personIds.length
? this.prisma.person.findMany({ ? this.prisma.person.findMany({
where: { id: { in: personIds } }, where: { id: { in: personIds } },
@@ -535,9 +535,14 @@ export class SmsCampaignsService {
}, },
}) })
: Promise.resolve([]), : Promise.resolve([]),
this.prisma.organization.findUnique({
where: { id: campaign.organizationId },
select: { name: true },
}),
]); ]);
const personMap = new Map(people.map((p) => [p.id, p])); const personMap = new Map(people.map((p) => [p.id, p]));
const leadMap = new Map(leads.map((l) => [l.id, l])); const leadMap = new Map(leads.map((l) => [l.id, l]));
const fromOrg = org?.name?.trim() || '';
let sent = 0; let sent = 0;
let failed = 0; let failed = 0;
@@ -572,6 +577,7 @@ export class SmsCampaignsService {
phone: recipient.mobile, phone: recipient.mobile,
title, title,
company, company,
from: fromOrg,
}); });
const personalized = await this.tracking.personalizeSmsBody({ const personalized = await this.tracking.personalizeSmsBody({
@@ -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') @Get('attachments/:id')
async downloadAttachment(@CurrentUser() user: Actor, @Param('id') id: string) { async downloadAttachment(@CurrentUser() user: Actor, @Param('id') id: string) {
const file = await this.treasury.openAttachment(user, id); const file = await this.treasury.openAttachment(user, id);
+123 -21
View File
@@ -4,7 +4,11 @@ import {
Injectable, Injectable,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { parseUserTreasuryAccess } from '@mento/shared'; import {
canManageTreasuryDocuments,
parseUserTreasuryAccess,
permissionsWithTreasuryOverride,
} from '@mento/shared';
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import ExcelJS from 'exceljs'; 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' }, orderBy: { bookedAt: 'desc' },
take: 200, take: 200,
}); });
return rows.map((row) => this.toDocumentDto(row)); 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( async createDocument(
actor: Actor, actor: Actor,
input: { input: {
@@ -557,12 +635,6 @@ export class TreasuryService {
if (input.accountId) { if (input.accountId) {
const account = await this.requireAccount(actor.organizationId, input.accountId, actor); const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.'); 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 bookedAt = startOfDay(input.bookedAt) ?? new Date();
const settlement = input.settlement === true; const settlement = input.settlement === true;
@@ -905,12 +977,6 @@ export class TreasuryService {
if (amount.greaterThan(available)) { if (amount.greaterThan(available)) {
throw new BadRequestException('مبلغ از ماندهٔ سندهای باز این طرف حساب بیشتر است.'); 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(); const occurredAt = startOfDay(input.occurredAt) ?? new Date();
let left = amount; let left = amount;
const touched: string[] = []; const touched: string[] = [];
@@ -1050,12 +1116,6 @@ export class TreasuryService {
} }
const account = await this.requireAccount(actor.organizationId, input.accountId, actor); const account = await this.requireAccount(actor.organizationId, input.accountId, actor);
if (!account.isActive) throw new BadRequestException('حساب غیرفعال است.'); 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 nextSettled = settled.plus(amount);
const status = nextSettled.equals(doc.amount) ? 'settled' : 'partial'; const status = nextSettled.equals(doc.amount) ? 'settled' : 'partial';
await this.prisma.$transaction([ 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> { private async accountScope(actor: Actor): Promise<string[] | null> {
if (actor.role === 'owner' || actor.role === 'admin') return null; if (actor.role === 'owner' || actor.role === 'admin') return null;
const membership = await this.prisma.membership.findFirst({ const membership = await this.prisma.membership.findFirst({
@@ -1566,7 +1667,8 @@ export class TreasuryService {
category?: { name: string } | null; category?: { name: string } | null;
account?: { name: string } | null; account?: { name: string } | null;
movements: Array<{ amount: Prisma.Decimal; voidedAt: Date | 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 { }): FinancialDocumentDto {
const settled = this.settledOf(row.movements); const settled = this.settledOf(row.movements);
const rawRemaining = row.amount.minus(settled); const rawRemaining = row.amount.minus(settled);
+4
View File
@@ -38,6 +38,10 @@ describe('اتوماسیون پیام', () => {
'سلام علی از منتکت - {unknown}', 'سلام علی از منتکت - {unknown}',
); );
assert.equal(applyMessageTemplate('{ name }', { name: 'x' }), 'x'); assert.equal(applyMessageTemplate('{ name }', { name: 'x' }), 'x');
assert.equal(
applyMessageTemplate('از طرف {از طرف}', { from: 'هنراندیشه' }),
'از طرف هنراندیشه',
);
}); });
it('متن پیامک بریده نمی‌شود', () => { it('متن پیامک بریده نمی‌شود', () => {
+52 -1
View File
@@ -1,6 +1,11 @@
import { describe, it } from 'node:test'; import { describe, it } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { leadsDeepWhere, resolveSectionAccess } from '../src/common/data-access'; import {
customersCompanyWhere,
customersPersonWhere,
leadsDeepWhere,
resolveSectionAccess,
} from '../src/common/data-access';
import { import {
noteAccessWhere, noteAccessWhere,
normalizeDataVisibility, normalizeDataVisibility,
@@ -122,3 +127,49 @@ describe('عمق داده وقتی نقش فقط بعضی بخش‌ها را ذ
assert.deepEqual(leads.section, { mode: 'rules', rules: [{ owners: ['self'] }] }); assert.deepEqual(leads.section, { mode: 'rules', rules: [{ owners: ['self'] }] });
}); });
}); });
describe('مسئول گروه مشتری روی عمق داده', () => {
const selfAccess = { mode: 'rules' as const, rules: [{ owners: ['self' as const] }] };
it('محدودیت self با OR مسئول گروه برای شخص', () => {
const where = customersPersonWhere({
userId: 'u1',
role: 'sales',
customersAccess: selfAccess,
teamPeerIds: null,
});
assert.deepEqual(where, {
OR: [
{ ownerId: 'u1' },
{ groupLinks: { some: { group: { assignees: { some: { id: 'u1' } } } } } },
],
});
});
it('محدودیت self با OR مسئول گروه برای شرکت', () => {
const where = customersCompanyWhere({
userId: 'u1',
role: 'sales',
customersAccess: selfAccess,
teamPeerIds: null,
});
assert.deepEqual(where, {
OR: [
{ ownerId: 'u1' },
{ groupLinks: { some: { group: { assignees: { some: { id: 'u1' } } } } } },
],
});
});
it('بدون محدودیت عمقی، فیلتر اضافه نمی‌شود', () => {
assert.deepEqual(
customersPersonWhere({
userId: 'u1',
role: 'sales',
customersAccess: { mode: 'all', rules: [] },
teamPeerIds: null,
}),
{},
);
});
});
@@ -126,6 +126,9 @@ function apply() {
<strong>{{ hasSort ? 'فیلتر و مرتب‌سازی' : 'فیلترها' }}</strong> <strong>{{ hasSort ? 'فیلتر و مرتب‌سازی' : 'فیلترها' }}</strong>
<button type="button" class="link" :disabled="!draftCount" @click="clearAll">پاک کردن همه</button> <button type="button" class="link" :disabled="!draftCount" @click="clearAll">پاک کردن همه</button>
</header> </header>
<p v-if="isPeople" class="facet-hint">
گروه، منبع و وضعیت با هم جمع می‌شوند؛ هر کدام کافی است (بدون تکرار).
</p>
<div class="panel-body"> <div class="panel-body">
<section v-if="hasSort" class="sec"> <section v-if="hasSort" class="sec">
@@ -264,6 +267,15 @@ function apply() {
border-bottom: 1px solid var(--line); border-bottom: 1px solid var(--line);
} }
.facet-hint {
margin: 0;
padding: 0.35rem 0.9rem 0.55rem;
font-size: var(--fs-sm);
color: #64748b;
line-height: 1.45;
border-bottom: 1px solid var(--line);
}
.panel-foot { .panel-foot {
border-top: 1px solid var(--line); border-top: 1px solid var(--line);
justify-content: flex-end; justify-content: flex-end;
+220 -15
View File
@@ -1,29 +1,54 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import axios from 'axios'; import axios from 'axios';
import type { CustomerGroupColor, CustomerGroupDto } from '@mento/shared'; import type { CustomerGroupColor, CustomerGroupDto, OrgUserDto } from '@mento/shared';
import { CUSTOMER_GROUP_COLORS } from '@mento/shared'; import { CUSTOMER_GROUP_COLORS } from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali'; import { toFaDigits } from '@/lib/jalali';
import { normalizeSearchText } from '@/lib/search';
import { import {
CUSTOMER_GROUP_COLOR_LABELS, CUSTOMER_GROUP_COLOR_LABELS,
groupSwatch, groupSwatch,
useCustomerGroups, useCustomerGroups,
} from '@/lib/customer-groups'; } from '@/lib/customer-groups';
import { useAuthStore } from '@/stores/auth';
import { UiButton, UiInput, UiModal } from '@/components/ui'; import { UiButton, UiInput, UiModal } from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue'; import UiIcon from '@/components/UiIcon.vue';
import OrgUserPersonPick from '@/components/OrgUserPersonPick.vue';
const props = defineProps<{ open: boolean }>(); const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; changed: [] }>(); const emit = defineEmits<{ close: []; changed: [] }>();
const auth = useAuthStore();
const canManage = computed(
() => auth.user?.role === 'owner' || auth.user?.role === 'admin',
);
const { groups, load } = useCustomerGroups(); const { groups, load } = useCustomerGroups();
const users = ref<OrgUserDto[]>([]);
const newName = ref(''); const newName = ref('');
const newColor = ref<CustomerGroupColor>('teal'); const newColor = ref<CustomerGroupColor>('teal');
const newAssigneeIds = ref<string[]>([]);
const editingId = ref<string | null>(null); const editingId = ref<string | null>(null);
const editName = ref(''); const editName = ref('');
const assigneeDraft = ref<Record<string, string[]>>({});
const listQuery = ref('');
const busy = ref(false); const busy = ref(false);
const error = ref(''); const error = ref('');
const filteredGroups = computed(() => {
const q = normalizeSearchText(listQuery.value);
if (!q) return groups.value;
return groups.value.filter((g) => {
const assigneeNames = (g.assignees ?? []).map((a) => a.fullName).join(' ');
return (
normalizeSearchText(g.name).includes(q) ||
normalizeSearchText(g.parentName ?? '').includes(q) ||
normalizeSearchText(assigneeNames).includes(q)
);
});
});
function errorText(e: unknown, fallback: string) { function errorText(e: unknown, fallback: string) {
if (axios.isAxiosError(e)) { if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] } | undefined)?.message; const msg = (e.response?.data as { message?: string | string[] } | undefined)?.message;
@@ -33,12 +58,30 @@ function errorText(e: unknown, fallback: string) {
return fallback; return fallback;
} }
async function loadUsers() {
try {
const { data } = await api.get<OrgUserDto[]>('/users');
users.value = data.filter((u) => u.isActive !== false);
} catch {
users.value = [];
}
}
function syncAssigneeDraft() {
const next: Record<string, string[]> = {};
for (const g of groups.value) {
next[g.id] = (g.assignees ?? []).map((a) => a.id);
}
assigneeDraft.value = next;
}
async function run(task: () => Promise<unknown>, fallback: string) { async function run(task: () => Promise<unknown>, fallback: string) {
busy.value = true; busy.value = true;
error.value = ''; error.value = '';
try { try {
await task(); await task();
await load(true); await load(true);
syncAssigneeDraft();
emit('changed'); emit('changed');
return true; return true;
} catch (e) { } catch (e) {
@@ -53,10 +96,18 @@ async function create() {
const name = newName.value.trim(); const name = newName.value.trim();
if (!name) return; if (!name) return;
const ok = await run( const ok = await run(
() => api.post('/customer-groups', { name, color: newColor.value }), () =>
api.post('/customer-groups', {
name,
color: newColor.value,
assigneeIds: newAssigneeIds.value,
}),
'ساخت گروه ناموفق بود.', 'ساخت گروه ناموفق بود.',
); );
if (ok) newName.value = ''; if (ok) {
newName.value = '';
newAssigneeIds.value = [];
}
} }
function startEdit(g: CustomerGroupDto) { function startEdit(g: CustomerGroupDto) {
@@ -82,6 +133,24 @@ async function setColor(g: CustomerGroupDto, color: CustomerGroupColor) {
await run(() => api.patch(`/customer-groups/${g.id}`, { color }), 'تغییر رنگ ناموفق بود.'); await run(() => api.patch(`/customer-groups/${g.id}`, { color }), 'تغییر رنگ ناموفق بود.');
} }
async function onAssigneesChange(g: CustomerGroupDto, ids: string[]) {
assigneeDraft.value = { ...assigneeDraft.value, [g.id]: ids };
const prev = (g.assignees ?? []).map((a) => a.id).sort().join(',');
const next = [...ids].sort().join(',');
if (prev === next) return;
await run(
() => api.patch(`/customer-groups/${g.id}`, { assigneeIds: ids }),
'ذخیره مسئولان گروه ناموفق بود.',
);
}
function assigneeLabel(g: CustomerGroupDto) {
const names = (g.assignees ?? []).map((a) => a.fullName).filter(Boolean);
if (!names.length) return 'بدون مسئول';
if (names.length === 1) return names[0]!;
return `${names[0]} و ${toFaDigits(names.length - 1)} نفر دیگر`;
}
async function remove(g: CustomerGroupDto) { async function remove(g: CustomerGroupDto) {
const used = g.personCount + g.companyCount; const used = g.personCount + g.companyCount;
const note = used ? ` این گروه از ${toFaDigits(used)} مخاطب برداشته می‌شود (خود مخاطب‌ها حذف نمی‌شوند).` : ''; const note = used ? ` این گروه از ${toFaDigits(used)} مخاطب برداشته می‌شود (خود مخاطب‌ها حذف نمی‌شوند).` : '';
@@ -95,7 +164,10 @@ watch(
if (!open) return; if (!open) return;
error.value = ''; error.value = '';
editingId.value = null; editingId.value = null;
void load(true).catch(() => { listQuery.value = '';
void Promise.all([load(true), loadUsers()])
.then(() => syncAssigneeDraft())
.catch(() => {
error.value = 'بارگذاری گروه‌ها ناموفق بود.'; error.value = 'بارگذاری گروه‌ها ناموفق بود.';
}); });
}, },
@@ -107,11 +179,16 @@ watch(
<UiModal :open="open" title="گروه‌های مشتری" @close="emit('close')"> <UiModal :open="open" title="گروه‌های مشتری" @close="emit('close')">
<div class="manager"> <div class="manager">
<p class="lead"> <p class="lead">
هر شخص یا شرکت می‌تواند چند گروه داشته باشد. گروه‌هایی که از ته‌حساب می‌آیند با برچسب هر شخص یا شرکت می‌تواند چند گروه داشته باشد. مسئولان گروه (اختیاری) اعضای آن گروه را مثل
«ته‌حساب» مشخص شده‌اند. مشتریان خود می‌بینند. گروه‌های ته‌حساب با برچسب «ته‌حساب» مشخص شده‌اند.
</p> </p>
<form class="new-row" @submit.prevent="create"> <form v-if="canManage" class="create-panel" @submit.prevent="create">
<header class="create-head">
<strong>گروه جدید</strong>
<span>نام، رنگ و مسئولان را مشخص کنید و افزودن بزنید.</span>
</header>
<div class="new-row">
<UiInput v-model="newName" placeholder="نام گروه جدید" :maxlength="80" :disabled="busy" /> <UiInput v-model="newName" placeholder="نام گروه جدید" :maxlength="80" :disabled="busy" />
<div class="swatches"> <div class="swatches">
<button <button
@@ -129,12 +206,33 @@ watch(
<UiIcon name="plus" :size="15" /> <UiIcon name="plus" :size="15" />
افزودن افزودن
</UiButton> </UiButton>
</div>
<div v-if="users.length" class="assignee-field create-assignees">
<span class="assignees-label">مسئولان (اختیاری)</span>
<OrgUserPersonPick
v-model="newAssigneeIds"
:users="users"
:disabled="busy"
empty-label="انتخاب مسئول"
/>
</div>
</form> </form>
<p v-if="error" class="error">{{ error }}</p> <p v-if="error" class="error">{{ error }}</p>
<ul v-if="groups.length" class="list"> <div v-if="canManage || groups.length" class="list-head">
<li v-for="g in groups" :key="g.id" class="row"> <h3 class="list-title">گروه‌های موجود</h3>
<label v-if="groups.length" class="list-search">
<UiIcon name="search" :size="15" />
<input
v-model="listQuery"
type="search"
placeholder="جستجوی گروه یا مسئول…"
/>
</label>
</div>
<ul v-if="filteredGroups.length" class="list">
<li v-for="g in filteredGroups" :key="g.id" class="row">
<div class="name-cell"> <div class="name-cell">
<form v-if="editingId === g.id" class="edit" @submit.prevent="saveName(g)"> <form v-if="editingId === g.id" class="edit" @submit.prevent="saveName(g)">
<UiInput v-model="editName" :maxlength="80" :disabled="busy" /> <UiInput v-model="editName" :maxlength="80" :disabled="busy" />
@@ -152,9 +250,10 @@ watch(
<span class="count"> <span class="count">
{{ toFaDigits(g.personCount) }} شخص · {{ toFaDigits(g.companyCount) }} شرکت {{ toFaDigits(g.personCount) }} شخص · {{ toFaDigits(g.companyCount) }} شرکت
</span> </span>
<span v-if="!canManage" class="assignee-summary">{{ assigneeLabel(g) }}</span>
</template> </template>
</div> </div>
<div v-if="editingId !== g.id" class="row-actions"> <div v-if="editingId !== g.id && canManage" class="row-actions">
<div class="swatches"> <div class="swatches">
<button <button
v-for="c in CUSTOMER_GROUP_COLORS" v-for="c in CUSTOMER_GROUP_COLORS"
@@ -173,8 +272,20 @@ watch(
<UiIcon name="trash" :size="14" /> <UiIcon name="trash" :size="14" />
</UiButton> </UiButton>
</div> </div>
<div v-if="canManage && users.length" class="assignee-field">
<span class="assignees-label">مسئولان</span>
<OrgUserPersonPick
:model-value="assigneeDraft[g.id] ?? []"
:users="users"
:disabled="busy"
empty-label="انتخاب مسئول"
@update:model-value="(ids) => (assigneeDraft[g.id] = ids)"
@change="(ids) => onAssigneesChange(g, ids)"
/>
</div>
</li> </li>
</ul> </ul>
<p v-else-if="groups.length && listQuery.trim()" class="muted">گروهی با این جستجو پیدا نشد.</p>
<p v-else class="muted">هنوز گروهی ساخته نشده است.</p> <p v-else class="muted">هنوز گروهی ساخته نشده است.</p>
</div> </div>
</UiModal> </UiModal>
@@ -200,6 +311,78 @@ watch(
font-size: 0.85rem; font-size: 0.85rem;
} }
.create-panel {
display: grid;
gap: 0.75rem;
padding: 0.85rem 0.95rem;
border: 1px solid color-mix(in srgb, var(--accent, #0d9488) 28%, #e2e8f0);
border-radius: 12px;
background:
linear-gradient(180deg, color-mix(in srgb, var(--accent, #0d9488) 8%, #fff) 0%, #fff 72%);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.7);
}
.create-head {
display: grid;
gap: 0.15rem;
}
.create-head strong {
color: var(--accent-deep, #0f766e);
font-size: 0.9rem;
font-weight: 700;
}
.create-head span {
color: #64748b;
font-size: 0.78rem;
}
.list-head {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
}
.list-title {
margin: 0;
color: #475569;
font-size: 0.8rem;
font-weight: 700;
}
.list-search {
display: flex;
align-items: center;
gap: 0.4rem;
min-width: min(16rem, 100%);
flex: 1 1 12rem;
max-width: 18rem;
height: 2.25rem;
padding: 0 0.65rem;
border: 1px solid #e2e8f0;
border-radius: var(--radius, 10px);
background: #fff;
color: #94a3b8;
}
.list-search:focus-within {
border-color: #5eead4;
}
.list-search input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: transparent;
font: inherit;
font-size: 0.85rem;
color: #0f172a;
}
.new-row, .new-row,
.edit { .edit {
display: flex; display: flex;
@@ -240,11 +423,9 @@ watch(
.list { .list {
list-style: none; list-style: none;
margin: 0; margin: 0;
padding: 0; padding: 0 0 0.25rem;
display: grid; display: grid;
gap: 0.4rem; gap: 0.4rem;
max-height: 55vh;
overflow-y: auto;
} }
.row { .row {
@@ -282,14 +463,38 @@ watch(
padding: 0.05rem 0.4rem; padding: 0.05rem 0.4rem;
} }
.count { .count,
.assignee-summary {
color: #94a3b8; color: #94a3b8;
font-size: 0.78rem; font-size: 0.78rem;
} }
.assignee-summary {
flex: 1 1 100%;
}
.row-actions { .row-actions {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 0.35rem; gap: 0.35rem;
} }
.assignee-field {
flex: 1 1 100%;
display: grid;
gap: 0.35rem;
padding-top: 0.35rem;
border-top: 1px dashed #e2e8f0;
}
.create-assignees {
border-top: 1px dashed color-mix(in srgb, var(--accent, #0d9488) 22%, #e2e8f0);
padding-top: 0.65rem;
}
.assignees-label {
font-size: 0.75rem;
color: #64748b;
font-weight: 600;
}
</style> </style>
+33 -24
View File
@@ -22,7 +22,6 @@ const props = withDefaults(
defineProps<{ defineProps<{
modelValue: SectionDataAccess; modelValue: SectionDataAccess;
section?: DataAccessSection; section?: DataAccessSection;
groups?: IdOption[];
stages?: IdOption[]; stages?: IdOption[];
pipelines?: IdOption[]; pipelines?: IdOption[];
boards?: IdOption[]; boards?: IdOption[];
@@ -36,7 +35,6 @@ const props = withDefaults(
}>(), }>(),
{ {
section: 'customers', section: 'customers',
groups: () => [],
stages: () => [], stages: () => [],
pipelines: () => [], pipelines: () => [],
boards: () => [], boards: () => [],
@@ -53,9 +51,9 @@ const emit = defineEmits<{
const sectionLabel = computed(() => DATA_ACCESS_SECTION_LABELS[props.section]); const sectionLabel = computed(() => DATA_ACCESS_SECTION_LABELS[props.section]);
const showGroups = computed(() => props.section === 'customers');
const showMoods = computed(() => props.section === 'customers'); const showMoods = computed(() => props.section === 'customers');
const showImportSources = computed(() => props.section === 'customers'); const showImportSources = computed(() => props.section === 'customers');
const isCustomers = computed(() => props.section === 'customers');
const showLeadSources = computed(() => props.section === 'leads'); const showLeadSources = computed(() => props.section === 'leads');
const showNoteTypes = computed(() => props.section === 'notes'); const showNoteTypes = computed(() => props.section === 'notes');
const showTicketStatuses = computed(() => props.section === 'tickets'); const showTicketStatuses = computed(() => props.section === 'tickets');
@@ -119,9 +117,8 @@ const boardsLegend = computed(() =>
/** چند قانون قدیمی → یک فیلتر (اتحاد گزینه‌ها) برای ویرایش ساده */ /** چند قانون قدیمی → یک فیلتر (اتحاد گزینه‌ها) برای ویرایش ساده */
function collapseRules(rules: DataAccessRule[]): DataAccessRule { function collapseRules(rules: DataAccessRule[]): DataAccessRule {
if (!rules.length) return {}; if (!rules.length) return {};
if (rules.length === 1) return { ...rules[0]! }; if (rules.length === 1) return stripCustomerGroupIds({ ...rules[0]! });
const owners = new Set<DataAccessOwnerKind>(); const owners = new Set<DataAccessOwnerKind>();
const groupIds = new Set<string>();
const sources = new Set<string>(); const sources = new Set<string>();
const moods = new Set<PersonMood>(); const moods = new Set<PersonMood>();
const stageIds = new Set<string>(); const stageIds = new Set<string>();
@@ -130,7 +127,6 @@ function collapseRules(rules: DataAccessRule[]): DataAccessRule {
const typeIds = new Set<string>(); const typeIds = new Set<string>();
for (const r of rules) { for (const r of rules) {
for (const o of r.owners ?? []) owners.add(o); for (const o of r.owners ?? []) owners.add(o);
for (const id of r.groupIds ?? []) groupIds.add(id);
for (const s of r.sources ?? []) sources.add(s); for (const s of r.sources ?? []) sources.add(s);
for (const m of r.moods ?? []) moods.add(m); for (const m of r.moods ?? []) moods.add(m);
for (const id of r.stageIds ?? []) stageIds.add(id); for (const id of r.stageIds ?? []) stageIds.add(id);
@@ -140,7 +136,6 @@ function collapseRules(rules: DataAccessRule[]): DataAccessRule {
} }
const out: DataAccessRule = {}; const out: DataAccessRule = {};
if (owners.size) out.owners = [...owners]; if (owners.size) out.owners = [...owners];
if (groupIds.size) out.groupIds = [...groupIds];
if (sources.size) out.sources = [...sources]; if (sources.size) out.sources = [...sources];
if (moods.size) out.moods = [...moods]; if (moods.size) out.moods = [...moods];
if (stageIds.size) out.stageIds = [...stageIds]; if (stageIds.size) out.stageIds = [...stageIds];
@@ -150,10 +145,17 @@ function collapseRules(rules: DataAccessRule[]): DataAccessRule {
return out; return out;
} }
/** دسترسی گروه فقط از مسئول‌گروه؛ groupIds دیگر در فیلتر مشتریان ذخیره/نمایش نمی‌شود */
function stripCustomerGroupIds(rule: DataAccessRule): DataAccessRule {
if (!isCustomers.value || !rule.groupIds?.length) return rule;
const { groupIds: _drop, ...rest } = rule;
return rest;
}
function ruleHasAnyFilter(rule: DataAccessRule): boolean { function ruleHasAnyFilter(rule: DataAccessRule): boolean {
return Boolean( return Boolean(
rule.owners?.length || rule.owners?.length ||
rule.groupIds?.length || (!isCustomers.value && rule.groupIds?.length) ||
rule.sources?.length || rule.sources?.length ||
rule.moods?.length || rule.moods?.length ||
rule.stageIds?.length || rule.stageIds?.length ||
@@ -184,10 +186,26 @@ const mode = computed({
const filter = computed(() => collapseRules(props.modelValue?.rules ?? [])); const filter = computed(() => collapseRules(props.modelValue?.rules ?? []));
/** پاک‌سازی groupIds قدیمی مشتریان هنگام باز شدن ویرایشگر */
watch(
() => [props.section, props.modelValue] as const,
() => {
if (!isCustomers.value || props.modelValue?.mode !== 'rules') return;
const rules = props.modelValue.rules ?? [];
if (!rules.some((r) => r.groupIds?.length)) return;
const collapsed = collapseRules(rules);
emit('update:modelValue', {
mode: 'rules',
rules: [ruleHasAnyFilter(collapsed) ? collapsed : {}],
});
},
{ immediate: true },
);
function emitFilter(next: DataAccessRule) { function emitFilter(next: DataAccessRule) {
const cleaned: DataAccessRule = {}; const cleaned: DataAccessRule = {};
if (next.owners?.length) cleaned.owners = [...next.owners]; if (next.owners?.length) cleaned.owners = [...next.owners];
if (next.groupIds?.length) cleaned.groupIds = [...next.groupIds]; if (!isCustomers.value && next.groupIds?.length) cleaned.groupIds = [...next.groupIds];
if (next.sources?.length) cleaned.sources = [...next.sources]; if (next.sources?.length) cleaned.sources = [...next.sources];
if (next.moods?.length) cleaned.moods = [...next.moods]; if (next.moods?.length) cleaned.moods = [...next.moods];
if (next.stageIds?.length) cleaned.stageIds = [...next.stageIds]; if (next.stageIds?.length) cleaned.stageIds = [...next.stageIds];
@@ -210,7 +228,6 @@ function toggleOwner(kind: DataAccessOwnerKind) {
} }
type ListKey = type ListKey =
| 'groupIds'
| 'sources' | 'sources'
| 'moods' | 'moods'
| 'stageIds' | 'stageIds'
@@ -293,16 +310,6 @@ const moodOptions: Choice[] = PERSON_MOODS.map((mood) => ({
const pickers = computed((): Picker[] => { const pickers = computed((): Picker[] => {
const rule = filter.value; const rule = filter.value;
const items: Picker[] = []; const items: Picker[] = [];
if (showGroups.value) {
items.push({
key: 'groupIds',
legend: 'گروه‌ها',
mode: 'multiple',
placeholder: props.groups.length ? 'جستجو و انتخاب گروه…' : 'گروهی تعریف نشده',
notFound: props.groups.length ? 'موردی پیدا نشد' : 'گروهی تعریف نشده',
options: withSelected(namedOptions(props.groups), rule.groupIds),
});
}
if (showImportSources.value) { if (showImportSources.value) {
const ready = props.importSourcesReady; const ready = props.importSourcesReady;
const failed = props.importSourcesFailed; const failed = props.importSourcesFailed;
@@ -417,7 +424,6 @@ const filterSummary = computed(() => {
const parts: string[] = []; const parts: string[] = [];
if (rule.owners?.includes('self')) parts.push(ownerSelfLabel.value); if (rule.owners?.includes('self')) parts.push(ownerSelfLabel.value);
if (rule.owners?.includes('team')) parts.push('تیم‌های عضو'); if (rule.owners?.includes('team')) parts.push('تیم‌های عضو');
if (rule.groupIds?.length) parts.push(`${rule.groupIds.length} گروه`);
if (rule.sources?.length) parts.push(`${rule.sources.length} مورد منبع/نوع`); if (rule.sources?.length) parts.push(`${rule.sources.length} مورد منبع/نوع`);
if (rule.moods?.length) parts.push(`${rule.moods.length} حال`); if (rule.moods?.length) parts.push(`${rule.moods.length} حال`);
if (rule.pipelineIds?.length) parts.push(`${rule.pipelineIds.length} پایپ‌لاین`); if (rule.pipelineIds?.length) parts.push(`${rule.pipelineIds.length} پایپ‌لاین`);
@@ -443,9 +449,12 @@ const filterSummary = computed(() => {
<template v-if="mode === 'rules'"> <template v-if="mode === 'rules'">
<p class="hint"> <p class="hint">
فقط رکوردهایی دیده می‌شوند که با فیلترهای پرشده با هم
<strong>همهٔ فیلترهای پرشده</strong> <strong>جمع می‌شوند</strong>
جور باشند. در هر فهرست، چند انتخاب یعنی هر کدام کافی است. خالی یعنی بدون محدودیت. ؛ هر بُعد کافی است (بدون تکرار). در هر فهرست هم چند انتخاب یعنی اتحاد. خالی یعنی بدون محدودیت آن بُعد.
<template v-if="isCustomers">
اعضای گروه‌هایی که این کاربر مسئولشان است جداگانه به همین محدوده اضافه می‌شوند.
</template>
</p> </p>
<p v-if="hadMultipleRules" class="hint warn"> <p v-if="hadMultipleRules" class="hint warn">
تنظیم قبلی چندتکه بود؛ اینجا در یک فیلتر ادغام شده. با ذخیره به همین شکل ساده ثبت می‌شود. تنظیم قبلی چندتکه بود؛ اینجا در یک فیلتر ادغام شده. با ذخیره به همین شکل ساده ثبت می‌شود.
@@ -16,7 +16,6 @@ import {
emptySectionDataAccess, emptySectionDataAccess,
} from '@mento/shared'; } from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { useCustomerGroups } from '@/lib/customer-groups';
import DataAccessEditor, { type IdOption } from '@/components/DataAccessEditor.vue'; import DataAccessEditor, { type IdOption } from '@/components/DataAccessEditor.vue';
const props = defineProps<{ const props = defineProps<{
@@ -85,7 +84,6 @@ function setSection(key: DataAccessSection, next: SectionDataAccess) {
}); });
} }
const { groups: customerGroups, load: loadCustomerGroups } = useCustomerGroups();
const importSources = ref<Array<{ value: string; label: string }>>([]); const importSources = ref<Array<{ value: string; label: string }>>([]);
const importSourcesReady = ref(false); const importSourcesReady = ref(false);
const importSourcesFailed = ref(false); const importSourcesFailed = ref(false);
@@ -142,7 +140,6 @@ async function loadTreasuryAccounts() {
} }
async function loadOptions() { async function loadOptions() {
await loadCustomerGroups().catch(() => undefined);
try { try {
const { data } = await api.get<PersonImportSourceStatDto[]>('/people/source-stats'); const { data } = await api.get<PersonImportSourceStatDto[]>('/people/source-stats');
importSources.value = data.map((row) => ({ value: row.source, label: row.label })); importSources.value = data.map((row) => ({ value: row.source, label: row.label }));
@@ -362,7 +359,6 @@ const typesForActive = computed(() => {
:key="active" :key="active"
:section="editorSection" :section="editorSection"
:model-value="sectionValue(editorSection)" :model-value="sectionValue(editorSection)"
:groups="customerGroups"
:stages="stagesForActive" :stages="stagesForActive"
:pipelines="pipelines" :pipelines="pipelines"
:boards="boardsForActive" :boards="boardsForActive"
@@ -0,0 +1,367 @@
<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import type { OrgUserDto } from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
import { normalizeSearchText } from '@/lib/search';
import UiIcon from '@/components/UiIcon.vue';
import UserAvatar from '@/components/UserAvatar.vue';
const props = withDefaults(
defineProps<{
modelValue: string[];
users: Array<Pick<OrgUserDto, 'id' | 'fullName' | 'orgRoleName' | 'hasAvatar'>>;
disabled?: boolean;
emptyLabel?: string;
}>(),
{
disabled: false,
emptyLabel: 'انتخاب مسئول',
},
);
const emit = defineEmits<{
'update:modelValue': [ids: string[]];
change: [ids: string[]];
}>();
const open = ref(false);
const query = ref('');
const searchInput = ref<HTMLInputElement | null>(null);
const selected = computed(() =>
props.modelValue
.map((id) => props.users.find((u) => u.id === id))
.filter((u): u is NonNullable<typeof u> => Boolean(u)),
);
const label = computed(() => {
if (!selected.value.length) return props.emptyLabel;
if (selected.value.length === 1) return selected.value[0]!.fullName;
return `${selected.value[0]!.fullName} و ${toFaDigits(selected.value.length - 1)} نفر دیگر`;
});
const filtered = computed(() => {
const q = normalizeSearchText(query.value);
if (!q) return props.users;
return props.users.filter(
(u) =>
normalizeSearchText(u.fullName).includes(q) ||
normalizeSearchText(u.orgRoleName ?? '').includes(q),
);
});
function toggleMenu() {
if (props.disabled) return;
open.value = !open.value;
if (open.value) {
void nextTick(() => searchInput.value?.focus());
}
}
function close() {
open.value = false;
}
function setIds(next: string[]) {
emit('update:modelValue', next);
emit('change', next);
}
function toggle(userId: string) {
if (props.disabled) return;
const set = new Set(props.modelValue);
if (set.has(userId)) set.delete(userId);
else set.add(userId);
setIds([...set]);
}
function remove(userId: string) {
if (props.disabled) return;
if (!props.modelValue.includes(userId)) return;
setIds(props.modelValue.filter((id) => id !== userId));
}
watch(open, (isOpen) => {
if (!isOpen) query.value = '';
});
defineExpose({ close });
</script>
<template>
<div class="wrap" @click.stop>
<button
class="picker person-pick"
type="button"
:disabled="disabled"
@click="toggleMenu"
>
<div class="assignee-avatars">
<UserAvatar
v-for="user in selected.slice(0, 3)"
:key="user.id"
:name="user.fullName"
:user-id="user.id"
:has-avatar="user.hasAvatar"
:size="28"
/>
<UserAvatar v-if="!selected.length" name="مسئول" :size="28" />
</div>
<span :class="{ ghost: !selected.length }">{{ label }}</span>
<UiIcon name="chevron" :size="16" />
</button>
<div v-if="selected.length" class="chips">
<span v-for="user in selected" :key="user.id" class="chip">
{{ user.fullName }}
<button
type="button"
class="chip-x"
:disabled="disabled"
:aria-label="`حذف ${user.fullName}`"
@click="remove(user.id)"
>
×
</button>
</span>
</div>
<div v-if="open" class="menu person-menu multi-menu" @click.stop>
<label class="person-search">
<UiIcon name="search" :size="15" />
<input
ref="searchInput"
v-model="query"
type="search"
placeholder="جستجوی نام یا نقش…"
@keydown.esc="close"
/>
</label>
<ul class="person-list">
<li v-for="user in filtered" :key="user.id">
<button
type="button"
class="multi-option"
:class="{ on: modelValue.includes(user.id) }"
@click="toggle(user.id)"
>
<span class="check" :class="{ on: modelValue.includes(user.id) }">
<UiIcon v-if="modelValue.includes(user.id)" name="check-plain" :size="12" />
</span>
<UserAvatar
:name="user.fullName"
:user-id="user.id"
:has-avatar="user.hasAvatar"
:size="28"
/>
<span class="role-name">{{ user.fullName }}</span>
<small v-if="user.orgRoleName" class="role-count">{{ user.orgRoleName }}</small>
</button>
</li>
<li v-if="!filtered.length" class="menu-empty">موردی پیدا نشد.</li>
</ul>
</div>
</div>
</template>
<style scoped>
.wrap {
position: relative;
width: 100%;
min-width: 12rem;
}
.picker {
width: 100%;
min-height: var(--control-h, 36px);
height: var(--control-h, 36px);
border: 1px solid #e2e8f0;
border-radius: var(--radius, 10px);
background: #fff;
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.4rem 0.7rem;
font: inherit;
text-align: start;
cursor: pointer;
}
.picker:disabled {
opacity: 0.65;
cursor: not-allowed;
}
.picker .ghost {
color: #94a3b8;
font-weight: 500;
}
.picker :deep(.ico:last-child) {
margin-inline-start: auto;
color: #94a3b8;
transform: rotate(90deg);
}
.assignee-avatars {
display: flex;
align-items: center;
}
.assignee-avatars :deep(.avatar),
.assignee-avatars > * {
margin-inline-end: -0.35rem;
box-shadow: 0 0 0 2px #fff;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin-top: 0.4rem;
}
.chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
max-width: 100%;
padding: 0.15rem 0.35rem 0.15rem 0.55rem;
border-radius: 999px;
background: #f0fdfa;
border: 1px solid #99f6e4;
color: #0f766e;
font-size: 0.78rem;
font-weight: 600;
}
.chip-x {
appearance: none;
border: 0;
background: transparent;
color: inherit;
cursor: pointer;
font: inherit;
line-height: 1;
padding: 0 0.2rem;
border-radius: 999px;
}
.chip-x:hover:not(:disabled) {
background: #ccfbf1;
}
.chip-x:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.menu {
position: absolute;
inset-inline: 0;
top: calc(100% + 0.25rem);
z-index: 40;
margin: 0;
background: #fff;
border-radius: var(--radius, 10px);
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.14);
}
.person-menu {
max-height: none;
overflow: visible;
display: grid;
gap: 0.35rem;
padding: 0.45rem;
border: 1px solid #e2e8f0;
}
.person-search {
display: flex;
align-items: center;
gap: 0.45rem;
height: 2.4rem;
padding: 0 0.7rem;
border: 1px solid #e2e8f0;
border-radius: var(--radius, 10px);
color: #94a3b8;
}
.person-search:focus-within {
border-color: #5eead4;
}
.person-search input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: transparent;
font: inherit;
font-size: 0.88rem;
color: #0f172a;
}
.person-list {
list-style: none;
margin: 0;
padding: 0;
max-height: 15rem;
overflow-y: auto;
}
.multi-menu .multi-option {
display: flex;
align-items: center;
gap: 0.55rem;
width: 100%;
border: 0;
background: none;
padding: 0.55rem 0.5rem;
border-radius: var(--radius, 10px);
font: inherit;
text-align: start;
cursor: pointer;
}
.multi-menu .multi-option:hover {
background: #f8fafc;
}
.multi-menu .multi-option.on {
background: #f0fdfa;
}
.multi-menu .check {
width: 18px;
height: 18px;
border: 1.5px solid #cbd5e1;
border-radius: 5px;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: #fff;
}
.multi-menu .check.on {
background: #14b8a6;
border-color: #14b8a6;
}
.multi-menu .role-name {
min-width: 0;
}
.multi-menu .role-count {
margin-inline-start: auto;
color: #94a3b8;
font-size: 0.72rem;
}
.menu-empty {
padding: 0.6rem;
color: #94a3b8;
font-size: 0.82rem;
}
</style>
+620 -59
View File
@@ -1,10 +1,23 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, nextTick, ref, watch } from 'vue';
import axios from 'axios'; import axios from 'axios';
import type { OutboundSmsHistoryResponse, OutboundSmsLogDto } from '@mento/shared'; import type {
import { MESSAGE_AUTOMATION_FIELDS, countSmsParts } from '@mento/shared'; OutboundSmsHistoryResponse,
OutboundSmsLogDto,
PersonAssetsDto,
SmsTemplateDto,
} from '@mento/shared';
import {
MESSAGE_AUTOMATION_FIELDS,
SMS_TEMPLATE_BODY_MAX,
SMS_TEMPLATE_MAX,
SMS_TEMPLATE_NAME_MAX,
countSmsParts,
} from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali'; import { formatJalaliDay, formatJalaliNumeric, toFaDigits } from '@/lib/jalali';
import { formatTahesabBedBes } from '@/lib/tahesab';
import { useAuthStore } from '@/stores/auth';
import { UiButton, UiModal } from '@/components/ui'; import { UiButton, UiModal } from '@/components/ui';
const props = withDefaults( const props = withDefaults(
@@ -25,7 +38,7 @@ const props = withDefaults(
recordTitle: '', recordTitle: '',
company: '', company: '',
title: 'ارسال پیامک', title: 'ارسال پیامک',
defaultText: 'سلام {نام} عزیز', defaultText: '',
nest: false, nest: false,
}, },
); );
@@ -35,18 +48,73 @@ const emit = defineEmits<{
sent: []; sent: [];
}>(); }>();
type Panel = 'none' | 'fields' | 'templates';
const auth = useAuthStore();
const text = ref(''); const text = ref('');
const busy = ref(false); const busy = ref(false);
const error = ref(''); const error = ref('');
const done = ref(''); const done = ref('');
const fieldsOpen = ref(false); const notice = ref('');
const panel = ref<Panel>('none');
const savingTemplate = ref(false);
const templateName = ref('');
const templateBody = ref('');
const bodyEl = ref<HTMLTextAreaElement | null>(null); const bodyEl = ref<HTMLTextAreaElement | null>(null);
const templateBodyEl = ref<HTMLTextAreaElement | null>(null);
const history = ref<OutboundSmsLogDto[]>([]); const history = ref<OutboundSmsLogDto[]>([]);
const historyLoading = ref(false); const historyLoading = ref(false);
const templates = ref<SmsTemplateDto[]>([]);
const templatesLoading = ref(false);
const fromOrg = ref('');
const rialBalanceText = ref('');
const metalBalanceText = ref('');
const METAL_FIELD_LABELS: Record<string, string> = {
MandeyeVazni: 'طلا',
MandeyeVazniNoghre: 'نقره',
MandeyeKolBeTALA: 'کل به طلا',
MandeMenhayeSeke: 'منهای سکه',
};
function isMetalMandehKey(key: string) {
if (METAL_FIELD_LABELS[key]) return true;
if (key.startsWith('Seke_')) return true;
return /Vazni|طلا|نقره|فلز|Gold|Silver/i.test(key);
}
function metalFieldLabel(key: string) {
if (METAL_FIELD_LABELS[key]) return METAL_FIELD_LABELS[key]!;
if (key.startsWith('Seke_')) return `سکه ${key.slice(5)}`;
return key;
}
function applyAssetsToVars(assets: PersonAssetsDto) {
const fields = assets.mandehFields ?? [];
const mali = fields.find((f) => f.key === 'MandeyeMali' || f.key === 'MandeyeKolBePool');
const rialRaw = mali?.value ?? assets.rialBalance;
rialBalanceText.value =
rialRaw == null || String(rialRaw).trim() === ''
? ''
: formatTahesabBedBes(rialRaw);
const metalParts = fields
.filter((f) => isMetalMandehKey(f.key) && f.value != null && String(f.value).trim() !== '')
.map((f) => `${metalFieldLabel(f.key)} ${formatTahesabBedBes(f.value)}`.trim());
metalBalanceText.value =
metalParts.join('، ') ||
(assets.goldBalance != null ? `طلا ${formatTahesabBedBes(assets.goldBalance)}` : '');
}
const preview = computed(() => fill(text.value)); const preview = computed(() => fill(text.value));
const count = computed(() => text.value.length); const count = computed(() => text.value.length);
const parts = computed(() => countSmsParts(text.value)); const parts = computed(() => countSmsParts(text.value));
const canSaveTemplate = computed(
() =>
templateName.value.trim().length >= 1 &&
templateBody.value.trim().length >= 2 &&
templates.value.length < SMS_TEMPLATE_MAX &&
!savingTemplate.value,
);
watch( watch(
() => props.open, () => props.open,
@@ -55,12 +123,43 @@ watch(
text.value = props.defaultText; text.value = props.defaultText;
error.value = ''; error.value = '';
done.value = ''; done.value = '';
fieldsOpen.value = false; notice.value = '';
panel.value = 'none';
templateName.value = '';
templateBody.value = '';
busy.value = false; busy.value = false;
fromOrg.value = auth.user?.organizationName?.trim() || '';
rialBalanceText.value = '';
metalBalanceText.value = '';
void loadHistory(); void loadHistory();
void loadTemplates();
void loadContextVars();
}, },
); );
async function loadContextVars() {
if (!fromOrg.value) {
try {
const { data } = await api.get<{ name?: string }>('/organizations/current');
if (data?.name?.trim()) fromOrg.value = data.name.trim();
} catch {
/* نام سازمان از auth کافی است */
}
}
const personMatch = props.endpoint.match(/\/people\/([^/]+)\/(?:sms|birthday-sms)/);
if (!personMatch?.[1]) return;
try {
const { data } = await api.get<PersonAssetsDto>(
`/integrations/tahesab/people/${personMatch[1]}/assets`,
{ params: { refresh: '0' } },
);
applyAssetsToVars(data);
} catch {
rialBalanceText.value = '';
metalBalanceText.value = '';
}
}
async function loadHistory() { async function loadHistory() {
history.value = []; history.value = [];
if (!props.historyEndpoint) return; if (!props.historyEndpoint) return;
@@ -77,41 +176,158 @@ async function loadHistory() {
} }
} }
function fill(source: string) { async function loadTemplates() {
const map: Record<string, string> = { templatesLoading.value = true;
نام: props.name, try {
name: props.name, const { data } = await api.get<SmsTemplateDto[]>('/sms-templates');
شماره: props.phone, templates.value = Array.isArray(data) ? data : [];
phone: props.phone, } catch (e) {
تاریخ: formatJalaliDay(new Date()), templates.value = [];
date: formatJalaliDay(new Date()), error.value = apiMessage(e, 'بارگذاری پیامک‌های آماده ناموفق بود.');
عنوان: props.recordTitle || props.name, } finally {
title: props.recordTitle || props.name, templatesLoading.value = false;
شرکت: props.company, }
company: props.company, }
const EMPTY_FIELD_HINT: Record<string, string> = {
عنوان: '〔عنوان ثبت نشده〕',
title: '〔عنوان ثبت نشده〕',
شرکت: '〔شرکت مشتری ثبت نشده〕',
company: '〔شرکت مشتری ثبت نشده〕',
نام: '〔نام ثبت نشده〕',
name: '〔نام ثبت نشده〕',
شماره: '〔شماره ثبت نشده〕',
phone: '〔شماره ثبت نشده〕',
'از طرف': '〔سازمان ثبت نشده〕',
from: '〔سازمان ثبت نشده〕',
'مانده ریالی': '〔مانده ریالی نیست〕',
rialBalance: '〔مانده ریالی نیست〕',
'مانده فلزی': '〔مانده فلزی نیست〕',
metalBalance: '〔مانده فلزی نیست〕',
}; };
return source.replace(/\{([^}]+)\}/g, (full, key: string) => {
const next = map[key.trim()]; function normalizeTemplateKey(key: string) {
return next === undefined ? full : next; return String(key ?? '')
.normalize('NFKC')
.replace(/[\u200c\u200d\u200e\u200f\ufeff]/g, '')
.replace(/ي/g, 'ی')
.replace(/ك/g, 'ک')
.replace(/\s+/g, ' ')
.trim();
}
/** پیش‌نمایش؛ اگر مقدار خالی باشد نشانه می‌گذارد تا با فیلد خالی قاطی نشود. */
function fill(source: string) {
const from = fromOrg.value.trim();
const rial = rialBalanceText.value.trim();
const metal = metalBalanceText.value.trim();
const entries: Array<[string, string]> = [
['نام', props.name.trim()],
['name', props.name.trim()],
['شماره', props.phone.trim()],
['phone', props.phone.trim()],
['تاریخ', formatJalaliDay(new Date())],
['date', formatJalaliDay(new Date())],
['عنوان', props.recordTitle.trim()],
['title', props.recordTitle.trim()],
['شرکت', props.company.trim()],
['company', props.company.trim()],
['از طرف', from],
['ازطرف', from],
['from', from],
['مانده ریالی', rial],
['ماندهریالی', rial],
['rialBalance', rial],
['مانده فلزی', metal],
['ماندهفلزی', metal],
['metalBalance', metal],
];
const map: Record<string, string> = {};
const hints: Record<string, string> = {};
for (const [key, value] of entries) {
const norm = normalizeTemplateKey(key);
map[norm] = value;
if (EMPTY_FIELD_HINT[key]) hints[norm] = EMPTY_FIELD_HINT[key]!;
}
return source.replace(/\{([^}]+)\}/g, (full, rawKey: string) => {
const key = normalizeTemplateKey(rawKey);
if (!(key in map)) return full;
const next = map[key] ?? '';
if (next) return next;
return hints[key] ?? full;
}); });
} }
function insertField(token: string) { function insertInto(
const el = bodyEl.value; target: 'compose' | 'draft',
const current = text.value; token: string,
) {
const el = target === 'compose' ? bodyEl.value : templateBodyEl.value;
const current = target === 'compose' ? text.value : templateBody.value;
const setValue = (next: string) => {
if (target === 'compose') text.value = next;
else templateBody.value = next;
};
if (!el) { if (!el) {
text.value = `${current}${token}`; setValue(`${current}${token}`);
} else { return;
}
const start = el.selectionStart ?? current.length; const start = el.selectionStart ?? current.length;
const end = el.selectionEnd ?? start; const end = el.selectionEnd ?? start;
text.value = `${current.slice(0, start)}${token}${current.slice(end)}`; setValue(`${current.slice(0, start)}${token}${current.slice(end)}`);
const caret = start + token.length; const caret = start + token.length;
requestAnimationFrame(() => { void nextTick(() => {
el.focus(); el.focus();
el.setSelectionRange(caret, caret); el.setSelectionRange(caret, caret);
}); });
} }
fieldsOpen.value = false;
function openPanel(next: Panel) {
panel.value = panel.value === next ? 'none' : next;
notice.value = '';
if (panel.value === 'templates') {
error.value = '';
void loadTemplates();
}
}
function applyTemplate(item: SmsTemplateDto) {
text.value = item.body;
error.value = '';
notice.value = `قالب «${item.name}» در متن پیام قرار گرفت.`;
}
async function saveTemplate() {
const name = templateName.value.trim().slice(0, SMS_TEMPLATE_NAME_MAX);
const body = templateBody.value.trim().slice(0, SMS_TEMPLATE_BODY_MAX);
if (!canSaveTemplate.value || !name || body.length < 2) return;
savingTemplate.value = true;
error.value = '';
notice.value = '';
try {
const { data } = await api.post<SmsTemplateDto[]>('/sms-templates', { name, body });
templates.value = Array.isArray(data) ? data : [];
templateName.value = '';
templateBody.value = '';
notice.value = `پیامک آماده «${name}» ذخیره شد.`;
} catch (e) {
error.value = apiMessage(e, 'ذخیره پیامک آماده ناموفق بود.');
} finally {
savingTemplate.value = false;
}
}
async function removeTemplate(item: SmsTemplateDto) {
if (!confirm(`پیامک آماده «${item.name}» حذف شود؟`)) return;
error.value = '';
notice.value = '';
try {
const { data } = await api.delete<SmsTemplateDto[]>(`/sms-templates/${item.id}`);
templates.value = Array.isArray(data) ? data : [];
notice.value = `«${item.name}» حذف شد.`;
} catch (e) {
error.value = apiMessage(e, 'حذف پیامک آماده ناموفق بود.');
}
} }
function apiMessage(e: unknown, fallback: string) { function apiMessage(e: unknown, fallback: string) {
@@ -122,17 +338,28 @@ function apiMessage(e: unknown, fallback: string) {
return fallback; return fallback;
} }
async function send() { async function send(force = false) {
if (!props.endpoint || busy.value || done.value) return; if (!props.endpoint || busy.value || done.value) return;
busy.value = true; busy.value = true;
error.value = ''; error.value = '';
notice.value = '';
try { try {
await api.post(props.endpoint, { text: text.value }); await api.post(props.endpoint, { text: text.value, ...(force ? { force: true } : {}) });
done.value = 'پیامک ارسال شد.'; done.value = 'پیامک ارسال شد.';
emit('sent'); emit('sent');
void loadHistory(); void loadHistory();
} catch (e) { } catch (e) {
if (axios.isAxiosError(e) && e.response?.status === 409) {
const msg = apiMessage(e, 'قبلاً پیامک تبریک فرستاده شده است. دوباره بفرستیم؟');
if (confirm(msg)) {
busy.value = false;
await send(true);
return;
}
error.value = msg;
} else {
error.value = apiMessage(e, 'ارسال پیامک ناموفق بود.'); error.value = apiMessage(e, 'ارسال پیامک ناموفق بود.');
}
} finally { } finally {
busy.value = false; busy.value = false;
} }
@@ -152,13 +379,33 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
</p> </p>
<div class="tools"> <div class="tools">
<button type="button" class="pill" @click="fieldsOpen = !fieldsOpen">فیلدهای پویا</button> <div class="tool-row">
<div v-if="fieldsOpen" class="fields"> <button
type="button"
class="pill"
:class="{ on: panel === 'fields' }"
@click="openPanel('fields')"
>
فیلدهای پویا
</button>
<button
type="button"
class="pill"
:class="{ on: panel === 'templates' }"
@click="openPanel('templates')"
>
ساخت پیامک آماده
</button>
</div>
<div v-if="panel === 'fields'" class="panel">
<p class="panel-hint">روی فیلد بزنید تا داخل متن پیام درج شود.</p>
<div class="field-grid">
<button <button
v-for="item in MESSAGE_AUTOMATION_FIELDS" v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="item.token" :key="item.token"
type="button" type="button"
@click="insertField(item.token)" @click="insertInto('compose', item.token)"
> >
<code>{{ item.token }}</code> <code>{{ item.token }}</code>
<span>{{ item.label }}</span> <span>{{ item.label }}</span>
@@ -166,8 +413,107 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
</div> </div>
</div> </div>
<textarea ref="bodyEl" v-model="text" rows="4" maxlength="500" placeholder="سلام {نام} عزیز" /> <div v-if="panel === 'templates'" class="panel">
<div class="draft">
<strong>ساخت پیامک آماده جدید</strong>
<p class="panel-hint">این متن جدا از پیام ارسالی است؛ بعد از ذخیره، عنوانش بالا برای استفاده سریع می‌آید.</p>
<input
v-model="templateName"
type="text"
:maxlength="SMS_TEMPLATE_NAME_MAX"
placeholder="نام قالب (مثلاً پیگیری جلسه)"
autocomplete="off"
/>
<textarea
ref="templateBodyEl"
v-model="templateBody"
rows="3"
:maxlength="SMS_TEMPLATE_BODY_MAX"
placeholder="متن قالب، مثلاً: سلام {نام} عزیز…"
/>
<div class="tpl-fields" role="group" aria-label="فیلدهای پویا برای قالب">
<span class="tpl-fields-label">درج فیلد در قالب:</span>
<button
v-for="item in MESSAGE_AUTOMATION_FIELDS"
:key="`tpl-${item.token}`"
type="button"
:title="item.label"
@click="insertInto('draft', item.token)"
>
<code>{{ item.token }}</code>
</button>
</div>
<button
type="button"
class="save-btn"
:disabled="!canSaveTemplate"
@click="saveTemplate"
>
{{ savingTemplate ? 'در حال ذخیره…' : 'ذخیره قالب' }}
</button>
<p v-if="templates.length >= SMS_TEMPLATE_MAX" class="muted">
سقف {{ toFaDigits(SMS_TEMPLATE_MAX) }} قالب پر شده است.
</p>
</div>
<div v-if="templates.length" class="manage-list">
<p class="panel-hint">حذف قالب‌های ذخیره‌شده:</p>
<ul class="template-list">
<li v-for="item in templates" :key="`del-${item.id}`">
<span class="pick-name">{{ item.name }}</span>
<button
type="button"
class="del"
:aria-label="`حذف ${item.name}`"
@click="removeTemplate(item)"
>
حذف
</button>
</li>
</ul>
</div>
</div>
</div>
<div class="compose-layout">
<div class="compose-main">
<label class="compose-label" for="sms-compose-body">متن پیام ارسالی</label>
<textarea
id="sms-compose-body"
ref="bodyEl"
v-model="text"
rows="5"
maxlength="500"
placeholder="متن پیام را بنویسید یا از ستون قالب‌ها انتخاب کنید"
/>
<p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p> <p class="count">{{ toFaDigits(count) }} نویسه · {{ toFaDigits(parts) }} پیامک</p>
</div>
<aside class="quick-col" aria-label="انتخاب سریع پیامک آماده">
<strong class="quick-col-title">قالب‌ها</strong>
<div v-if="templatesLoading" class="muted tiny">در حال بارگذاری…</div>
<div
v-else-if="templates.length"
class="quick-templates"
role="list"
>
<button
v-for="item in templates"
:key="item.id"
type="button"
class="tpl-chip"
role="listitem"
:title="item.body"
@click="applyTemplate(item)"
>
{{ item.name }}
</button>
</div>
<p v-else class="muted tiny quick-empty">
هنوز قالبی نیست. از «ساخت پیامک آماده» بسازید.
</p>
</aside>
</div>
<div class="preview"> <div class="preview">
<span>پیش‌نمایش</span> <span>پیش‌نمایش</span>
@@ -195,6 +541,7 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
</div> </div>
<p v-if="error" class="err">{{ error }}</p> <p v-if="error" class="err">{{ error }}</p>
<p v-else-if="notice" class="ok">{{ notice }}</p>
<p v-if="done" class="ok">{{ done }}</p> <p v-if="done" class="ok">{{ done }}</p>
<template #footer> <template #footer>
@@ -234,66 +581,279 @@ function statusLabel(status: OutboundSmsLogDto['status']) {
} }
.tools { .tools {
position: relative; margin-bottom: 0.55rem;
margin-bottom: 0.45rem;
} }
.pill, .tool-row {
.fields button { display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.pill {
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff); border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: var(--accent-subtle); background: var(--accent-subtle);
color: var(--accent-deep); color: var(--accent-deep);
border-radius: 999px; border-radius: 999px;
font: inherit; font: inherit;
cursor: pointer; cursor: pointer;
}
.pill {
padding: 0.28rem 0.7rem; padding: 0.28rem 0.7rem;
font-size: 0.8rem; font-size: 0.8rem;
} }
.fields { .pill.on {
position: absolute; background: var(--accent-deep);
z-index: 2; color: #fff;
top: calc(100% + 0.3rem); border-color: var(--accent-deep);
inset-inline: 0; }
.panel {
margin-top: 0.45rem;
display: grid; display: grid;
gap: 0.25rem; gap: 0.45rem;
max-width: 100%; padding: 0.55rem;
padding: 0.4rem;
background: #fff; background: #fff;
border: 1px solid #e7eef2; border: 1px solid #e7eef2;
border-radius: 12px; border-radius: 12px;
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
} }
.fields button { .panel-hint {
margin: 0;
color: #64748b;
font-size: 0.75rem;
}
.field-grid {
display: grid;
gap: 0.25rem;
}
.field-grid button {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
gap: 0.6rem; gap: 0.6rem;
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
border-radius: 8px; border-radius: 8px;
padding: 0.35rem 0.5rem; padding: 0.35rem 0.5rem;
background: #fff; background: #fff;
text-align: start; text-align: start;
} font: inherit;
cursor: pointer;
.fields code {
color: var(--accent-deep); color: var(--accent-deep);
} }
textarea { .field-grid code {
color: var(--accent-deep);
}
.template-list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.3rem;
max-height: 9.5rem;
overflow: auto;
}
.template-list li {
display: flex;
align-items: stretch;
gap: 0.3rem;
}
.compose-layout {
display: grid;
grid-template-columns: minmax(0, 1fr) 10.5rem;
gap: 0.75rem;
align-items: stretch;
margin-bottom: 0.15rem;
}
.compose-main {
min-width: 0;
display: grid;
align-content: start;
}
.quick-col {
display: flex;
flex-direction: column;
gap: 0.35rem;
min-height: 0;
max-height: 11.5rem;
padding: 0.5rem;
border: 1px solid #e7eef2;
border-radius: 12px;
background: #fafbfc;
}
.quick-col-title {
font-size: 0.78rem;
color: #0f172a;
}
.quick-templates {
display: flex;
flex-direction: column;
gap: 0.3rem;
min-height: 0;
overflow: auto;
flex: 1;
padding-inline-end: 0.1rem;
}
.tpl-chip {
flex: none;
width: 100%;
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: #fff;
color: var(--accent-deep);
border-radius: 8px;
font: inherit;
font-size: 0.76rem;
font-weight: 600;
padding: 0.4rem 0.5rem;
cursor: pointer;
text-align: start;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tpl-chip:hover {
background: var(--accent-subtle);
}
.quick-empty {
margin: 0;
}
.tiny {
font-size: 0.72rem;
}
@media (max-width: 640px) {
.compose-layout {
grid-template-columns: 1fr;
}
.quick-col {
max-height: 8.5rem;
}
}
.manage-list {
padding-top: 0.45rem;
border-top: 1px solid #eef2f7;
}
.template-list .pick-name {
flex: 1;
min-width: 0;
padding: 0.4rem 0.5rem;
font-size: 0.82rem;
color: #0f172a;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.template-list .del {
flex: none;
border: 0;
border-radius: 8px;
background: transparent;
color: #b91c1c;
font: inherit;
font-size: 0.75rem;
cursor: pointer;
padding: 0.35rem 0.45rem;
}
.draft {
display: grid;
gap: 0.35rem;
padding-top: 0.45rem;
border-top: 1px solid #eef2f7;
}
.draft strong {
font-size: 0.86rem;
color: #0f172a;
}
.draft input,
.draft textarea,
#sms-compose-body {
width: 100%; width: 100%;
box-sizing: border-box; box-sizing: border-box;
border: 1px solid #e2e8f0; border: 1px solid #e2e8f0;
border-radius: 12px; border-radius: 10px;
padding: 0.7rem 0.8rem; padding: 0.55rem 0.7rem;
font: inherit; font: inherit;
resize: vertical;
color: #0f172a; color: #0f172a;
} }
.draft textarea,
#sms-compose-body {
resize: vertical;
}
.tpl-fields {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.3rem;
}
.tpl-fields-label {
color: #64748b;
font-size: 0.74rem;
margin-inline-end: 0.15rem;
}
.tpl-fields button {
border: 1px solid color-mix(in srgb, var(--accent) 28%, #fff);
background: #fff;
color: var(--accent-deep);
border-radius: 999px;
font: inherit;
font-size: 0.74rem;
padding: 0.2rem 0.5rem;
cursor: pointer;
}
.tpl-fields code {
color: inherit;
}
.save-btn {
justify-self: start;
border: 0;
border-radius: 8px;
background: #0f766e;
color: #fff;
font: inherit;
font-size: 0.8rem;
padding: 0.45rem 0.75rem;
cursor: pointer;
}
.save-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.compose-label {
display: block;
margin: 0.15rem 0 0.35rem;
color: #475569;
font-size: 0.8rem;
font-weight: 600;
}
.count { .count {
margin: 0.35rem 0 0; margin: 0.35rem 0 0;
color: #94a3b8; color: #94a3b8;
@@ -316,6 +876,7 @@ textarea {
margin: 0.3rem 0 0; margin: 0.3rem 0 0;
color: #134e4a; color: #134e4a;
overflow-wrap: anywhere; overflow-wrap: anywhere;
white-space: pre-wrap;
} }
.history { .history {
+11 -2
View File
@@ -18,8 +18,10 @@ const props = withDefaults(
tableKey: string; tableKey: string;
label?: string; label?: string;
align?: 'start' | 'end'; align?: 'start' | 'end';
/** فقط آیکون تنظیمات (بدون متن «ستون‌ها») */
iconOnly?: boolean;
}>(), }>(),
{ label: 'ستون‌ها', align: 'start' }, { label: 'ستون‌ها', align: 'start', iconOnly: false },
); );
const open = ref(false); const open = ref(false);
@@ -60,12 +62,19 @@ const placement = computed(() =>
</a-button> </a-button>
</a-flex> </a-flex>
</template> </template>
<a-button :type="hiddenCount > 0 ? 'primary' : 'default'" :ghost="hiddenCount > 0"> <a-button
:type="hiddenCount > 0 ? 'primary' : 'default'"
:ghost="hiddenCount > 0"
:title="iconOnly ? (hiddenCount ? `${label} · ${toFaDigits(hiddenCount)} مخفی` : label) : undefined"
:aria-label="label"
>
<template #icon><SettingOutlined /></template> <template #icon><SettingOutlined /></template>
<template v-if="!iconOnly">
{{ label }} {{ label }}
<template v-if="hiddenCount"> <template v-if="hiddenCount">
· {{ toFaDigits(hiddenCount) }} مخفی · {{ toFaDigits(hiddenCount) }} مخفی
</template> </template>
</template>
</a-button> </a-button>
</a-popover> </a-popover>
</template> </template>
+88 -2
View File
@@ -22,6 +22,7 @@ import {
import { UiButton, UiEmptyState, UiField, UiInput } from '@/components/ui'; import { UiButton, UiEmptyState, UiField, UiInput } from '@/components/ui';
import DataAccessPolicyPanel from '@/components/DataAccessPolicyPanel.vue'; import DataAccessPolicyPanel from '@/components/DataAccessPolicyPanel.vue';
import { formatLocalDateInput, parseLocalInput, toFaDigits } from '@/lib/jalali'; import { formatLocalDateInput, parseLocalInput, toFaDigits } from '@/lib/jalali';
import { matchesSearch } from '@/lib/search';
const props = defineProps<{ const props = defineProps<{
users: OrgUserDto[]; users: OrgUserDto[];
@@ -74,6 +75,29 @@ const editableUsers = computed(() =>
props.users.filter((u) => u.isActive !== false && u.role !== 'owner' && u.role !== 'admin'), props.users.filter((u) => u.isActive !== false && u.role !== 'owner' && u.role !== 'admin'),
); );
const teamsQuery = ref('');
const accessQuery = ref('');
const filteredTeams = computed(() => {
const q = teamsQuery.value.trim();
if (!q) return teams.value;
return teams.value.filter((team) =>
matchesSearch(q, [
team.name,
team.description,
...team.members.map((m) => m.fullName),
]),
);
});
const filteredAccessUsers = computed(() => {
const q = accessQuery.value.trim();
if (!q) return editableUsers.value;
return editableUsers.value.filter((u) =>
matchesSearch(q, [u.fullName, u.mobile, u.email, u.orgRoleName, accessSummary(u)]),
);
});
async function setPriorArchive(userId: string, enabled: boolean) { async function setPriorArchive(userId: string, enabled: boolean) {
priorSavingId.value = userId; priorSavingId.value = userId;
priorPick.value = ''; priorPick.value = '';
@@ -383,14 +407,22 @@ onMounted(() => {
</section> </section>
<section class="card"> <section class="card">
<header class="card-head">
<h3>تیم‌ها</h3> <h3>تیم‌ها</h3>
<UiInput
v-if="teams.length"
v-model="teamsQuery"
placeholder="جستجوی تیم یا عضو…"
/>
</header>
<UiEmptyState <UiEmptyState
v-if="!loading && !teams.length" v-if="!loading && !teams.length"
title="تیمی تعریف نشده" title="تیمی تعریف نشده"
description="تیم بسازید تا اعضای فروش پرونده‌های هم‌تیمی را ببینند." description="تیم بسازید تا اعضای فروش پرونده‌های هم‌تیمی را ببینند."
/> />
<p v-else-if="!filteredTeams.length" class="hint">تیمی با این جستجو پیدا نشد.</p>
<div v-else class="team-list"> <div v-else class="team-list">
<article v-for="t in teams" :key="t.id" class="team"> <article v-for="t in filteredTeams" :key="t.id" class="team">
<header> <header>
<div> <div>
<strong>{{ t.name }}</strong> <strong>{{ t.name }}</strong>
@@ -504,7 +536,14 @@ onMounted(() => {
</section> </section>
<section class="card"> <section class="card">
<header class="card-head">
<h3>محدوده داده</h3> <h3>محدوده داده</h3>
<UiInput
v-if="editableUsers.length"
v-model="accessQuery"
placeholder="جستجوی کاربر…"
/>
</header>
<p class="hint"> <p class="hint">
مالک و مدیر همیشه همه را می‌بینند. پیش‌فرض از نقش می‌آید؛ برای کاربر خاص می‌توانید فیلتر مالک و مدیر همیشه همه را می‌بینند. پیش‌فرض از نقش می‌آید؛ برای کاربر خاص می‌توانید فیلتر
جدا بگذارید. جدا بگذارید.
@@ -514,8 +553,9 @@ onMounted(() => {
title="کاربر قابل تنظیم نیست" title="کاربر قابل تنظیم نیست"
description="فقط نقش‌های فروش و پشتیبانی محدوده داده جدا دارند." description="فقط نقش‌های فروش و پشتیبانی محدوده داده جدا دارند."
/> />
<p v-else-if="!filteredAccessUsers.length" class="hint">کاربری با این جستجو پیدا نشد.</p>
<div v-else class="vis-table"> <div v-else class="vis-table">
<div v-for="u in editableUsers" :key="u.id" class="vis-user"> <div v-for="u in filteredAccessUsers" :key="u.id" class="vis-user">
<div class="vis-row"> <div class="vis-row">
<span> <span>
{{ u.fullName }} {{ u.fullName }}
@@ -567,6 +607,22 @@ onMounted(() => {
margin: 0 0 0.75rem; margin: 0 0 0.75rem;
font-size: 1rem; font-size: 1rem;
} }
.card-head {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
margin-bottom: 0.75rem;
}
.card-head h3 {
margin: 0;
}
.card-head :deep(.field),
.card-head :deep(input) {
min-width: min(16rem, 100%);
max-width: 18rem;
}
.prior-head { .prior-head {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -722,5 +778,35 @@ select {
.prior-picker { .prior-picker {
grid-template-columns: 1fr; grid-template-columns: 1fr;
} }
.card-head {
flex-direction: column;
align-items: stretch;
}
.card-head :deep(.field),
.card-head :deep(input) {
max-width: none;
min-width: 0;
width: 100%;
}
.team header {
flex-direction: column;
align-items: stretch;
}
.team .actions {
width: 100%;
}
.vis-row {
align-items: start;
}
.vis-badge {
display: inline-block;
margin: 0.25rem 0 0;
}
} }
</style> </style>
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import axios from 'axios'; import axios from 'axios';
import type { import type {
@@ -9,7 +9,7 @@ import type {
} from '@mento/shared'; } from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { activityTypeView } from '@/lib/activity-types'; import { activityTypeView } from '@/lib/activity-types';
import { calendarDaysBetween, formatClockFa, formatJalaliDay, startOfLocalDay, toFaDigits } from '@/lib/jalali'; import { formatRelativeDayLabel, toFaDigits } from '@/lib/jalali';
import PipelineBoard from '@/components/pipeline/PipelineBoard.vue'; import PipelineBoard from '@/components/pipeline/PipelineBoard.vue';
import DealCardOverlay from '@/components/pipeline/DealCardOverlay.vue'; import DealCardOverlay from '@/components/pipeline/DealCardOverlay.vue';
import ActivityQuickView from '@/components/activities/ActivityQuickView.vue'; import ActivityQuickView from '@/components/activities/ActivityQuickView.vue';
@@ -71,6 +71,43 @@ let peekLinger = 0;
const moving = ref(false); const moving = ref(false);
const stageBusy = ref(false); const stageBusy = ref(false);
const localOrder = ref<string[] | null>(null); const localOrder = ref<string[] | null>(null);
/** صف جابه‌جایی تا دراپ پشت‌سرهم قفل نشود؛ در watchdog هم ریست می‌شود */
let moveChain: Promise<void> = Promise.resolve();
let moveWatchdog = 0;
/** هویت درگ بیرون از reactivity تا clear/re-render وسط drop شناسه را نبلعد */
let dragSessionId: string | null = null;
let dragVisualTimer = 0;
function clearDragState() {
window.clearTimeout(dragVisualTimer);
dragSessionId = null;
draggingId.value = null;
dropStageId.value = null;
overlayDeal.value = null;
draggingColumnId.value = null;
}
function resetMoveLock() {
window.clearTimeout(moveWatchdog);
moving.value = false;
moveChain = Promise.resolve();
}
function armMoveWatchdog() {
window.clearTimeout(moveWatchdog);
moveWatchdog = window.setTimeout(() => {
resetMoveLock();
}, 12_000);
}
function enqueueMove(task: () => Promise<void>) {
const run = moveChain.then(task, task);
moveChain = run.then(
() => undefined,
() => undefined,
);
return run;
}
const KIND_BADGE: Record<ActivityStageDto['kind'], string | undefined> = { const KIND_BADGE: Record<ActivityStageDto['kind'], string | undefined> = {
open: undefined, open: undefined,
@@ -93,18 +130,6 @@ function apiMessage(e: unknown, fallback: string) {
return fallback; return fallback;
} }
function dateText(item: ActivityDto) {
if (!item.dueAt) return 'بدون موعد';
const due = new Date(item.dueAt);
const days = calendarDaysBetween(due, new Date());
const day =
days === 0 ? 'امروز' : days === 1 ? 'دیروز' : days === -1 ? 'فردا' : formatJalaliDay(due);
const late =
item.status === 'open' &&
startOfLocalDay(due).getTime() < startOfLocalDay().getTime();
return `${late ? 'عقب‌افتاده · ' : ''}${day} · ${formatClockFa(due)}`;
}
function toCard(item: ActivityDto, stageId: string): PipelineDeal { function toCard(item: ActivityDto, stageId: string): PipelineDeal {
const party = item.company?.name || item.person?.fullName || item.deal?.title || ''; const party = item.company?.name || item.person?.fullName || item.deal?.title || '';
const assigneeNames = item.assignees?.length const assigneeNames = item.assignees?.length
@@ -117,7 +142,13 @@ function toCard(item: ActivityDto, stageId: string): PipelineDeal {
title: item.title, title: item.title,
description: [activityTypeView(item).name, party].filter(Boolean).join(' · '), description: [activityTypeView(item).name, party].filter(Boolean).join(' · '),
amount: null, amount: null,
date: dateText(item), date:
item.status === 'done'
? 'انجام شده'
: item.dueAt
? formatRelativeDayLabel(item.dueAt)
: 'بدون موعد',
dateIso: item.dueAt ?? undefined,
initials: initialsFromTitle(party || item.title), initials: initialsFromTitle(party || item.title),
stageId, stageId,
createdAt: item.createdAt, createdAt: item.createdAt,
@@ -126,6 +157,7 @@ function toCard(item: ActivityDto, stageId: string): PipelineDeal {
ownerId: item.assignee?.id ?? null, ownerId: item.assignee?.id ?? null,
assigneeIds: (item.assignees ?? []).map((a) => a.id), assigneeIds: (item.assignees ?? []).map((a) => a.id),
priority: item.priority, priority: item.priority,
activityStatus: item.status,
}; };
} }
@@ -227,14 +259,12 @@ function onMenuActivity(id: string) {
} }
function onDragStart(deal: PipelineDeal, event: DragEvent) { function onDragStart(deal: PipelineDeal, event: DragEvent) {
// اگر شناسهٔ درگ ستون گیر کرده باشد، دراپ کارت را ستون‌جابه‌جا می‌بیند
draggingColumnId.value = null; draggingColumnId.value = null;
draggingId.value = deal.id; // قفل/صف مانده از درخواست قبلی را باز کن
overlayDeal.value = deal; if (moving.value) resetMoveLock();
const sid = findStageOf(deal.id);
overlayAccent.value = dragSessionId = deal.id;
(props.stages.find((s) => s.id === sid)?.color as PipelineAccent | undefined) ?? 'green'; // setData / setDragImage باید همزمان با dragstart باشند
overlayPos.value = { x: (event.clientX || 0) + 12, y: (event.clientY || 0) + 12 };
event.dataTransfer?.setData('text/plain', deal.id); event.dataTransfer?.setData('text/plain', deal.id);
if (event.dataTransfer) { if (event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.effectAllowed = 'move';
@@ -242,21 +272,44 @@ function onDragStart(deal: PipelineDeal, event: DragEvent) {
img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
event.dataTransfer.setDragImage(img, 0, 0); event.dataTransfer.setDragImage(img, 0, 0);
} }
// بستن پیش‌نمایش وسط dragstart گاهی خودِ درگ را لغو می‌کند
if (quickId.value) void nextTick(() => closeQuick()); const sid = findStageOf(deal.id);
overlayAccent.value =
(props.stages.find((s) => s.id === sid)?.color as PipelineAccent | undefined) ?? 'green';
overlayPos.value = { x: (event.clientX || 0) + 12, y: (event.clientY || 0) + 12 };
// تغییر DOM (opacity/overlay/بستن peek) داخل dragstart درگ HTML5 را در کروم لغو می‌کند
window.clearTimeout(dragVisualTimer);
dragVisualTimer = window.setTimeout(() => {
if (dragSessionId !== deal.id) return;
draggingId.value = deal.id;
overlayDeal.value = deal;
if (quickId.value) closeQuick();
}, 0);
} }
function onDragEnd() { function onDragEnd() {
const endedId = draggingId.value; const endedId = dragSessionId ?? draggingId.value;
// drop معمولاً قبل از dragend است؛ کمی تأخیر تا fallback شناسه از بین نرود
window.setTimeout(() => { window.setTimeout(() => {
if (draggingId.value !== endedId) return; if (dragSessionId && dragSessionId !== endedId) return;
draggingId.value = null; if (draggingId.value && draggingId.value !== endedId) return;
dropStageId.value = null; clearDragState();
overlayDeal.value = null;
}, 0); }, 0);
} }
function onColumnDragStart(id: string) {
window.clearTimeout(dragVisualTimer);
dragSessionId = null;
draggingId.value = null;
overlayDeal.value = null;
draggingColumnId.value = id;
}
function onColumnDragEnd() {
draggingColumnId.value = null;
dropStageId.value = null;
}
function onDragOver(stageId: string, event: DragEvent) { function onDragOver(stageId: string, event: DragEvent) {
event.preventDefault(); event.preventDefault();
dropStageId.value = stageId; dropStageId.value = stageId;
@@ -269,17 +322,19 @@ function onDragOver(stageId: string, event: DragEvent) {
async function moveCard(activityId: string, toStageId: string, index?: number) { async function moveCard(activityId: string, toStageId: string, index?: number) {
const fromStageId = findStageOf(activityId); const fromStageId = findStageOf(activityId);
if (!fromStageId) return; if (!fromStageId) return;
const from = columns.value[fromStageId]!; const from = columns.value[fromStageId];
const to = columns.value[toStageId]; const to = columns.value[toStageId];
if (!to) return; if (!from || !to) return;
const fromIndex = from.items.findIndex((i) => i.id === activityId); const fromIndex = from.items.findIndex((i) => i.id === activityId);
const item = from.items[fromIndex]; const item = from.items[fromIndex];
if (!item) return; if (!item) return;
const toStage = props.stages.find((s) => s.id === toStageId)!; const toStage = props.stages.find((s) => s.id === toStageId);
if (!toStage) return;
const same = fromStageId === toStageId; const same = fromStageId === toStageId;
const without = (same ? from.items : to.items).filter((i) => i.id !== activityId); const without = (same ? from.items : to.items).filter((i) => i.id !== activityId);
if (same && index == null) return; if (same && index == null) return;
let insertAt = index == null || index < 0 ? 0 : index; // بدون ایندکس صریح → ته ستون (هم‌تراز با بورد معامله)
let insertAt = index == null || index < 0 ? without.length : index;
if (same && index != null && index > fromIndex) insertAt -= 1; if (same && index != null && index > fromIndex) insertAt -= 1;
insertAt = Math.max(0, Math.min(insertAt, without.length)); insertAt = Math.max(0, Math.min(insertAt, without.length));
if (same && insertAt === fromIndex) return; if (same && insertAt === fromIndex) return;
@@ -301,6 +356,7 @@ async function moveCard(activityId: string, toStageId: string, index?: number) {
} }
moving.value = true; moving.value = true;
armMoveWatchdog();
try { try {
const { data } = await api.patch<ActivityDto>(`/activities/${activityId}/stage`, { const { data } = await api.patch<ActivityDto>(`/activities/${activityId}/stage`, {
stageId: toStageId, stageId: toStageId,
@@ -333,6 +389,7 @@ async function moveCard(activityId: string, toStageId: string, index?: number) {
} }
emit('error', apiMessage(e, 'جابه‌جایی فعالیت ناموفق بود.')); emit('error', apiMessage(e, 'جابه‌جایی فعالیت ناموفق بود.'));
} finally { } finally {
window.clearTimeout(moveWatchdog);
moving.value = false; moving.value = false;
} }
} }
@@ -340,23 +397,24 @@ async function moveCard(activityId: string, toStageId: string, index?: number) {
async function onDrop(stageId: string, event: DragEvent, index?: number) { async function onDrop(stageId: string, event: DragEvent, index?: number) {
event.preventDefault(); event.preventDefault();
const transfer = event.dataTransfer?.getData('text/plain') || ''; const transfer = event.dataTransfer?.getData('text/plain') || '';
const cardId = draggingId.value; const cardId = dragSessionId || draggingId.value;
const columnId = draggingColumnId.value; const columnId = draggingColumnId.value;
dropStageId.value = null; clearDragState();
draggingId.value = null;
overlayDeal.value = null;
draggingColumnId.value = null;
const isStageDrag = transfer.startsWith('stage:'); // کارت همیشه بر payload ستون اولویت دارد تا درگ کارت به‌اشتباه reorder ستون نشود
if (isStageDrag || (!transfer && !cardId && columnId)) { const activityId =
const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId; cardId || (transfer && !transfer.startsWith('stage:') ? transfer : '');
if (fromId) await reorderColumn(fromId, stageId); if (activityId) {
// fire-and-forget: await روی زنجیرهٔ گیرکرده نباید drop بعدی را قفل کند
void enqueueMove(() => moveCard(activityId, stageId, index));
return; return;
} }
const activityId = (!isStageDrag && transfer) || cardId || ''; const isStageDrag = transfer.startsWith('stage:');
if (!activityId || moving.value) return; if (isStageDrag || columnId) {
await moveCard(activityId, stageId, index); const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId;
if (fromId) await reorderColumn(fromId, stageId);
}
} }
async function persistOrder(ids: string[]) { async function persistOrder(ids: string[]) {
@@ -453,6 +511,7 @@ function activityQuery(id: string) {
if (source.typeDefId) query.typeDefId = source.typeDefId; if (source.typeDefId) query.typeDefId = source.typeDefId;
else if (source.type) query.type = source.type; else if (source.type) query.type = source.type;
if (source.status) query.status = source.status; if (source.status) query.status = source.status;
if (source.priority) query.priority = source.priority;
if (source.assigneeId) query.assigneeId = source.assigneeId; if (source.assigneeId) query.assigneeId = source.assigneeId;
if (source.title) query.title = source.title; if (source.title) query.title = source.title;
if (source.customer) query.customer = source.customer; if (source.customer) query.customer = source.customer;
@@ -514,8 +573,8 @@ function openFullActivity(id: string) {
@rename-stage="onRenameStage" @rename-stage="onRenameStage"
@delete-stage="onDeleteStage" @delete-stage="onDeleteStage"
@move-stage="onMoveStage" @move-stage="onMoveStage"
@column-drag-start="(id: string) => { draggingId = null; overlayDeal = null; draggingColumnId = id; }" @column-drag-start="onColumnDragStart"
@column-drag-end="draggingColumnId = null; dropStageId = null" @column-drag-end="onColumnDragEnd"
@add-stage="onAddStage" @add-stage="onAddStage"
@load-more="loadMore" @load-more="loadMore"
/> />
@@ -1,7 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
export type DeskFilterField = 'title' | 'who' | 'customer' | 'type' | 'when' | 'status'; export type DeskFilterField =
| 'title'
| 'who'
| 'customer'
| 'type'
| 'priority'
| 'when'
| 'status';
const props = defineProps<{ const props = defineProps<{
/** یک ستون، یا پنل کامل بالای صفحه */ /** یک ستون، یا پنل کامل بالای صفحه */
@@ -10,11 +17,13 @@ const props = defineProps<{
customer: string; customer: string;
due: '' | 'set' | 'unset'; due: '' | 'set' | 'unset';
typeKey: string; typeKey: string;
priorityKey: string;
statusKey: string; statusKey: string;
assigneeId: string; assigneeId: string;
showAssignee: boolean; showAssignee: boolean;
users: Array<{ id: string; fullName: string }>; users: Array<{ id: string; fullName: string }>;
types: Array<{ key: string; label: string }>; types: Array<{ key: string; label: string }>;
priorities: Array<{ key: string; label: string; color?: string }>;
statuses: Array<{ key: string; label: string }>; statuses: Array<{ key: string; label: string }>;
}>(); }>();
@@ -23,6 +32,7 @@ const emit = defineEmits<{
customer: [value: string]; customer: [value: string];
due: [value: '' | 'set' | 'unset']; due: [value: '' | 'set' | 'unset'];
type: [value: string]; type: [value: string];
priority: [value: string];
status: [value: string]; status: [value: string];
assignee: [value: string]; assignee: [value: string];
clear: []; clear: [];
@@ -86,6 +96,7 @@ const hasAny = computed(
() => () =>
Boolean(props.title.trim() || props.customer.trim() || props.due || props.assigneeId) || Boolean(props.title.trim() || props.customer.trim() || props.due || props.assigneeId) ||
props.typeKey !== 'all' || props.typeKey !== 'all' ||
props.priorityKey !== 'all' ||
props.statusKey !== 'all', props.statusKey !== 'all',
); );
@@ -101,6 +112,9 @@ const whoLabel = computed(
const typeLabel = computed( const typeLabel = computed(
() => props.types.find((item) => item.key === props.typeKey)?.label || 'همه', () => props.types.find((item) => item.key === props.typeKey)?.label || 'همه',
); );
const priorityLabel = computed(
() => props.priorities.find((item) => item.key === props.priorityKey)?.label || 'همه',
);
const statusLabel = computed( const statusLabel = computed(
() => props.statuses.find((item) => item.key === props.statusKey)?.label || 'همه', () => props.statuses.find((item) => item.key === props.statusKey)?.label || 'همه',
); );
@@ -144,6 +158,11 @@ function pickType(next: string) {
finish(); finish();
} }
function pickPriority(next: string) {
emit('priority', props.priorityKey === next && next !== 'all' ? 'all' : next);
finish();
}
function pickStatus(next: string) { function pickStatus(next: string) {
emit('status', props.statusKey === next && next !== 'all' ? 'all' : next); emit('status', props.statusKey === next && next !== 'all' ? 'all' : next);
finish(); finish();
@@ -282,6 +301,36 @@ function pickAssignee(next: string) {
</div> </div>
</section> </section>
<section v-if="shows('priority')">
<button
v-if="field === 'all'"
type="button"
class="acc"
:class="{ on: priorityKey !== 'all' }"
@click="toggleSection('priority')"
>
<span>اولویت</span>
<em>{{ priorityLabel }}</em>
</button>
<div v-if="opened('priority')" class="pick" role="listbox" aria-label="اولویت">
<button
v-for="opt in priorities"
:key="opt.key"
type="button"
:class="{ on: priorityKey === opt.key }"
@click="pickPriority(opt.key)"
>
<span
v-if="opt.color && opt.key !== 'all'"
class="prio-dot"
:style="{ background: opt.color }"
aria-hidden="true"
/>
{{ opt.label }}
</button>
</div>
</section>
<section v-if="shows('when')"> <section v-if="shows('when')">
<button <button
v-if="field === 'all'" v-if="field === 'all'"
@@ -434,6 +483,9 @@ function pickAssignee(next: string) {
} }
.pick button { .pick button {
display: flex;
align-items: center;
gap: 0.4rem;
text-align: start; text-align: start;
border-radius: 8px; border-radius: 8px;
padding: 0.42rem 0.5rem; padding: 0.42rem 0.5rem;
@@ -450,6 +502,13 @@ function pickAssignee(next: string) {
font-weight: 700; font-weight: 700;
} }
.prio-dot {
width: 0.55rem;
height: 0.55rem;
border-radius: 50%;
flex: none;
}
.seg { .seg {
display: flex; display: flex;
gap: 0.25rem; gap: 0.25rem;
@@ -29,6 +29,7 @@ import {
startOfLocalDay, startOfLocalDay,
} from '@/lib/jalali'; } from '@/lib/jalali';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import { canCollaborateOnActivity, canMutateActivity } from '@/lib/activity-access';
import ActivityCommentSheet from '@/components/activities/ActivityCommentSheet.vue'; import ActivityCommentSheet from '@/components/activities/ActivityCommentSheet.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
@@ -200,6 +201,10 @@ function clearNoteMedia() {
const isClosed = computed( const isClosed = computed(
() => activity.value?.status === 'done' || activity.value?.status === 'canceled', () => activity.value?.status === 'done' || activity.value?.status === 'canceled',
); );
const canMutate = computed(() => canMutateActivity(activity.value, auth.user));
const canCollaborate = computed(() =>
canCollaborateOnActivity(activity.value, auth.user),
);
const needsEveryone = computed( const needsEveryone = computed(
() => activity.value?.completionMode === 'all' && (activity.value.assignees?.length ?? 0) > 1, () => activity.value?.completionMode === 'all' && (activity.value.assignees?.length ?? 0) > 1,
); );
@@ -407,6 +412,10 @@ async function runAction() {
error.value = ''; error.value = '';
try { try {
if (isClosed.value) { if (isClosed.value) {
if (!canMutate.value) {
error.value = 'شما مجوز ویرایش این فعالیت را ندارید.';
return;
}
await api.patch(`/activities/${id}`, { status: 'open' }); await api.patch(`/activities/${id}`, { status: 'open' });
await load(id); await load(id);
emit('changed'); emit('changed');
@@ -525,7 +534,13 @@ function openFull() {
<a-divider :style="{ margin: '16px 0 12px' }" /> <a-divider :style="{ margin: '16px 0 12px' }" />
<a-flex justify="space-between" align="center" :style="{ marginBottom: '8px' }"> <a-flex justify="space-between" align="center" :style="{ marginBottom: '8px' }">
<a-typography-text strong>یادداشت</a-typography-text> <a-typography-text strong>یادداشت</a-typography-text>
<a-button type="primary" shape="circle" aria-label="یادداشت جدید" @click="commentOpen = true"> <a-button
type="primary"
shape="circle"
aria-label="یادداشت جدید"
:disabled="!canCollaborate"
@click="commentOpen = true"
>
<template #icon><PlusOutlined /></template> <template #icon><PlusOutlined /></template>
</a-button> </a-button>
</a-flex> </a-flex>
@@ -630,12 +645,16 @@ function openFull() {
<a-flex align="center" :gap="8"> <a-flex align="center" :gap="8">
<a-select <a-select
v-model:value="postponeKey" v-model:value="postponeKey"
:disabled="saving || loading || isClosed" :disabled="saving || loading || isClosed || !canCollaborate"
:options="postponeChoices.map((item) => ({ value: item.key, label: item.label }))" :options="postponeChoices.map((item) => ({ value: item.key, label: item.label }))"
:dropdown-style="{ zIndex: 1200 }" :dropdown-style="{ zIndex: 1200 }"
style="flex: 1" style="flex: 1"
/> />
<a-button type="primary" :disabled="saving || loading || isClosed || !postponeReady" @click="applyPostpone"> <a-button
type="primary"
:disabled="saving || loading || isClosed || !canCollaborate || !postponeReady"
@click="applyPostpone"
>
تعویق تعویق
</a-button> </a-button>
</a-flex> </a-flex>
@@ -644,12 +663,17 @@ function openFull() {
v-model="customDue" v-model="customDue"
mode="datetime" mode="datetime"
placeholder="تاریخ و ساعت" placeholder="تاریخ و ساعت"
:disabled="!canCollaborate"
/> />
</a-flex> </a-flex>
<a-divider :style="{ margin: '16px 0 12px' }" /> <a-divider :style="{ margin: '16px 0 12px' }" />
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8"> <a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
<a-button type="primary" :disabled="saving || loading" @click="runAction"> <a-button
type="primary"
:disabled="saving || loading || (isClosed && !canMutate)"
@click="runAction"
>
{{ actionLabel }} {{ actionLabel }}
</a-button> </a-button>
<a-button type="link" @click="openFull">مشاهدهٔ کامل</a-button> <a-button type="link" @click="openFull">مشاهدهٔ کامل</a-button>
@@ -4,6 +4,7 @@ import axios from 'axios';
import type { import type {
ActivityFieldDef, ActivityFieldDef,
ActivityFieldType, ActivityFieldType,
ActivityPrioritySetting,
ActivityStageColor, ActivityStageColor,
ActivityType, ActivityType,
ActivityTypeDefDto, ActivityTypeDefDto,
@@ -17,9 +18,11 @@ import {
ACTIVITY_STAGE_COLORS, ACTIVITY_STAGE_COLORS,
ACTIVITY_TYPE_ICONS, ACTIVITY_TYPE_ICONS,
ACTIVITY_TYPE_LABELS, ACTIVITY_TYPE_LABELS,
DEFAULT_ACTIVITY_PRIORITY_SETTINGS,
} from '@mento/shared'; } from '@mento/shared';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali'; import { toFaDigits } from '@/lib/jalali';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { import {
ACTIVITY_TYPE_ICON_LABELS, ACTIVITY_TYPE_ICON_LABELS,
newFieldKey, newFieldKey,
@@ -32,6 +35,17 @@ import UiIcon from '@/components/UiIcon.vue';
const props = defineProps<{ open: boolean }>(); const props = defineProps<{ open: boolean }>();
const emit = defineEmits<{ close: []; changed: [] }>(); const emit = defineEmits<{ close: []; changed: [] }>();
type MgrTab = 'types' | 'priorities';
const tab = ref<MgrTab>('types');
const prioritiesApi = useActivityPriorities();
const priorityDraft = ref<ActivityPrioritySetting[]>(
DEFAULT_ACTIVITY_PRIORITY_SETTINGS.map((r) => ({ ...r })),
);
const prioritySaved = ref('');
const priorityDirty = computed(
() => JSON.stringify(priorityDraft.value) !== prioritySaved.value,
);
const BASE_TYPES: ActivityType[] = ['call', 'meeting', 'task', 'note']; const BASE_TYPES: ActivityType[] = ['call', 'meeting', 'task', 'note'];
type FieldDraft = ActivityFieldDef & { optionsText: string }; type FieldDraft = ActivityFieldDef & { optionsText: string };
@@ -96,13 +110,74 @@ function select(id: string | 'new') {
notice.value = ''; notice.value = '';
} }
async function loadPrioritiesTab() {
await prioritiesApi.load(true);
priorityDraft.value = prioritiesApi.items.value.map((r) => ({ ...r }));
prioritySaved.value = JSON.stringify(priorityDraft.value);
}
function switchTab(next: MgrTab) {
if (next === tab.value) return;
if (tab.value === 'types' && dirty.value && draft.value) {
if (!window.confirm('تغییرات ذخیره نشده از بین می‌رود. ادامه می‌دهید؟')) return;
}
if (tab.value === 'priorities' && priorityDirty.value) {
if (!window.confirm('تغییرات اولویت‌ها ذخیره نشده از بین می‌رود. ادامه می‌دهید؟')) return;
}
tab.value = next;
error.value = '';
notice.value = '';
if (next === 'priorities') void loadPrioritiesTab();
}
async function savePriorities() {
for (const row of priorityDraft.value) {
if (!row.label.trim()) {
error.value = 'عنوان همهٔ سطوح اولویت را بنویسید.';
return;
}
if (!/^#[0-9a-fA-F]{6}$/.test(row.color)) {
error.value = 'رنگ باید به صورت #RRGGBB باشد.';
return;
}
}
busy.value = 'prio';
error.value = '';
notice.value = '';
try {
const { data } = await api.put<ActivityPrioritySetting[]>('/activities/priorities', {
items: priorityDraft.value.map((r) => ({
key: r.key,
label: r.label.trim(),
color: r.color,
})),
});
prioritiesApi.setLocal(data);
priorityDraft.value = data.map((r) => ({ ...r }));
prioritySaved.value = JSON.stringify(priorityDraft.value);
notice.value = 'اولویت‌ها ذخیره شد.';
emit('changed');
} catch (e) {
error.value = apiMessage(e, 'ذخیرهٔ اولویت‌ها ناموفق بود.');
} finally {
busy.value = '';
}
}
function resetPriorities() {
if (!window.confirm('عنوان و رنگ‌ها به پیش‌فرض برگردند؟')) return;
priorityDraft.value = DEFAULT_ACTIVITY_PRIORITY_SETTINGS.map((r) => ({ ...r }));
}
watch( watch(
() => props.open, () => props.open,
async (open) => { async (open) => {
if (!open) return; if (!open) return;
error.value = ''; error.value = '';
notice.value = ''; notice.value = '';
tab.value = 'types';
await load(true); await load(true);
await prioritiesApi.load(true);
const first = types.value[0]; const first = types.value[0];
selectedId.value = null; selectedId.value = null;
draft.value = null; draft.value = null;
@@ -283,7 +358,12 @@ async function moveType(index: number, dir: -1 | 1) {
} }
function close() { function close() {
if (dirty.value && draft.value && !window.confirm('تغییرات ذخیره نشده از بین می‌رود. بستن؟')) return; if (tab.value === 'types' && dirty.value && draft.value) {
if (!window.confirm('تغییرات ذخیره نشده از بین می‌رود. بستن؟')) return;
}
if (tab.value === 'priorities' && priorityDirty.value) {
if (!window.confirm('تغییرات اولویت‌ها ذخیره نشده از بین می‌رود. بستن؟')) return;
}
emit('close'); emit('close');
} }
</script> </script>
@@ -291,6 +371,28 @@ function close() {
<template> <template>
<UiModal :open="open" title="انواع فعالیت و فیلدهای اختصاصی" @close="close"> <UiModal :open="open" title="انواع فعالیت و فیلدهای اختصاصی" @close="close">
<div class="mgr"> <div class="mgr">
<div class="tabs" role="tablist">
<button
type="button"
role="tab"
:class="{ on: tab === 'types' }"
:aria-selected="tab === 'types'"
@click="switchTab('types')"
>
انواع و فیلدها
</button>
<button
type="button"
role="tab"
:class="{ on: tab === 'priorities' }"
:aria-selected="tab === 'priorities'"
@click="switchTab('priorities')"
>
اولویت‌ها
</button>
</div>
<template v-if="tab === 'types'">
<p class="hint"> <p class="hint">
برای هر نوع فعالیت فیلدهای مخصوص خودش را تعریف کنید؛ مثلاً «موضوع جلسه» و «شرکت‌کنندگان» برای جلسه برای هر نوع فعالیت فیلدهای مخصوص خودش را تعریف کنید؛ مثلاً «موضوع جلسه» و «شرکت‌کنندگان» برای جلسه
یا «لیست کارها» برای وظیفه. «نوع پایه» مشخص می‌کند فعالیت در گزارش‌ها جزو تماس، جلسه، وظیفه یا پیام یا «لیست کارها» برای وظیفه. «نوع پایه» مشخص می‌کند فعالیت در گزارش‌ها جزو تماس، جلسه، وظیفه یا پیام
@@ -479,6 +581,43 @@ function close() {
</section> </section>
<p v-else class="empty">یک نوع فعالیت را انتخاب کنید.</p> <p v-else class="empty">یک نوع فعالیت را انتخاب کنید.</p>
</div> </div>
</template>
<div v-else class="prio">
<p class="hint">
پنج سطح اولویت ثابت است؛ فقط عنوان و رنگ را عوض کنید. تغییر عنوان روی همهٔ فعالیت‌ها و کارهای
روتین قبلی هم اعمال می‌شود (کلید داخلی عوض نمی‌شود).
</p>
<ul class="prio-list">
<li v-for="row in priorityDraft" :key="row.key" class="prio-row">
<span class="swatch" :style="{ background: row.color }" aria-hidden="true" />
<label class="f grow">
<span>عنوان</span>
<input v-model="row.label" maxlength="40" />
</label>
<label class="f color">
<span>رنگ</span>
<input v-model="row.color" type="color" :aria-label="`رنگ ${row.label}`" />
</label>
</li>
</ul>
<p v-if="error" class="error">{{ error }}</p>
<p v-else-if="notice" class="notice">{{ notice }}</p>
<div class="actions">
<UiButton
variant="primary"
type="button"
:disabled="!priorityDirty || Boolean(busy)"
:loading="busy === 'prio'"
@click="savePriorities"
>
ذخیرهٔ اولویت‌ها
</UiButton>
<UiButton variant="ghost" type="button" :disabled="Boolean(busy)" @click="resetPriorities">
بازگشت به پیش‌فرض
</UiButton>
</div>
</div>
</div> </div>
</UiModal> </UiModal>
</template> </template>
@@ -489,6 +628,78 @@ function close() {
gap: 0.9rem; gap: 0.9rem;
} }
.tabs {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.tabs button {
border: 1px solid var(--line);
background: #fff;
border-radius: 999px;
padding: 0.35rem 0.85rem;
font: inherit;
font-size: 0.84rem;
cursor: pointer;
color: #475569;
}
.tabs button.on {
border-color: #5eead4;
background: #f0fdfa;
color: #0f766e;
font-weight: 600;
}
.prio {
display: grid;
gap: 0.85rem;
}
.prio-list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.55rem;
}
.prio-row {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 0.65rem;
padding: 0.55rem 0.65rem;
border: 1px solid var(--line);
border-radius: var(--radius);
background: #fff;
}
.swatch {
width: 1.1rem;
height: 1.1rem;
border-radius: 999px;
margin-bottom: 0.55rem;
flex-shrink: 0;
border: 1px solid rgba(15, 23, 42, 0.12);
}
.prio-row .grow {
flex: 1;
min-width: 10rem;
}
.prio-row .color input[type='color'] {
width: 3rem;
height: 2.1rem;
padding: 0;
border: 1px solid var(--line);
border-radius: 8px;
background: none;
cursor: pointer;
}
.hint { .hint {
margin: 0; margin: 0;
color: #64748b; color: #64748b;
@@ -0,0 +1,393 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
Alert as AAlert,
Avatar as AAvatar,
Button as AButton,
Card as ACard,
Collapse as ACollapse,
CollapsePanel as ACollapsePanel,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex,
Space as ASpace,
Spin as ASpin,
Tag as ATag,
Typography,
theme,
} from 'ant-design-vue';
import {
CalendarOutlined,
CheckCircleOutlined,
ClockCircleOutlined,
LeftOutlined,
PhoneOutlined,
PlusOutlined,
ScheduleOutlined,
TeamOutlined,
WarningOutlined,
} from '@ant-design/icons-vue';
import type { ActivityDto, ActivityStatus, ActivityType, PaginatedResponse } from '@mento/shared';
import { ACTIVITY_TYPE_LABELS } from '@mento/shared';
import { api } from '@/lib/api';
import {
calendarDaysBetween,
formatClockFa,
formatJalaliDay,
startOfLocalDay,
toFaDigits,
} from '@/lib/jalali';
const { Text: ATypographyText, Title: ATypographyTitle, Paragraph: ATypographyParagraph } =
Typography;
const { token } = theme.useToken();
const STATUS_LABELS: Record<ActivityStatus, string> = {
open: 'باز',
done: 'انجام‌شده',
canceled: 'لغو شده',
};
const TYPE_ICONS: Record<ActivityType, typeof PhoneOutlined> = {
call: PhoneOutlined,
meeting: TeamOutlined,
task: CheckCircleOutlined,
note: ScheduleOutlined,
};
type DueTone = 'overdue' | 'today' | 'soon' | 'later' | 'none';
const props = withDefaults(
defineProps<{
dealId: string;
personId?: string | null;
companyId?: string | null;
dealTitle?: string;
}>(),
{
personId: null,
companyId: null,
dealTitle: '',
},
);
const router = useRouter();
const items = ref<ActivityDto[]>([]);
const loading = ref(false);
const error = ref('');
const closedKeys = ref<string[]>([]);
function sortByDue(a: ActivityDto, b: ActivityDto) {
const ta = a.dueAt ? new Date(a.dueAt).getTime() : Number.POSITIVE_INFINITY;
const tb = b.dueAt ? new Date(b.dueAt).getTime() : Number.POSITIVE_INFINITY;
if (Number.isNaN(ta) && Number.isNaN(tb)) return 0;
if (Number.isNaN(ta)) return 1;
if (Number.isNaN(tb)) return -1;
return ta - tb;
}
const planned = computed(() =>
items.value.filter((a) => a.status === 'open').slice().sort(sortByDue),
);
const closed = computed(() =>
items.value
.filter((a) => a.status !== 'open')
.slice()
.sort((a, b) => {
const ta = a.completedAt || a.updatedAt || a.dueAt || '';
const tb = b.completedAt || b.updatedAt || b.dueAt || '';
return tb.localeCompare(ta);
}),
);
function dueTone(dueAt: string | null): DueTone {
if (!dueAt) return 'none';
const due = new Date(dueAt);
if (Number.isNaN(due.getTime())) return 'none';
const days = calendarDaysBetween(startOfLocalDay(), startOfLocalDay(due));
if (days < 0) return 'overdue';
if (days === 0) return 'today';
if (days <= 2) return 'soon';
return 'later';
}
function dueLabel(dueAt: string | null) {
if (!dueAt) return 'بدون موعد';
const d = new Date(dueAt);
if (Number.isNaN(d.getTime())) return 'بدون موعد';
const tone = dueTone(dueAt);
if (tone === 'overdue') {
const days = Math.abs(calendarDaysBetween(startOfLocalDay(), startOfLocalDay(d)));
return days === 1 ? 'دیروز موعد داشت' : `${toFaDigits(days)} روز تأخیر`;
}
if (tone === 'today') return `امروز · ${formatClockFa(d)}`;
return `${formatJalaliDay(d)} · ${formatClockFa(d)}`;
}
function dueTagColor(tone: DueTone) {
if (tone === 'overdue') return 'error';
if (tone === 'today') return 'warning';
if (tone === 'soon') return 'processing';
return 'default';
}
function rowStyle(tone: DueTone, closedRow = false) {
const base = {
width: '100%',
padding: `${token.value.paddingSM}px ${token.value.padding}px`,
borderRadius: `${token.value.borderRadiusLG}px`,
border: `1px solid ${token.value.colorBorderSecondary}`,
background: token.value.colorBgContainer,
cursor: 'pointer' as const,
opacity: closedRow ? 0.78 : 1,
};
if (closedRow) {
return { ...base, background: token.value.colorFillAlter };
}
if (tone === 'overdue') {
return {
...base,
borderColor: token.value.colorErrorBorder,
background: token.value.colorErrorBg,
};
}
if (tone === 'today') {
return {
...base,
borderColor: token.value.colorWarningBorder,
background: token.value.colorWarningBg,
};
}
return base;
}
function avatarStyle(tone: DueTone) {
if (tone === 'overdue') {
return { backgroundColor: token.value.colorErrorBg, color: token.value.colorError };
}
if (tone === 'today') {
return { backgroundColor: token.value.colorWarningBg, color: token.value.colorWarning };
}
return {
backgroundColor: token.value.colorPrimaryBg,
color: token.value.colorPrimary,
};
}
function typeLabel(item: ActivityDto) {
const type = item.type as ActivityType;
return item.typeDef?.name || ACTIVITY_TYPE_LABELS[type];
}
function statusLabel(status: ActivityDto['status']) {
return STATUS_LABELS[status as ActivityStatus];
}
function typeIcon(type: ActivityDto['type']) {
return TYPE_ICONS[type as ActivityType];
}
function newActivityQuery() {
const query: Record<string, string> = { dealId: props.dealId };
if (props.personId) query.personId = props.personId;
if (props.companyId) query.companyId = props.companyId;
if (props.dealTitle.trim()) query.title = `پیگیری: ${props.dealTitle.trim()}`;
return query;
}
function goCreate() {
void router.push({ name: 'activity-new', query: newActivityQuery() });
}
function goDetail(id: string) {
void router.push({ name: 'activity-detail', params: { id } });
}
async function load() {
if (!props.dealId) return;
loading.value = true;
error.value = '';
try {
const { data } = await api.get<PaginatedResponse<ActivityDto>>('/activities', {
params: { filter: 'all', dealId: props.dealId, limit: 50 },
});
items.value = data.items ?? [];
} catch {
error.value = 'بارگذاری فعالیت‌های معامله ممکن نشد.';
items.value = [];
} finally {
loading.value = false;
}
}
watch(
() => props.dealId,
() => {
void load();
},
{ immediate: true },
);
</script>
<template>
<a-card :bordered="false">
<template #title>
<a-space :size="8">
<CalendarOutlined :style="{ color: token.colorPrimary }" />
<span>فعالیت‌های برنامه‌ریزی‌شده</span>
<a-tag v-if="planned.length" color="processing" :bordered="false">
{{ toFaDigits(planned.length) }} باز
</a-tag>
</a-space>
</template>
<template #extra>
<a-button type="primary" @click="goCreate">
<template #icon><PlusOutlined /></template>
افزودن فعالیت
</a-button>
</template>
<a-alert
v-if="error"
type="error"
show-icon
:message="error"
:style="{ marginBottom: `${token.margin}px` }"
/>
<a-spin :spinning="loading">
<a-empty
v-if="!loading && !planned.length"
:image="AEmpty.PRESENTED_IMAGE_SIMPLE"
:style="{ paddingBlock: `${token.paddingLG}px` }"
>
<template #description>
<a-flex vertical align="center" :gap="token.marginXS">
<a-typography-title :level="5" :style="{ margin: 0 }">
هنوز فعالیتی برای این معامله نیست
</a-typography-title>
<a-typography-paragraph
type="secondary"
:style="{ margin: 0, maxWidth: '28rem', textAlign: 'center' }"
>
یک تماس، جلسه یا پیگیری زمان‌بندی کن تا معامله از دست نرود.
</a-typography-paragraph>
</a-flex>
</template>
<a-button type="primary" @click="goCreate">
<template #icon><PlusOutlined /></template>
افزودن اولین فعالیت
</a-button>
</a-empty>
<a-flex v-else-if="planned.length" vertical :gap="token.marginSM">
<a-flex
v-for="item in planned"
:key="item.id"
align="center"
justify="space-between"
:gap="token.marginSM"
wrap="wrap"
:style="rowStyle(dueTone(item.dueAt))"
role="button"
tabindex="0"
@click="goDetail(item.id)"
@keydown.enter="goDetail(item.id)"
>
<a-flex align="center" :gap="token.marginSM" :style="{ minWidth: 0, flex: '1 1 220px' }">
<a-avatar :size="40" :style="avatarStyle(dueTone(item.dueAt))">
<template #icon>
<WarningOutlined v-if="dueTone(item.dueAt) === 'overdue'" />
<ClockCircleOutlined v-else-if="dueTone(item.dueAt) === 'today'" />
<component :is="typeIcon(item.type)" v-else />
</template>
</a-avatar>
<a-flex vertical :gap="4" :style="{ minWidth: 0 }">
<a-typography-text strong :ellipsis="{ tooltip: item.title }">
{{ item.title }}
</a-typography-text>
<a-space :size="8" wrap>
<a-tag :bordered="false">{{ typeLabel(item) }}</a-tag>
<a-tag :color="dueTagColor(dueTone(item.dueAt))" :bordered="false">
{{ dueLabel(item.dueAt) }}
</a-tag>
<a-typography-text v-if="item.assignee?.fullName" type="secondary">
{{ item.assignee.fullName }}
</a-typography-text>
</a-space>
</a-flex>
</a-flex>
<LeftOutlined :style="{ color: token.colorTextQuaternary, flexShrink: 0 }" />
</a-flex>
</a-flex>
<template v-if="closed.length">
<a-divider v-if="planned.length" :style="{ margin: `${token.marginMD}px 0` }" />
<a-collapse
v-model:activeKey="closedKeys"
ghost
:bordered="false"
:style="{
background: 'transparent',
marginTop: planned.length ? 0 : `${token.marginSM}px`,
}"
>
<a-collapse-panel key="closed">
<template #header>
<a-typography-text type="secondary">
{{ toFaDigits(closed.length) }} فعالیت انجام‌شده یا لغو شده
</a-typography-text>
</template>
<a-flex vertical :gap="token.marginSM">
<a-flex
v-for="item in closed"
:key="item.id"
align="center"
justify="space-between"
:gap="token.marginSM"
wrap="wrap"
:style="rowStyle('none', true)"
role="button"
tabindex="0"
@click="goDetail(item.id)"
@keydown.enter="goDetail(item.id)"
>
<a-flex
align="center"
:gap="token.marginSM"
:style="{ minWidth: 0, flex: '1 1 220px' }"
>
<a-avatar
:size="40"
:style="{
backgroundColor: token.colorFillSecondary,
color: token.colorTextSecondary,
}"
>
<template #icon>
<component :is="typeIcon(item.type)" />
</template>
</a-avatar>
<a-flex vertical :gap="4" :style="{ minWidth: 0 }">
<a-typography-text :ellipsis="{ tooltip: item.title }">
{{ item.title }}
</a-typography-text>
<a-space :size="8" wrap>
<a-tag :bordered="false">{{ statusLabel(item.status) }}</a-tag>
<a-typography-text type="secondary">
{{ dueLabel(item.dueAt) }}
</a-typography-text>
</a-space>
</a-flex>
</a-flex>
<LeftOutlined :style="{ color: token.colorTextQuaternary, flexShrink: 0 }" />
</a-flex>
</a-flex>
</a-collapse-panel>
</a-collapse>
</template>
</a-spin>
</a-card>
</template>
@@ -3,6 +3,8 @@ import { computed, onMounted, ref } from 'vue';
import { RouterLink } from 'vue-router'; import { RouterLink } from 'vue-router';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali'; import { toFaDigits } from '@/lib/jalali';
import { hasSectionPermission } from '@/lib/section-permissions';
import { useAuthStore } from '@/stores/auth';
import UiIcon from '@/components/UiIcon.vue'; import UiIcon from '@/components/UiIcon.vue';
import { UiModal } from '@/components/ui'; import { UiModal } from '@/components/ui';
import SmsComposeModal from '@/components/SmsComposeModal.vue'; import SmsComposeModal from '@/components/SmsComposeModal.vue';
@@ -25,9 +27,13 @@ type BirthdayMonth = {
items: BirthdayItem[]; items: BirthdayItem[];
}; };
const auth = useAuthStore();
const data = ref<BirthdayMonth | null>(null); const data = ref<BirthdayMonth | null>(null);
const listOpen = ref(false); const listOpen = ref(false);
const smsTarget = ref<BirthdayItem | null>(null); const smsTarget = ref<BirthdayItem | null>(null);
const canSeeCustomers = computed(() =>
hasSectionPermission(auth.user?.role, auth.user?.permissions, 'customers'),
);
const groups = computed(() => { const groups = computed(() => {
const map = new Map<number, BirthdayItem[]>(); const map = new Map<number, BirthdayItem[]>();
@@ -44,6 +50,10 @@ function openSms(person: BirthdayItem) {
} }
onMounted(async () => { onMounted(async () => {
if (!canSeeCustomers.value) {
data.value = null;
return;
}
try { try {
const { data: body } = await api.get<BirthdayMonth>('/people/birthdays'); const { data: body } = await api.get<BirthdayMonth>('/people/birthdays');
data.value = body.total > 0 ? body : null; data.value = body.total > 0 ? body : null;
+124 -33
View File
@@ -1,10 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed, onMounted, ref } from 'vue';
import { import {
CalendarOutlined, CalendarOutlined,
CheckOutlined, CheckOutlined,
DeleteOutlined, DeleteOutlined,
FlagFilled, FlagFilled,
LeftOutlined,
MoreOutlined, MoreOutlined,
} from '@ant-design/icons-vue'; } from '@ant-design/icons-vue';
import { import {
@@ -18,10 +19,12 @@ import {
Typography, Typography,
theme, theme,
} from 'ant-design-vue'; } from 'ant-design-vue';
import DealQuickActivityPopover from '@/components/pipeline/DealQuickActivityPopover.vue';
import { calendarDaysBetween, formatJalaliNumeric } from '@/lib/jalali';
import { userAvatarSrc } from '@/lib/userAvatars'; import { userAvatarSrc } from '@/lib/userAvatars';
import type { ActivityPriority } from '@mento/shared';
import type { PipelineAccent, PipelineDeal, PipelineUiCopy } from '@/lib/pipeline-board'; import type { PipelineAccent, PipelineDeal, PipelineUiCopy } from '@/lib/pipeline-board';
import { DEAL_BOARD_COPY, formatCurrencyParts } from '@/lib/pipeline-board'; import { DEAL_BOARD_COPY, formatCurrencyParts } from '@/lib/pipeline-board';
import { useActivityPriorities } from '@/lib/activity-priorities';
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
@@ -51,6 +54,11 @@ const emit = defineEmits<{
const { Text: ATypographyText } = Typography; const { Text: ATypographyText } = Typography;
const { token } = theme.useToken(); const { token } = theme.useToken();
const activityOpen = ref(false);
const highlighted = computed(
() => props.selected || props.peeking || activityOpen.value,
);
const showAmount = computed( const showAmount = computed(
() => !props.copy.hideAmount && props.deal.amount != null, () => !props.copy.hideAmount && props.deal.amount != null,
); );
@@ -67,16 +75,24 @@ const extraAssignees = computed(() =>
Math.max(0, (props.deal.assigneeNames?.length ?? 0) - 1), Math.max(0, (props.deal.assigneeNames?.length ?? 0) - 1),
); );
const showTrash = computed(() => props.selectMode && props.selected); const showTrash = computed(() => props.selectMode && props.selected);
const PRIORITY_FLAG: Record<ActivityPriority, { label: string; color: string }> = { const dateHint = computed(() => {
very_high: { label: 'خیلی زیاد', color: '#dc2626' }, if (!props.deal.dateIso) return props.deal.date;
high: { label: 'زیاد', color: '#ea580c' }, const d = new Date(props.deal.dateIso);
medium: { label: 'متوسط', color: '#eab308' }, if (Number.isNaN(d.getTime())) return props.deal.date;
low: { label: 'کم', color: '#16a34a' }, return formatJalaliNumeric(d);
very_low: { label: 'خیلی کم', color: '#94a3b8' }, });
const activityPriorities = useActivityPriorities();
onMounted(() => {
void activityPriorities.load();
});
const priorityFlag = computed(() => {
const key = props.deal.priority;
if (!key) return null;
return {
label: activityPriorities.labelOf(key),
color: activityPriorities.colorOf(key),
}; };
const priorityFlag = computed(() => });
props.deal.priority ? PRIORITY_FLAG[props.deal.priority] : null,
);
function onTitleClick() { function onTitleClick() {
if (props.selectMode) { if (props.selectMode) {
@@ -87,27 +103,65 @@ function onTitleClick() {
else emit('open', props.deal.id); else emit('open', props.deal.id);
} }
const chevronStyle = computed(() => ({ /** موعد: (فقط فعالیت) انجام‌شده سبز · عقب‌افتاده قرمز · امروز زرد · آینده/بی‌موعد خاکستری */
display: 'inline-block', const dueTone = computed<'done' | 'overdue' | 'today' | 'upcoming' | 'none'>(() => {
width: '0.42rem', if (props.copy.quickView && props.deal.activityStatus === 'done') return 'done';
height: '0.42rem', if (!props.deal.dateIso) return 'none';
borderRight: '1.6px solid currentColor', const due = new Date(props.deal.dateIso);
borderBottom: '1.6px solid currentColor', if (Number.isNaN(due.getTime())) return 'none';
transform: props.previewing ? 'rotate(-45deg)' : 'rotate(135deg)', const days = calendarDaysBetween(new Date(), due);
if (days < 0) return 'overdue';
if (days === 0) return 'today';
return 'upcoming';
});
const dueToneColor = computed(() => {
if (dueTone.value === 'done') return token.value.colorSuccess;
if (dueTone.value === 'overdue') return token.value.colorError;
if (dueTone.value === 'today') return token.value.colorWarning;
return token.value.colorTextSecondary;
});
const chevronBtnStyle = computed(() => ({
boxSizing: 'border-box' as const,
width: '22px',
height: '22px',
margin: 0,
padding: 0,
border: `1.5px solid ${dueToneColor.value}`,
borderRadius: '50%',
background: 'transparent',
color: dueToneColor.value,
display: 'inline-grid',
placeItems: 'center',
cursor: 'pointer',
lineHeight: 0,
flexShrink: 0,
}));
const chevronIconStyle = computed(() => ({
fontSize: '10px',
width: '10px',
height: '10px',
lineHeight: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
transform: props.previewing ? 'rotate(180deg)' : 'none',
transition: 'transform 0.15s ease', transition: 'transform 0.15s ease',
})); }));
const cardStyle = computed(() => ({ const cardStyle = computed(() => ({
cursor: props.selectMode ? 'pointer' : 'grab', cursor: props.selectMode ? 'pointer' : 'grab',
opacity: props.dragging ? 0.4 : 1, // تغییر opacity/transform وسط dragstart درگ HTML5 را در کروم لغو می‌کند؛ فقط سایه
transform: props.dragging ? 'scale(0.98)' : 'none', opacity: props.dragging ? 0.55 : 1,
transition: 'opacity 180ms ease, transform 180ms ease, box-shadow 180ms ease', transition: 'opacity 120ms ease, box-shadow 120ms ease',
margin: 0, margin: 0,
position: props.peeking ? 'relative' : undefined, position: highlighted.value ? 'relative' : undefined,
zIndex: props.peeking ? 2 : undefined, zIndex: highlighted.value ? 2 : undefined,
background: props.selected || props.peeking ? token.value.colorPrimaryBg : token.value.colorBgContainer, background: highlighted.value ? token.value.colorPrimaryBg : token.value.colorBgContainer,
borderColor: props.selected || props.peeking ? token.value.colorPrimary : token.value.colorBorderSecondary, borderColor: highlighted.value ? token.value.colorPrimary : token.value.colorBorderSecondary,
boxShadow: props.peeking boxShadow: highlighted.value
? `0 0 0 2px ${token.value.colorPrimary}` ? `0 0 0 2px ${token.value.colorPrimary}`
: props.dragging : props.dragging
? token.value.boxShadow ? token.value.boxShadow
@@ -230,38 +284,75 @@ const cardStyle = computed(() => ({
<a-tag v-if="extraAssignees > 0" :bordered="false" :title="assigneeTitle"> <a-tag v-if="extraAssignees > 0" :bordered="false" :title="assigneeTitle">
+{{ extraAssignees }} +{{ extraAssignees }}
</a-tag> </a-tag>
<a-typography-text type="secondary" :style="{ fontSize: `${token.fontSizeSM}px` }"> <a-tooltip :title="dateHint">
<a-typography-text
:type="dueTone === 'none' ? 'secondary' : undefined"
:style="{
fontSize: `${token.fontSizeSM}px`,
color: dueTone !== 'none' ? dueToneColor : undefined,
}"
>
<CalendarOutlined :style="{ marginInlineEnd: '4px' }" /> <CalendarOutlined :style="{ marginInlineEnd: '4px' }" />
{{ deal.date }} {{ deal.date }}
</a-typography-text> </a-typography-text>
</a-tooltip>
</a-space> </a-space>
<a-space :size="4" align="center" :style="{ flexShrink: 0 }">
<a-typography-text <a-typography-text
v-if="showAmount" v-if="showAmount"
strong strong
dir="ltr" dir="ltr"
:style="{ margin: 0, whiteSpace: 'nowrap', flexShrink: 0 }" :style="{ margin: 0, whiteSpace: 'nowrap' }"
> >
{{ money.number }} {{ money.number }}
<a-typography-text type="secondary" :style="{ fontSize: `${token.fontSizeSM}px` }"> <a-typography-text type="secondary" :style="{ fontSize: `${token.fontSizeSM}px` }">
{{ money.unit }} {{ money.unit }}
</a-typography-text> </a-typography-text>
</a-typography-text> </a-typography-text>
<a-button <button
v-if="copy.quickView && !selectMode" v-if="copy.quickView && !selectMode"
type="text" type="button"
class="deal-card-peek"
:aria-label="previewing ? 'بستن پیش‌نمایش' : 'پیش‌نمایش فعالیت'" :aria-label="previewing ? 'بستن پیش‌نمایش' : 'پیش‌نمایش فعالیت'"
:aria-expanded="previewing" :aria-expanded="previewing"
:style="{ color: token.colorTextSecondary }" :style="chevronBtnStyle"
@click.stop="emit('open', deal.id)" @click.stop="emit('open', deal.id)"
> >
<template #icon><i class="chev" aria-hidden="true" :style="chevronStyle" /></template> <LeftOutlined :style="chevronIconStyle" />
</a-button> </button>
<a-tooltip v-else-if="priorityFlag" :title="`اولویت: ${priorityFlag.label}`"> <a-tooltip v-else-if="priorityFlag" :title="`اولویت: ${priorityFlag.label}`">
<span :style="{ display: 'inline-flex', flexShrink: 0, lineHeight: 1 }"> <span :style="{ display: 'inline-flex', flexShrink: 0, lineHeight: 1 }">
<FlagFilled :style="{ color: priorityFlag.color, fontSize: '16px' }" /> <FlagFilled :style="{ color: priorityFlag.color, fontSize: '16px' }" />
</span> </span>
</a-tooltip> </a-tooltip>
<span
v-if="copy.quickActivity && !selectMode"
@click.stop
@mousedown.stop
>
<DealQuickActivityPopover
:deal="deal"
@update:open="activityOpen = $event"
/>
</span>
</a-space>
</a-flex> </a-flex>
</a-flex> </a-flex>
</a-card> </a-card>
</template> </template>
<style scoped>
/* وسط‌چین دقیق آیکون داخل دایره (anticon پیش‌فرض vertical-align دارد) */
.deal-card-peek :deep(.anticon) {
display: inline-flex !important;
align-items: center;
justify-content: center;
vertical-align: 0;
line-height: 0;
}
.deal-card-peek :deep(.anticon > svg) {
display: block;
width: 10px;
height: 10px;
}
</style>
@@ -0,0 +1,571 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
Alert as AAlert,
Badge as ABadge,
Button as AButton,
Card as ACard,
Col as ACol,
Divider as ADivider,
Flex as AFlex,
FormItem as AFormItem,
Input as AInput,
Row as ARow,
Select as ASelect,
Space as ASpace,
Tooltip as ATooltip,
Typography,
message,
theme,
} from 'ant-design-vue';
import {
CalendarOutlined,
CloseOutlined,
FormOutlined,
PlusOutlined,
} from '@ant-design/icons-vue';
import type {
ActivityDto,
ActivityType,
CreateActivityRequest,
DealActivityCue,
DealActivitySummaryDto,
} from '@mento/shared';
import { ACTIVITY_TYPE_LABELS } from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { api } from '@/lib/api';
import {
formatLocalDateInput,
formatRelativeDayLabel,
formatClockFa,
toFaDigits,
} from '@/lib/jalali';
import type { PipelineDeal } from '@/lib/pipeline-board';
const { Title: ATypographyTitle, Link: ATypographyLink, Text: ATypographyText } =
Typography;
const props = defineProps<{
deal: PipelineDeal;
disabled?: boolean;
}>();
const emit = defineEmits<{
'update:open': [open: boolean];
}>();
const router = useRouter();
const { token } = theme.useToken();
type PanelMode = 'list' | 'create';
const open = ref(false);
const rendered = ref(false);
const placed = ref(false);
const panelEl = ref<HTMLElement | null>(null);
const frame = ref({ left: 12, top: 12, width: 360, maxHeight: 480, shift: 88 });
let hideTimer = 0;
let reveal = false;
const VIEW_PAD = 16;
const PREVIEW_LIMIT = 3;
const mode = ref<PanelMode>('create');
const listExpanded = ref(false);
const saving = ref(false);
const error = ref('');
const title = ref('');
const type = ref<ActivityType>('task');
const dueDate = ref('');
const dueTime = ref('');
const localCue = ref<DealActivityCue | null>(null);
const localSummaries = ref<DealActivitySummaryDto[] | null>(null);
const summaries = computed(
() => localSummaries.value ?? props.deal.activitySummaries ?? [],
);
const activityCue = computed<DealActivityCue>(
() => localCue.value ?? props.deal.activityCue ?? 'none',
);
const openCount = computed(
() => summaries.value.filter((item) => item.status === 'open').length,
);
const visibleSummaries = computed(() =>
listExpanded.value ? summaries.value : summaries.value.slice(0, PREVIEW_LIMIT),
);
const hiddenCount = computed(() =>
Math.max(0, summaries.value.length - PREVIEW_LIMIT),
);
const cueMeta = computed(() => {
switch (activityCue.value) {
case 'overdue':
return { color: token.value.colorError, title: 'فعالیت عقب‌افتاده' };
case 'done':
return { color: token.value.colorSuccess, title: 'فعالیت انجام‌شده' };
case 'none':
return { color: token.value.colorWarning, title: 'بدون فعالیت — افزودن' };
default:
return { color: token.value.colorTextSecondary, title: 'فعالیت‌های معامله' };
}
});
const typeOptions = computed(() =>
(Object.entries(ACTIVITY_TYPE_LABELS) as Array<[ActivityType, string]>)
.filter(([value]) => value !== 'note')
.map(([value, label]) => ({ value, label })),
);
const fieldItemStyle = computed(() => ({
marginBottom: 0,
width: '100%',
}));
const panelTitle = computed(() =>
mode.value === 'list' ? 'فعالیت‌های معامله' : 'ایجاد فعالیت سریع',
);
watch(
() => [props.deal.activityCue, props.deal.activitySummaries] as const,
() => {
localCue.value = null;
localSummaries.value = null;
},
);
function resetForm() {
title.value = `پیگیری: ${props.deal.title}`;
type.value = 'task';
dueDate.value = formatLocalDateInput(new Date());
dueTime.value = '';
error.value = '';
}
function cueDotColor(cue: Exclude<DealActivityCue, 'none'>) {
if (cue === 'overdue') return token.value.colorError;
if (cue === 'done') return token.value.colorSuccess;
return token.value.colorTextSecondary;
}
function activityWhen(item: DealActivitySummaryDto) {
if (!item.dueAt) return 'بدون موعد';
const d = new Date(item.dueAt);
if (Number.isNaN(d.getTime())) return '—';
const day = formatRelativeDayLabel(item.dueAt);
return `${day} · ${formatClockFa(d)}`;
}
function cardEl() {
return document.querySelector<HTMLElement>(
`.ant-card[data-card-id="${CSS.escape(props.deal.id)}"]`,
);
}
function columnScroller(el: HTMLElement) {
let node = el.parentElement;
while (node) {
const style = getComputedStyle(node);
const scrolls = style.overflowY === 'auto' || style.overflowY === 'scroll';
if (scrolls && node.scrollHeight > node.clientHeight + 2) return node;
node = node.parentElement;
}
return null;
}
function panelExtent() {
const content = panelEl.value?.scrollHeight ?? 0;
return content > 80 ? content : 360;
}
function liftColumn(el: HTMLElement, cardTop: number, height: number, vh: number) {
const overflow = cardTop + height - (vh - VIEW_PAD);
if (overflow <= 8) return;
const scroller = columnScroller(el);
if (!scroller) return;
const room = scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop;
const delta = Math.min(overflow, Math.max(0, room));
if (delta <= 8) return;
const motion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
? 'auto'
: 'smooth';
scroller.scrollBy({ top: delta, behavior: motion });
}
function measure() {
const el = cardEl();
if (!el) return;
let rect = el.getBoundingClientRect();
if (rect.width < 8) return;
const vw = window.innerWidth;
const vh = window.innerHeight;
const width = Math.min(360, vw - 24);
const gap = 10;
const side: 'left' | 'right' = rect.left >= vw - rect.right ? 'left' : 'right';
let left = side === 'left' ? rect.left - gap - width : rect.right + gap;
left = Math.max(12, Math.min(left, vw - width - 12));
const height = Math.min(panelExtent(), Math.max(200, vh - VIEW_PAD * 2));
if (reveal) {
reveal = false;
liftColumn(el, rect.top, height, vh);
rect = el.getBoundingClientRect();
}
let top = rect.top;
const maxTop = vh - VIEW_PAD - height;
if (top > maxTop) top = Math.max(VIEW_PAD, maxTop);
if (top < VIEW_PAD) top = VIEW_PAD;
const maxHeight = Math.max(200, vh - VIEW_PAD - top);
const travel = Math.min(100, Math.round(width * 0.28));
frame.value = { left, top, width, maxHeight, shift: side === 'left' ? travel : -travel };
}
const panelStyle = computed(() => ({
position: 'fixed' as const,
zIndex: 1050,
top: `${frame.value.top}px`,
left: `${frame.value.left}px`,
width: `${frame.value.width}px`,
maxHeight: `${frame.value.maxHeight}px`,
overflow: 'auto' as const,
boxSizing: 'border-box' as const,
padding: `${token.value.padding}px`,
background: token.value.colorBgElevated,
color: token.value.colorText,
border: `1px solid ${token.value.colorBorderSecondary}`,
borderRadius: `${token.value.borderRadiusLG}px`,
boxShadow: token.value.boxShadowSecondary,
transform: placed.value ? 'translate3d(0, 0, 0)' : `translate3d(${frame.value.shift}px, 0, 0)`,
opacity: placed.value ? 1 : 0,
transition: 'transform 220ms cubic-bezier(.2, .8, .2, 1), opacity 180ms ease',
pointerEvents: placed.value ? ('auto' as const) : ('none' as const),
}));
function setOpen(next: boolean) {
if (open.value === next) return;
open.value = next;
emit('update:open', next);
}
function toggleOpen() {
if (props.disabled) return;
setOpen(!open.value);
}
function close() {
setOpen(false);
}
function openCreate() {
mode.value = 'create';
resetForm();
void nextTick().then(() => measure());
}
function backToList() {
mode.value = 'list';
error.value = '';
void nextTick().then(() => measure());
}
function goActivity(id: string) {
close();
void router.push({ name: 'activity-detail', params: { id } });
}
function onViewport() {
if (open.value) measure();
}
function onPointerDown(event: PointerEvent) {
if (!open.value || !placed.value) return;
const target = event.target;
if (!(target instanceof Node)) return;
if (panelEl.value?.contains(target)) return;
if (
target instanceof Element &&
target.closest('.ant-select-dropdown, #jalali-picker, .layer')
) {
return;
}
const card = cardEl();
if (card?.contains(target)) return;
close();
}
function onKey(event: KeyboardEvent) {
if (event.key === 'Escape' && open.value) close();
}
watch(open, async (isOpen) => {
if (!isOpen) {
placed.value = false;
window.clearTimeout(hideTimer);
hideTimer = window.setTimeout(() => {
if (!open.value) rendered.value = false;
}, 230);
return;
}
window.clearTimeout(hideTimer);
listExpanded.value = false;
mode.value = summaries.value.length ? 'list' : 'create';
resetForm();
rendered.value = true;
reveal = true;
measure();
await nextTick();
measure();
requestAnimationFrame(() => {
requestAnimationFrame(() => {
if (open.value) {
placed.value = true;
void nextTick().then(() => measure());
}
});
});
});
onMounted(() => {
window.addEventListener('resize', onViewport);
window.addEventListener('scroll', onViewport, true);
document.addEventListener('pointerdown', onPointerDown, true);
document.addEventListener('keydown', onKey);
});
onBeforeUnmount(() => {
window.removeEventListener('resize', onViewport);
window.removeEventListener('scroll', onViewport, true);
document.removeEventListener('pointerdown', onPointerDown, true);
document.removeEventListener('keydown', onKey);
window.clearTimeout(hideTimer);
});
function dueAtIso(): string | null {
if (!dueDate.value) return null;
const time = dueTime.value.trim() || '10:30';
const due = new Date(`${dueDate.value}T${time}:00`);
return Number.isNaN(due.getTime()) ? null : due.toISOString();
}
function fullFormQuery() {
const query: Record<string, string> = { dealId: props.deal.id };
if (props.deal.personId) query.personId = props.deal.personId;
if (props.deal.companyId) query.companyId = props.deal.companyId;
if (title.value.trim()) query.title = title.value.trim();
if (type.value) query.type = type.value;
if (dueAtIso()) query.dueAt = dueAtIso()!;
return query;
}
function goFullForm() {
close();
void router.push({ name: 'activity-new', query: fullFormQuery() });
}
async function submit() {
error.value = '';
if (title.value.trim().length < 2) {
error.value = 'عنوان فعالیت را بنویسید.';
return;
}
const dueAt = dueAtIso();
if (!dueDate.value || !dueAt) {
error.value = 'تاریخ فعالیت را مشخص کنید.';
return;
}
const body: CreateActivityRequest = {
title: title.value.trim(),
type: type.value,
dueAt,
dealId: props.deal.id,
personId: props.deal.personId || null,
companyId: props.deal.companyId || null,
assigneeId: props.deal.ownerId || null,
};
saving.value = true;
try {
const { data } = await api.post<ActivityDto>('/activities', body);
message.success('فعالیت ثبت شد');
const dueMs = new Date(dueAt).getTime();
const cue: Exclude<DealActivityCue, 'none'> =
Number.isFinite(dueMs) && dueMs < Date.now() ? 'overdue' : 'upcoming';
const created: DealActivitySummaryDto = {
id: data.id,
title: data.title,
type: data.type,
status: data.status === 'done' ? 'done' : 'open',
dueAt: data.dueAt,
cue,
};
const next = [created, ...summaries.value.filter((item) => item.id !== created.id)];
localSummaries.value = next;
localCue.value =
next.some((item) => item.cue === 'overdue')
? 'overdue'
: next.some((item) => item.status === 'open')
? 'upcoming'
: next.some((item) => item.cue === 'done')
? 'done'
: 'none';
mode.value = 'list';
void nextTick().then(() => measure());
} catch {
error.value = 'ثبت فعالیت ناموفق بود.';
} finally {
saving.value = false;
}
}
</script>
<template>
<a-tooltip :title="cueMeta.title">
<a-badge
:count="openCount"
:offset="[-2, 2]"
:number-style="{ fontSize: '10px', minWidth: '16px', height: '16px', lineHeight: '16px' }"
>
<a-button
type="text"
:disabled="disabled"
aria-label="فعالیت‌های معامله"
:aria-expanded="open"
:style="{
color: open ? token.colorPrimary : cueMeta.color,
width: '28px',
minWidth: '28px',
height: '28px',
padding: 0,
}"
@click.stop="toggleOpen"
@mousedown.stop
@dragstart.stop.prevent
>
<template #icon><CalendarOutlined /></template>
</a-button>
</a-badge>
</a-tooltip>
<Teleport to="body">
<div
v-if="rendered"
ref="panelEl"
role="dialog"
dir="rtl"
:aria-label="`${panelTitle} برای ${deal.title}`"
:style="panelStyle"
>
<a-flex justify="space-between" align="center" :style="{ marginBottom: `${token.marginSM}px` }">
<a-typography-title :level="5" :style="{ margin: 0 }">{{ panelTitle }}</a-typography-title>
<a-space :size="4">
<a-button
v-if="mode === 'list'"
type="text"
aria-label="فعالیت جدید"
@click="openCreate"
>
<template #icon><PlusOutlined /></template>
</a-button>
<a-button type="text" aria-label="بستن" @click="close">
<template #icon><CloseOutlined /></template>
</a-button>
</a-space>
</a-flex>
<template v-if="mode === 'list'">
<a-flex vertical :gap="8">
<a-card
v-for="item in visibleSummaries"
:key="item.id"
hoverable
:bordered="true"
:body-style="{ padding: '10px 12px' }"
@click="goActivity(item.id)"
>
<a-flex align="flex-start" :gap="10">
<span
aria-hidden="true"
:style="{
width: '8px',
height: '8px',
marginTop: '6px',
borderRadius: '999px',
background: cueDotColor(item.cue),
flexShrink: 0,
}"
/>
<div :style="{ minWidth: 0, flex: 1 }">
<a-typography-text strong :style="{ display: 'block' }">
{{ item.title }}
</a-typography-text>
<a-typography-text type="secondary" :style="{ fontSize: `${token.fontSizeSM}px` }">
{{ ACTIVITY_TYPE_LABELS[item.type] || item.type }}
·
{{ activityWhen(item) }}
</a-typography-text>
</div>
</a-flex>
</a-card>
<a-typography-link
v-if="!listExpanded && hiddenCount > 0"
@click="listExpanded = true"
>
مشاهده همه ({{ toFaDigits(summaries.length) }})
</a-typography-link>
</a-flex>
</template>
<a-flex v-else vertical :gap="token.marginSM">
<a-alert v-if="error" type="error" show-icon :message="error" />
<a-form-item label="عنوان" :style="fieldItemStyle">
<a-input v-model:value="title" placeholder="عنوان فعالیت" allow-clear />
</a-form-item>
<a-form-item label="نوع" :style="fieldItemStyle">
<a-select v-model:value="type" :options="typeOptions" style="width: 100%" />
</a-form-item>
<a-row :gutter="[12, 12]" align="top">
<a-col :span="12">
<a-form-item label="تاریخ" :style="fieldItemStyle">
<JalaliDateInput v-model="dueDate" placeholder="تاریخ" style="width: 100%" />
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="ساعت" :style="fieldItemStyle">
<JalaliDateInput
v-model="dueTime"
mode="time"
placeholder="اختیاری"
style="width: 100%"
/>
</a-form-item>
</a-col>
</a-row>
<a-divider :style="{ margin: `${token.marginXS}px 0` }" />
<a-flex justify="space-between" align="center" wrap="wrap" :gap="8">
<a-space :size="8">
<a-typography-link v-if="summaries.length" @click="backToList">
بازگشت به لیست
</a-typography-link>
<a-typography-link @click="goFullForm">
<FormOutlined />
فرم کامل
</a-typography-link>
</a-space>
<a-space :size="8">
<a-button :disabled="saving" @click="summaries.length ? backToList() : close()">
انصراف
</a-button>
<a-button type="primary" :loading="saving" @click="submit">ذخیره</a-button>
</a-space>
</a-flex>
</a-flex>
</div>
</Teleport>
</template>
@@ -15,11 +15,13 @@ import {
Space as ASpace, Space as ASpace,
Table as ATable, Table as ATable,
Tag as ATag, Tag as ATag,
Tooltip as ATooltip,
Typography, Typography,
theme, theme,
} from 'ant-design-vue'; } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue'; import type { TableColumnsType } from 'ant-design-vue';
import TableColumnsMenu from '@/components/TableColumnsMenu.vue'; import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
import { formatJalaliNumeric } from '@/lib/jalali';
import type { import type {
PipelineAccent, PipelineAccent,
PipelineDeal, PipelineDeal,
@@ -82,6 +84,13 @@ function money(deal: PipelineDeal) {
return formatCurrencyParts(deal.amount ?? 0, deal.currencyUnit ?? 'ریال'); return formatCurrencyParts(deal.amount ?? 0, deal.currencyUnit ?? 'ریال');
} }
function dateHint(deal: PipelineDeal) {
if (!deal.dateIso) return deal.date;
const d = new Date(deal.dateIso);
if (Number.isNaN(d.getTime())) return deal.date;
return formatJalaliNumeric(d);
}
const hideAmount = computed(() => Boolean(props.copy.hideAmount)); const hideAmount = computed(() => Boolean(props.copy.hideAmount));
const tableKey = computed(() => (hideAmount.value ? 'pipeline.leads' : 'pipeline.deals')); const tableKey = computed(() => (hideAmount.value ? 'pipeline.leads' : 'pipeline.deals'));
@@ -213,10 +222,12 @@ onUnmounted(() => {
</span> </span>
</template> </template>
<template v-else-if="column.key === 'date'"> <template v-else-if="column.key === 'date'">
<a-tooltip :title="dateHint(record.deal)">
<a-space :size="6"> <a-space :size="6">
<CalendarOutlined /> <CalendarOutlined />
<span>{{ record.deal.date }}</span> <span>{{ record.deal.date }}</span>
</a-space> </a-space>
</a-tooltip>
</template> </template>
<template v-else-if="column.key === 'actions'"> <template v-else-if="column.key === 'actions'">
<span :data-card-id="record.deal.id"> <span :data-card-id="record.deal.id">
@@ -334,10 +345,12 @@ onUnmounted(() => {
{{ row.stageTitle }} {{ row.stageTitle }}
</a-tag> </a-tag>
<a-flex justify="space-between" align="center"> <a-flex justify="space-between" align="center">
<a-tooltip :title="dateHint(row.deal)">
<a-space :size="6"> <a-space :size="6">
<CalendarOutlined /> <CalendarOutlined />
<a-typography-text type="secondary">{{ row.deal.date }}</a-typography-text> <a-typography-text type="secondary">{{ row.deal.date }}</a-typography-text>
</a-space> </a-space>
</a-tooltip>
<span v-if="!hideAmount" dir="ltr"> <span v-if="!hideAmount" dir="ltr">
<a-typography-text strong>{{ money(row.deal).number }}</a-typography-text> <a-typography-text strong>{{ money(row.deal).number }}</a-typography-text>
<a-typography-text type="secondary" :style="{ marginInlineStart: '6px' }"> <a-typography-text type="secondary" :style="{ marginInlineStart: '6px' }">
@@ -24,9 +24,9 @@ import {
} from 'ant-design-vue'; } from 'ant-design-vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { import {
ENTITY_TYPE_LABELS, ENTITY_TYPE_LABELS,
PRIORITY_LABELS,
ROUTINES_CTX, ROUTINES_CTX,
apiError, apiError,
localInputToIso, localInputToIso,
@@ -68,10 +68,10 @@ const form = reactive({
const saving = ref(false); const saving = ref(false);
const error = ref(''); const error = ref('');
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const priorityOptions = computed(() => const priorityOptions = computed(() =>
(Object.entries(PRIORITY_LABELS) as Array<[ActivityPriority, string]>).map( activityPriorities.items.value.map((row) => ({ value: row.key, label: row.label })),
([value, label]) => ({ value, label }),
),
); );
const categoryOptions = computed(() => [ const categoryOptions = computed(() => [
@@ -25,9 +25,9 @@ import { api } from '@/lib/api';
import { canAssignToOthers } from '@/lib/assign-access'; import { canAssignToOthers } from '@/lib/assign-access';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import { formatJalaliDayClock } from '@/lib/jalali'; import { formatJalaliDayClock } from '@/lib/jalali';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { import {
ENTITY_TYPE_LABELS, ENTITY_TYPE_LABELS,
PRIORITY_LABELS,
PRIORITY_VARIANTS, PRIORITY_VARIANTS,
ROUTINES_CTX, ROUTINES_CTX,
ROUTINE_ENTITY_LINK_LABELS, ROUTINE_ENTITY_LINK_LABELS,
@@ -108,7 +108,11 @@ const done = computed(() => task.value?.status === 'completed');
const auth = useAuthStore(); const auth = useAuthStore();
const canManage = computed(() => !!shell?.context.value?.isManager); const canManage = computed(() => !!shell?.context.value?.isManager);
const canAssignOthers = computed(() => canAssignToOthers(auth.user, 'routines')); const canAssignOthers = computed(() => canAssignToOthers(auth.user, 'routines'));
const priorities = Object.entries(PRIORITY_LABELS) as Array<[ActivityPriority, string]>; const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const priorities = computed(() =>
activityPriorities.items.value.map((r) => [r.key, r.label] as [ActivityPriority, string]),
);
function startEdit() { function startEdit() {
const t = task.value; const t = task.value;
@@ -193,7 +197,7 @@ function eventText(ev: RoutineTaskEventDto): string {
<div class="badges"> <div class="badges">
<UiBadge :variant="STATUS_VARIANTS[task.status]">{{ ROUTINE_TASK_STATUS_LABELS[task.status] }}</UiBadge> <UiBadge :variant="STATUS_VARIANTS[task.status]">{{ ROUTINE_TASK_STATUS_LABELS[task.status] }}</UiBadge>
<UiBadge :variant="PRIORITY_VARIANTS[task.priority]" size="sm"> <UiBadge :variant="PRIORITY_VARIANTS[task.priority]" size="sm">
اولویت {{ PRIORITY_LABELS[task.priority] }} اولویت {{ activityPriorities.labelOf(task.priority) }}
</UiBadge> </UiBadge>
<UiBadge v-if="task.isMandatory" variant="warning" size="sm">اجباری</UiBadge> <UiBadge v-if="task.isMandatory" variant="warning" size="sm">اجباری</UiBadge>
</div> </div>
@@ -23,9 +23,9 @@ import {
const AMenuItem = AMenu.Item; const AMenuItem = AMenu.Item;
import UserAvatar from '@/components/UserAvatar.vue'; import UserAvatar from '@/components/UserAvatar.vue';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { import {
ENTITY_TYPE_LABELS, ENTITY_TYPE_LABELS,
PRIORITY_LABELS,
ROUTINE_TASK_SOURCE_LABELS, ROUTINE_TASK_SOURCE_LABELS,
ROUTINE_TASK_STATUS_LABELS, ROUTINE_TASK_STATUS_LABELS,
entityRoute, entityRoute,
@@ -64,6 +64,9 @@ const emit = defineEmits<{
action: [kind: RoutineTaskRowAction, task: RoutineTaskDto]; action: [kind: RoutineTaskRowAction, task: RoutineTaskDto];
}>(); }>();
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const done = computed(() => props.task.status === 'completed'); const done = computed(() => props.task.status === 'completed');
const closed = computed(() => props.task.status === 'skipped' || props.task.status === 'cancelled'); const closed = computed(() => props.task.status === 'skipped' || props.task.status === 'cancelled');
const open = computed(() => isOpenStatus(props.task.status)); const open = computed(() => isOpenStatus(props.task.status));
@@ -150,7 +153,7 @@ function onMenuClick({ key }: { key: string | number }) {
<CheckOutlined /> {{ formatTime(task.completedAt) }} <CheckOutlined /> {{ formatTime(task.completedAt) }}
</a-typography-text> </a-typography-text>
<a-tag v-if="task.category" :bordered="false">{{ task.category.name }}</a-tag> <a-tag v-if="task.category" :bordered="false">{{ task.category.name }}</a-tag>
<a-tag :bordered="false">{{ PRIORITY_LABELS[task.priority] }}</a-tag> <a-tag :bordered="false">{{ activityPriorities.labelOf(task.priority) }}</a-tag>
<a-tag v-if="task.status !== 'todo'" :bordered="false"> <a-tag v-if="task.status !== 'todo'" :bordered="false">
{{ ROUTINE_TASK_STATUS_LABELS[task.status] }} {{ ROUTINE_TASK_STATUS_LABELS[task.status] }}
</a-tag> </a-tag>
@@ -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,594 @@
<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,
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 { useTreasuryMobile } from '@/views/treasury/useTreasuryMobile';
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 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) {
Modal.confirm({
title: 'ابطال سند',
content: 'این سند و گردش متصل به آن باطل شود؟',
okText: 'ابطال',
okType: 'danger',
cancelText: 'انصراف',
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) {
Modal.confirm({
title: 'حذف سند',
content:
row.status === 'void'
? 'سند باطل‌شده برای همیشه حذف شود؟'
: 'سند بدون گردش برای همیشه حذف شود؟ در صورت داشتن دریافت/پرداخت ابتدا ابطال کنید.',
okText: 'حذف',
okType: 'danger',
cancelText: 'انصراف',
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() {
emit('reload');
}
function asDoc(record: unknown): FinancialDocumentDto {
return record as FinancialDocumentDto;
}
</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="rows"
: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 rows" :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>
</a-card>
<a-modal
v-model:open="detailOpen"
title="جزئیات سند"
:footer="null"
:width="isMobile ? '100%' : 720"
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"
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>
+37 -2
View File
@@ -184,8 +184,43 @@ function onSizeChange(e: Event) {
@media (max-width: 900px) { @media (max-width: 900px) {
.ui-pagination { .ui-pagination {
flex-direction: column; flex-direction: column;
align-items: center; align-items: stretch;
gap: var(--sp-3); gap: 0.65rem;
}
.pagination-info {
width: 100%;
flex-wrap: nowrap;
justify-content: space-between;
gap: 0.35rem;
font-size: 0.78rem;
}
.page-count {
flex: 0 1 auto;
white-space: nowrap;
}
.size-picker {
margin-inline-start: 0;
flex: 0 0 auto;
gap: 0.25rem;
white-space: nowrap;
}
.size-picker span:last-child {
display: none;
}
.size-picker select {
height: 28px;
min-width: 3.25rem;
padding: 0 0.3rem;
}
.pagination-controls {
width: 100%;
justify-content: center;
} }
} }
</style> </style>
+43
View File
@@ -0,0 +1,43 @@
import type { ActivityDto, ActivityEditPolicy } from '@mento/shared';
type ActivityAccessUser = {
id?: string | null;
role?: string | null;
} | null | undefined;
type ActivityAccessRow = Pick<
ActivityDto,
'editPolicy' | 'createdBy' | 'assignee' | 'assignees'
> | null | undefined;
function isAssignee(
activity: NonNullable<ActivityAccessRow>,
userId: string,
): boolean {
if (activity.assignee?.id === userId) return true;
return (activity.assignees ?? []).some((a) => a.id === userId);
}
/** ویرایش/حذف فیلدهای فعالیت — انجام/جابه‌جایی ستون جداست */
export function canMutateActivity(
activity: ActivityAccessRow,
user: ActivityAccessUser,
): boolean {
if (!activity || !user?.id) return false;
if (user.role === 'owner' || user.role === 'admin') return true;
if (activity.createdBy?.id === user.id) return true;
const policy: ActivityEditPolicy = activity.editPolicy ?? 'creator';
if (policy !== 'assignees') return false;
return isAssignee(activity, user.id);
}
/** ثبت نظر و تعویق برای همهٔ مسئولان (حتی وقتی ویرایش فقط با ایجادکننده است) */
export function canCollaborateOnActivity(
activity: ActivityAccessRow,
user: ActivityAccessUser,
): boolean {
if (!activity || !user?.id) return false;
if (user.role === 'owner' || user.role === 'admin') return true;
if (activity.createdBy?.id === user.id) return true;
return isAssignee(activity, user.id);
}
+67
View File
@@ -0,0 +1,67 @@
import { computed, ref } from 'vue';
import type { ActivityPriority, ActivityPrioritySetting } from '@mento/shared';
import {
DEFAULT_ACTIVITY_PRIORITY_SETTINGS,
parseActivityPrioritySettings,
} from '@mento/shared';
import { api } from '@/lib/api';
const items = ref<ActivityPrioritySetting[]>([...DEFAULT_ACTIVITY_PRIORITY_SETTINGS]);
const loaded = ref(false);
let pending: Promise<void> | null = null;
/** تنظیمات اولویت فعالیت/روتین (کش مشترک) */
export function useActivityPriorities() {
async function load(force = false): Promise<void> {
if (loaded.value && !force) return;
if (pending && !force) return pending;
pending = api
.get<ActivityPrioritySetting[]>('/activities/priorities')
.then(({ data }) => {
items.value = parseActivityPrioritySettings(data);
loaded.value = true;
})
.catch(() => {
if (!loaded.value) items.value = [...DEFAULT_ACTIVITY_PRIORITY_SETTINGS];
})
.finally(() => {
pending = null;
});
return pending;
}
const byKey = computed(() => {
const map = new Map<ActivityPriority, ActivityPrioritySetting>();
for (const row of items.value) map.set(row.key, row);
return map;
});
const labels = computed(() => {
const out = {} as Record<ActivityPriority, string>;
for (const row of items.value) out[row.key] = row.label;
return out;
});
const colors = computed(() => {
const out = {} as Record<ActivityPriority, string>;
for (const row of items.value) out[row.key] = row.color;
return out;
});
function labelOf(key: ActivityPriority | string | null | undefined): string {
if (!key) return '—';
return byKey.value.get(key as ActivityPriority)?.label ?? String(key);
}
function colorOf(key: ActivityPriority | string | null | undefined): string {
if (!key) return '#94a3b8';
return byKey.value.get(key as ActivityPriority)?.color ?? '#94a3b8';
}
function setLocal(next: ActivityPrioritySetting[]) {
items.value = parseActivityPrioritySettings(next);
loaded.value = true;
}
return { items, byKey, labels, colors, loaded, load, labelOf, colorOf, setLocal };
}
+11
View File
@@ -226,6 +226,17 @@ export function formatRelativeContact(iso: string | null | undefined): string {
return `${toFaDigits(days)} روز پیش`; return `${toFaDigits(days)} روز پیش`;
} }
/** تاریخ نسبی تقویمی برای کارت‌ها: امروز / ۳ روز عقب افتاده / ۵ روز مانده */
export function formatRelativeDayLabel(iso: string | null | undefined): string {
if (!iso) return '—';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '—';
const daysAhead = calendarDaysBetween(new Date(), d);
if (daysAhead === 0) return 'امروز';
if (daysAhead > 0) return `${toFaDigits(daysAhead)} روز مانده`;
return `${toFaDigits(-daysAhead)} روز عقب افتاده`;
}
/** فعالیت بعدی: امروز ۱۶:۳۰ / فردا ۱۰:۰۰ / ۲۴ مرداد ۱۱:۲۰ */ /** فعالیت بعدی: امروز ۱۶:۳۰ / فردا ۱۰:۰۰ / ۲۴ مرداد ۱۱:۲۰ */
export function formatNextSlot(iso: string | null | undefined): string { export function formatNextSlot(iso: string | null | undefined): string {
if (!iso) return '—'; if (!iso) return '—';
+29 -3
View File
@@ -1,6 +1,11 @@
import { currencySuffix } from '@/lib/money'; import { currencySuffix } from '@/lib/money';
import { matchesSearch } from '@/lib/search'; import { matchesSearch } from '@/lib/search';
import type { ActivityPriority } from '@mento/shared'; import type {
ActivityPriority,
ActivityStatus,
DealActivityCue,
DealActivitySummaryDto,
} from '@mento/shared';
export type PipelineAccent = 'green' | 'orange' | 'purple' | 'blue' | 'rose' | 'slate'; export type PipelineAccent = 'green' | 'orange' | 'purple' | 'blue' | 'rose' | 'slate';
@@ -10,6 +15,8 @@ export type PipelineDeal = {
description: string; description: string;
amount: number | null; amount: number | null;
date: string; date: string;
/** ISO برای tooltip تاریخ مطلق */
dateIso?: string;
initials: string; initials: string;
/** شناسه مرحله فعلی — هنگام جابه‌جایی به‌روز می‌شود */ /** شناسه مرحله فعلی — هنگام جابه‌جایی به‌روز می‌شود */
stageId?: string; stageId?: string;
@@ -20,10 +27,18 @@ export type PipelineDeal = {
assigneeNames?: string[]; assigneeNames?: string[];
ownerId?: string | null; ownerId?: string | null;
assigneeIds?: string[]; assigneeIds?: string[];
personId?: string | null;
companyId?: string | null;
/** متن‌های قابل جستجو (مشتری، شرکت، یادداشت، مسئولان …) */ /** متن‌های قابل جستجو (مشتری، شرکت، یادداشت، مسئولان …) */
searchFields?: Array<string | null | undefined>; searchFields?: Array<string | null | undefined>;
/** اولویت فعالیت؛ فقط روی کارت فعالیت نشان داده می‌شود */ /** اولویت فعالیت؛ فقط روی کارت فعالیت نشان داده می‌شود */
priority?: ActivityPriority; priority?: ActivityPriority;
/** وضعیت فعالیت (برای کارت کانبان فعالیت: انجام‌شده و …) */
activityStatus?: ActivityStatus;
/** نشانگر وضعیت فعالیت معامله روی دکمهٔ تقویم */
activityCue?: DealActivityCue;
/** خلاصه فعالیت‌ها برای پاپ‌آپ دکمهٔ تقویم */
activitySummaries?: DealActivitySummaryDto[];
}; };
export type PipelineUiCopy = { export type PipelineUiCopy = {
@@ -36,6 +51,8 @@ export type PipelineUiCopy = {
hideAmount?: boolean; hideAmount?: boolean;
/** کارت فعالیت: پرچم کنار عنوان و پنجرهٔ خلاصه به‌جای ورود مستقیم به جزئیات */ /** کارت فعالیت: پرچم کنار عنوان و پنجرهٔ خلاصه به‌جای ورود مستقیم به جزئیات */
quickView?: boolean; quickView?: boolean;
/** گوشه کارت: ایجاد سریع فعالیت برای معامله */
quickActivity?: boolean;
}; };
export const DEAL_BOARD_COPY: PipelineUiCopy = { export const DEAL_BOARD_COPY: PipelineUiCopy = {
@@ -45,6 +62,7 @@ export const DEAL_BOARD_COPY: PipelineUiCopy = {
addItemAria: 'افزودن معامله به این مرحله', addItemAria: 'افزودن معامله به این مرحله',
itemMenuAria: 'گزینه‌های معامله', itemMenuAria: 'گزینه‌های معامله',
listColTitle: 'معامله', listColTitle: 'معامله',
quickActivity: true,
}; };
export const PROJECT_BOARD_COPY: PipelineUiCopy = { export const PROJECT_BOARD_COPY: PipelineUiCopy = {
@@ -185,8 +203,10 @@ export function mapBoardToStages(
expectedCloseAt: string | null; expectedCloseAt: string | null;
createdAt: string; createdAt: string;
promotedFromPriorAt: string | null; promotedFromPriorAt: string | null;
person: { fullName: string } | null; activityCue?: DealActivityCue;
company: { name: string } | null; activitySummaries?: DealActivitySummaryDto[];
person: { id?: string; fullName: string } | null;
company: { id?: string; name: string } | null;
owner?: { id: string; fullName: string } | null; owner?: { id: string; fullName: string } | null;
assignees?: Array<{ id: string; fullName: string }>; assignees?: Array<{ id: string; fullName: string }>;
}>; }>;
@@ -229,6 +249,9 @@ export function mapBoardToStages(
description, description,
amount: deal.amount ?? 0, amount: deal.amount ?? 0,
date: formatDate(dateIso), date: formatDate(dateIso),
dateIso,
activityCue: deal.activityCue ?? 'none',
activitySummaries: deal.activitySummaries ?? [],
initials: initialsFromTitle( initials: initialsFromTitle(
deal.company?.name || deal.title, deal.company?.name || deal.title,
), ),
@@ -239,6 +262,8 @@ export function mapBoardToStages(
assigneeNames, assigneeNames,
ownerId: deal.owner?.id ?? null, ownerId: deal.owner?.id ?? null,
assigneeIds: (deal.assignees ?? []).map((a) => a.id), assigneeIds: (deal.assignees ?? []).map((a) => a.id),
personId: deal.person?.id ?? null,
companyId: deal.company?.id ?? null,
searchFields: [ searchFields: [
deal.notes, deal.notes,
deal.company?.name, deal.company?.name,
@@ -294,6 +319,7 @@ export function mapProjectBoardToStages(
'', '',
amount: null, amount: null,
date: formatDate(card.createdAt), date: formatDate(card.createdAt),
dateIso: card.createdAt,
initials: initialsFromTitle( initials: initialsFromTitle(
card.company?.name || card.person?.fullName || card.title, card.company?.name || card.person?.fullName || card.title,
), ),
+1
View File
@@ -29,6 +29,7 @@ export {
type BadgeVariant = 'neutral' | 'accent' | 'success' | 'warning' | 'danger' | 'info'; type BadgeVariant = 'neutral' | 'accent' | 'success' | 'warning' | 'danger' | 'info';
/** پیش‌فرض؛ برای نمایش زنده از useActivityPriorities استفاده کنید */
export const PRIORITY_LABELS: Record<ActivityPriority, string> = { export const PRIORITY_LABELS: Record<ActivityPriority, string> = {
very_low: 'خیلی کم', very_low: 'خیلی کم',
low: 'کم', low: 'کم',
+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;
}
+110 -39
View File
@@ -25,6 +25,7 @@ import ActivityDeskFilters from '@/components/activities/ActivityDeskFilters.vue
import ActivityStagesManager from '@/components/activities/ActivityStagesManager.vue'; import ActivityStagesManager from '@/components/activities/ActivityStagesManager.vue';
import ActivityTypesManager from '@/components/activities/ActivityTypesManager.vue'; import ActivityTypesManager from '@/components/activities/ActivityTypesManager.vue';
import { PIPELINE_ACCENT } from '@/lib/pipeline-board'; import { PIPELINE_ACCENT } from '@/lib/pipeline-board';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { activityTypeView, typeColorStyle, useActivityTypes } from '@/lib/activity-types'; import { activityTypeView, typeColorStyle, useActivityTypes } from '@/lib/activity-types';
import { import {
ACTIVITY_EXCEL_ALIASES, ACTIVITY_EXCEL_ALIASES,
@@ -42,6 +43,7 @@ import type {
ActivityBoardDto, ActivityBoardDto,
ActivityDto, ActivityDto,
ActivityFilter, ActivityFilter,
ActivityPriority,
ActivityStageCountsDto, ActivityStageCountsDto,
ActivityStageDto, ActivityStageDto,
ActivityStatus, ActivityStatus,
@@ -50,9 +52,12 @@ import type {
OrgUserDto, OrgUserDto,
PaginatedResponse, PaginatedResponse,
} from '@mento/shared'; } from '@mento/shared';
import { brand } from '@mento/shared'; import { ACTIVITY_PRIORITY_KEYS, brand } from '@mento/shared';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import { canMutateActivity } from '@/lib/activity-access';
import { canManageSettings, canViewAllRecords } from '@/lib/roles'; import { canManageSettings, canViewAllRecords } from '@/lib/roles';
import { apiError } from '@/lib/routines';
import { message } from 'ant-design-vue';
import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize'; import { PAGE_SIZE_OPTIONS, usePageSize } from '@/lib/pageSize';
import { registerTableColumns, useTableColumns } from '@/lib/tableColumns'; import { registerTableColumns, useTableColumns } from '@/lib/tableColumns';
import TableColumnsMenu from '@/components/TableColumnsMenu.vue'; import TableColumnsMenu from '@/components/TableColumnsMenu.vue';
@@ -91,6 +96,7 @@ const actGridStyle = computed(() => ({
/** 'all' یا شناسهٔ نوع فعالیت */ /** 'all' یا شناسهٔ نوع فعالیت */
type TypeFilter = string; type TypeFilter = string;
type PriorityFilter = 'all' | ActivityPriority;
type StatusFilter = 'all' | ActivityStatus; type StatusFilter = 'all' | ActivityStatus;
type UiStatus = 'done' | 'progress' | 'planned' | 'overdue' | 'canceled'; type UiStatus = 'done' | 'progress' | 'planned' | 'overdue' | 'canceled';
type DeskScope = 'mine' | 'team'; type DeskScope = 'mine' | 'team';
@@ -118,6 +124,18 @@ const STATUS_FILTERS: Array<{ key: StatusFilter; label: string }> = [
{ key: 'canceled', label: 'لغو شده' }, { key: 'canceled', label: 'لغو شده' },
]; ];
const activityPriorities = useActivityPriorities();
const PRIORITY_FILTERS = computed<
Array<{ key: PriorityFilter; label: string; color?: string }>
>(() => [
{ key: 'all', label: 'همه اولویت‌ها' },
...activityPriorities.items.value.map((row) => ({
key: row.key as PriorityFilter,
label: row.label,
color: row.color,
})),
]);
const pageSize = usePageSize('activities', 10); const pageSize = usePageSize('activities', 10);
const route = useRoute(); const route = useRoute();
@@ -177,6 +195,7 @@ const boardDeleteOpen = ref(false);
async function onTypesChanged() { async function onTypesChanged() {
await activityTypes.load(true); await activityTypes.load(true);
await activityPriorities.load(true);
kanbanReload.value += 1; kanbanReload.value += 1;
await refreshAll(); await refreshAll();
} }
@@ -240,6 +259,13 @@ const statusFilter = computed<StatusFilter>(() => {
: 'all'; : 'all';
}); });
const priorityFilter = computed<PriorityFilter>(() => {
const value = typeof route.query.priority === 'string' ? route.query.priority : 'all';
return ACTIVITY_PRIORITY_KEYS.includes(value as ActivityPriority)
? (value as ActivityPriority)
: 'all';
});
const assigneeFilter = computed(() => const assigneeFilter = computed(() =>
typeof route.query.assigneeId === 'string' ? route.query.assigneeId : '', typeof route.query.assigneeId === 'string' ? route.query.assigneeId : '',
); );
@@ -318,6 +344,7 @@ const sharedParams = computed<Record<string, string | undefined>>(() => ({
? legacyBaseType.value ? legacyBaseType.value
: undefined, : undefined,
status: statusFilter.value === 'all' ? undefined : statusFilter.value, status: statusFilter.value === 'all' ? undefined : statusFilter.value,
priority: priorityFilter.value === 'all' ? undefined : priorityFilter.value,
assigneeId: assigneeFilter.value || undefined, assigneeId: assigneeFilter.value || undefined,
title: titleFilter.value.trim() || undefined, title: titleFilter.value.trim() || undefined,
customer: customerFilter.value.trim() || undefined, customer: customerFilter.value.trim() || undefined,
@@ -330,6 +357,7 @@ function stageDotStyle(s: ActivityStageDto) {
const activeFacetCount = computed(() => { const activeFacetCount = computed(() => {
let n = 0; let n = 0;
if (typeFilter.value !== 'all') n += 1; if (typeFilter.value !== 'all') n += 1;
if (priorityFilter.value !== 'all') n += 1;
if (statusFilter.value !== 'all') n += 1; if (statusFilter.value !== 'all') n += 1;
if (assigneeFilter.value) n += 1; if (assigneeFilter.value) n += 1;
if (titleFilter.value.trim()) n += 1; if (titleFilter.value.trim()) n += 1;
@@ -432,6 +460,7 @@ function deskDetailQuery(columnStageId?: string): Record<string, string> {
if (search) query.q = search; if (search) query.q = search;
if (typeFilter.value !== 'all') query.typeDefId = typeFilter.value; if (typeFilter.value !== 'all') query.typeDefId = typeFilter.value;
if (statusFilter.value !== 'all') query.status = statusFilter.value; if (statusFilter.value !== 'all') query.status = statusFilter.value;
if (priorityFilter.value !== 'all') query.priority = priorityFilter.value;
if (assigneeFilter.value) query.assigneeId = assigneeFilter.value; if (assigneeFilter.value) query.assigneeId = assigneeFilter.value;
if (titleFilter.value.trim()) query.title = titleFilter.value.trim(); if (titleFilter.value.trim()) query.title = titleFilter.value.trim();
if (customerFilter.value.trim()) query.customer = customerFilter.value.trim(); if (customerFilter.value.trim()) query.customer = customerFilter.value.trim();
@@ -446,25 +475,13 @@ function deskDetailQuery(columnStageId?: string): Record<string, string> {
return query; return query;
} }
function activityRoute(id: string, edit = false, columnStageId?: string) { function activityRoute(id: string, columnStageId?: string) {
if (!edit) {
return { return {
name: 'activity-detail' as const, name: 'activity-detail' as const,
params: { id }, params: { id },
query: deskDetailQuery(columnStageId), query: deskDetailQuery(columnStageId),
}; };
} }
const query: Record<string, string> = {};
for (const key of ['board', 'view', 'desk', 'filter', 'stage', 'q', 'typeDefId', 'status', 'assigneeId', 'title', 'customer', 'due'] as const) {
const value = route.query[key];
if (typeof value === 'string' && value) query[key] = value;
}
return {
name: 'activity-edit' as const,
params: { id },
query,
};
}
function setBoard(next: string) { function setBoard(next: string) {
void router.replace({ void router.replace({
@@ -782,6 +799,13 @@ function setStatusFilter(next: string) {
patchFacetQuery({ status: value === 'all' ? undefined : value }); patchFacetQuery({ status: value === 'all' ? undefined : value });
} }
function setPriorityFilter(next: string) {
const value: PriorityFilter = ACTIVITY_PRIORITY_KEYS.includes(next as ActivityPriority)
? (next as ActivityPriority)
: 'all';
patchFacetQuery({ priority: value === 'all' ? undefined : value });
}
function setAssigneeFilter(next: string) { function setAssigneeFilter(next: string) {
patchFacetQuery({ patchFacetQuery({
assigneeId: next || undefined, assigneeId: next || undefined,
@@ -806,6 +830,7 @@ function clearFacets() {
type: undefined, type: undefined,
typeDefId: undefined, typeDefId: undefined,
status: undefined, status: undefined,
priority: undefined,
assigneeId: undefined, assigneeId: undefined,
title: undefined, title: undefined,
customer: undefined, customer: undefined,
@@ -938,10 +963,27 @@ function clearSelect() {
selectedIds.value = new Set(); selectedIds.value = new Set();
} }
function canDeleteActivity(item: ActivityDto | null | undefined) {
return canMutateActivity(item, auth.user);
}
function activityById(id: string) {
return (
items.value.find((row) => row.id === id) ||
(boardMenuActivity.value?.id === id ? boardMenuActivity.value : null)
);
}
function askDeleteActivity(id: string, title?: string) { function askDeleteActivity(id: string, title?: string) {
menuId.value = null; menuId.value = null;
boardMenuId.value = null; boardMenuId.value = null;
const target = activityById(id);
boardMenuActivity.value = null; boardMenuActivity.value = null;
if (target && !canDeleteActivity(target)) {
message.warning('شما مجوز حذف این فعالیت را ندارید.');
error.value = 'شما مجوز حذف این فعالیت را ندارید.';
return;
}
deleteSingleTitle.value = title?.trim() || activityTitle(id); deleteSingleTitle.value = title?.trim() || activityTitle(id);
deleteActivityIds.value = [id]; deleteActivityIds.value = [id];
} }
@@ -951,8 +993,24 @@ function askBulkDelete() {
menuId.value = null; menuId.value = null;
boardMenuId.value = null; boardMenuId.value = null;
boardMenuActivity.value = null; boardMenuActivity.value = null;
const selected = [...selectedIds.value];
const allowed = selected.filter((id) => {
const row = activityById(id);
return !row || canDeleteActivity(row);
});
const blocked = selected.length - allowed.length;
if (!allowed.length) {
message.warning('شما مجوز حذف این فعالیت‌ها را ندارید.');
error.value = 'شما مجوز حذف این فعالیت‌ها را ندارید.';
return;
}
if (blocked > 0) {
message.warning(
`${toFaDigits(blocked)} مورد به‌خاطر نبود مجوز حذف کنار گذاشته شد.`,
);
}
deleteSingleTitle.value = ''; deleteSingleTitle.value = '';
deleteActivityIds.value = [...selectedIds.value]; deleteActivityIds.value = allowed;
} }
async function confirmDeleteActivities() { async function confirmDeleteActivities() {
@@ -962,16 +1020,24 @@ async function confirmDeleteActivities() {
error.value = ''; error.value = '';
try { try {
const results = await Promise.allSettled(ids.map((id) => api.delete(`/activities/${id}`))); const results = await Promise.allSettled(ids.map((id) => api.delete(`/activities/${id}`)));
const failed = results.filter((r) => r.status === 'rejected').length; const failed = results.filter((r) => r.status === 'rejected');
deleteActivityIds.value = []; deleteActivityIds.value = [];
clearSelect(); clearSelect();
kanbanReload.value += 1; kanbanReload.value += 1;
await refreshAll(); await refreshAll();
if (failed) { if (failed.length) {
const first = failed[0];
const detail =
first && first.status === 'rejected'
? apiError(first.reason, '')
: '';
error.value = error.value =
failed === ids.length failed.length === ids.length
? 'حذف فعالیت‌ها ناموفق بود.' ? detail || 'شما مجوز حذف این فعالیت را ندارید.'
: `${toFaDigits(failed)} مورد حذف نشد.`; : detail
? `${toFaDigits(failed.length)} مورد حذف نشد: ${detail}`
: `${toFaDigits(failed.length)} مورد حذف نشد.`;
message.error(error.value);
} }
} finally { } finally {
activityDeleting.value = false; activityDeleting.value = false;
@@ -1130,6 +1196,7 @@ onMounted(() => {
mobileQuery.addEventListener('change', syncMobile); mobileQuery.addEventListener('change', syncMobile);
void loadUsers(); void loadUsers();
void activityTypes.load(true); void activityTypes.load(true);
void activityPriorities.load();
void loadBoards() void loadBoards()
.then(() => loadStages()) .then(() => loadStages())
.then(() => { .then(() => {
@@ -1185,11 +1252,11 @@ onUnmounted(() => {
variant="ghost" variant="ghost"
size="sm" size="sm"
type="button" type="button"
title="انواع فعالیت و فیلدها" title="انواع فعالیت و اولویت ها"
@click="typesManagerOpen = true" @click="typesManagerOpen = true"
> >
<UiIcon name="sliders" :size="14" /> <UiIcon name="sliders" :size="14" />
<span class="manage-label">انواع فعالیت و فیلدها</span> <span class="manage-label">انواع فعالیت و اولویت ها</span>
</UiButton> </UiButton>
<UiButton <UiButton
v-if="canManageStages" v-if="canManageStages"
@@ -1348,7 +1415,7 @@ onUnmounted(() => {
<hr class="board-menu-sep" /> <hr class="board-menu-sep" />
<button type="button" class="menu-row" @click="typesManagerOpen = true"> <button type="button" class="menu-row" @click="typesManagerOpen = true">
<UiIcon name="sliders" :size="16" /> <UiIcon name="sliders" :size="16" />
انواع فعالیت و فیلدها انواع فعالیت و اولویت ها
</button> </button>
<button type="button" class="menu-row" @click="stagesManagerOpen = true"> <button type="button" class="menu-row" @click="stagesManagerOpen = true">
<UiIcon name="settings" :size="16" /> <UiIcon name="settings" :size="16" />
@@ -1427,16 +1494,19 @@ onUnmounted(() => {
:customer="customerFilter" :customer="customerFilter"
:due="dueFilter" :due="dueFilter"
:type-key="typeFilter" :type-key="typeFilter"
:priority-key="priorityFilter"
:status-key="statusFilter" :status-key="statusFilter"
:assignee-id="assigneeFilter" :assignee-id="assigneeFilter"
:show-assignee="showDeskTabs" :show-assignee="showDeskTabs"
:users="users" :users="users"
:types="TYPE_FILTERS" :types="TYPE_FILTERS"
:priorities="PRIORITY_FILTERS"
:statuses="STATUS_FILTERS" :statuses="STATUS_FILTERS"
@title="setTitleFilter" @title="setTitleFilter"
@customer="setCustomerFilter" @customer="setCustomerFilter"
@due="setDueFilter" @due="setDueFilter"
@type="setTypeFilter" @type="setTypeFilter"
@priority="setPriorityFilter"
@status="setStatusFilter" @status="setStatusFilter"
@assignee="setAssigneeFilter" @assignee="setAssigneeFilter"
@clear="clearFacets" @clear="clearFacets"
@@ -1646,16 +1716,19 @@ onUnmounted(() => {
:customer="customerFilter" :customer="customerFilter"
:due="dueFilter" :due="dueFilter"
:type-key="typeFilter" :type-key="typeFilter"
:priority-key="priorityFilter"
:status-key="statusFilter" :status-key="statusFilter"
:assignee-id="assigneeFilter" :assignee-id="assigneeFilter"
:show-assignee="showDeskTabs" :show-assignee="showDeskTabs"
:users="users" :users="users"
:types="TYPE_FILTERS" :types="TYPE_FILTERS"
:priorities="PRIORITY_FILTERS"
:statuses="STATUS_FILTERS" :statuses="STATUS_FILTERS"
@title="setTitleFilter" @title="setTitleFilter"
@customer="setCustomerFilter" @customer="setCustomerFilter"
@due="setDueFilter" @due="setDueFilter"
@type="setTypeFilter" @type="setTypeFilter"
@priority="setPriorityFilter"
@status="setStatusFilter" @status="setStatusFilter"
@assignee="setAssigneeFilter" @assignee="setAssigneeFilter"
@done="onFacetDone" @done="onFacetDone"
@@ -1776,16 +1849,18 @@ onUnmounted(() => {
<RouterLink :to="activityRoute(item.id)"> <RouterLink :to="activityRoute(item.id)">
مشاهده مشاهده
</RouterLink> </RouterLink>
<RouterLink :to="activityRoute(item.id, true)">
ویرایش
</RouterLink>
<button v-if="canPromotePrior(item)" type="button" @click="promotePriorActivity(item.id)"> <button v-if="canPromotePrior(item)" type="button" @click="promotePriorActivity(item.id)">
انتقال به کار جاری انتقال به کار جاری
</button> </button>
<button v-if="canMarkShare(item)" type="button" @click="complete(item.id)"> <button v-if="canMarkShare(item)" type="button" @click="complete(item.id)">
{{ completeLabel(item) }} {{ completeLabel(item) }}
</button> </button>
<button type="button" class="danger" @click="askDeleteActivity(item.id, item.title)"> <button
v-if="canDeleteActivity(item)"
type="button"
class="danger"
@click="askDeleteActivity(item.id, item.title)"
>
حذف حذف
</button> </button>
</UiDropdownMenu> </UiDropdownMenu>
@@ -1866,16 +1941,18 @@ onUnmounted(() => {
<RouterLink :to="activityRoute(item.id)"> <RouterLink :to="activityRoute(item.id)">
مشاهده مشاهده
</RouterLink> </RouterLink>
<RouterLink :to="activityRoute(item.id, true)">
ویرایش
</RouterLink>
<button v-if="canPromotePrior(item)" type="button" @click="promotePriorActivity(item.id)"> <button v-if="canPromotePrior(item)" type="button" @click="promotePriorActivity(item.id)">
انتقال به کار جاری انتقال به کار جاری
</button> </button>
<button v-if="canMarkShare(item)" type="button" @click="complete(item.id)"> <button v-if="canMarkShare(item)" type="button" @click="complete(item.id)">
{{ completeLabel(item) }} {{ completeLabel(item) }}
</button> </button>
<button type="button" class="danger" @click="askDeleteActivity(item.id, item.title)"> <button
v-if="canDeleteActivity(item)"
type="button"
class="danger"
@click="askDeleteActivity(item.id, item.title)"
>
حذف حذف
</button> </button>
</UiDropdownMenu> </UiDropdownMenu>
@@ -1922,18 +1999,11 @@ onUnmounted(() => {
<button type="button" role="menuitem" @click="startSelect(boardMenuId)">انتخاب</button> <button type="button" role="menuitem" @click="startSelect(boardMenuId)">انتخاب</button>
<RouterLink <RouterLink
role="menuitem" role="menuitem"
:to="activityRoute(boardMenuId, false, viewMode === 'board' ? boardMenuStageId : undefined)" :to="activityRoute(boardMenuId, viewMode === 'board' ? boardMenuStageId : undefined)"
@click="boardMenuId = null; boardMenuActivity = null; boardMenuStageId = ''" @click="boardMenuId = null; boardMenuActivity = null; boardMenuStageId = ''"
> >
مشاهده مشاهده
</RouterLink> </RouterLink>
<RouterLink
role="menuitem"
:to="activityRoute(boardMenuId, true)"
@click="boardMenuId = null; boardMenuActivity = null"
>
ویرایش
</RouterLink>
<button <button
v-if="boardMenuActivity && canPromotePrior(boardMenuActivity)" v-if="boardMenuActivity && canPromotePrior(boardMenuActivity)"
type="button" type="button"
@@ -1943,6 +2013,7 @@ onUnmounted(() => {
انتقال به کار جاری انتقال به کار جاری
</button> </button>
<button <button
v-if="canDeleteActivity(boardMenuActivity)"
type="button" type="button"
role="menuitem" role="menuitem"
class="danger" class="danger"
+225 -70
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'; import { computed, h, onMounted, onUnmounted, ref, watch } from 'vue';
import { RouterLink, onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'; import { RouterLink, onBeforeRouteLeave, useRoute, useRouter } from 'vue-router';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { import {
@@ -18,7 +18,7 @@ import ActivityCommentSheet from '@/components/activities/ActivityCommentSheet.v
import ActivityPostponeSheet from '@/components/activities/ActivityPostponeSheet.vue'; import ActivityPostponeSheet from '@/components/activities/ActivityPostponeSheet.vue';
import ActivityFieldsView from '@/components/activities/ActivityFieldsView.vue'; import ActivityFieldsView from '@/components/activities/ActivityFieldsView.vue';
import StagePathStrip from '@/components/StagePathStrip.vue'; import StagePathStrip from '@/components/StagePathStrip.vue';
import { message, Modal } from 'ant-design-vue'; import { Button as AButton, message, Modal } from 'ant-design-vue';
import type { import type {
ActivityChecklistItem, ActivityChecklistItem,
ActivityDto, ActivityDto,
@@ -29,7 +29,10 @@ import type {
TeamDto, TeamDto,
} from '@mento/shared'; } from '@mento/shared';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import { canCollaborateOnActivity, canMutateActivity } from '@/lib/activity-access';
import { canAssignToOthers } from '@/lib/assign-access'; import { canAssignToOthers } from '@/lib/assign-access';
import { apiError } from '@/lib/routines';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { activityTypeView, typeColorStyle, useActivityTypes } from '@/lib/activity-types'; import { activityTypeView, typeColorStyle, useActivityTypes } from '@/lib/activity-types';
import { import {
bindThreadMedia, bindThreadMedia,
@@ -49,8 +52,33 @@ import {
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const ACTIVITY_LIST_QUERY = ['board', 'view', 'desk', 'filter', 'stage', 'q', 'typeDefId', 'status', 'assigneeId', 'title', 'customer', 'due'] as const; const ACTIVITY_LIST_QUERY = [
const NAV_API_QUERY = ['q', 'desk', 'type', 'typeDefId', 'status', 'assigneeId', 'title', 'customer', 'due'] as const; 'board',
'view',
'desk',
'filter',
'stage',
'q',
'typeDefId',
'status',
'priority',
'assigneeId',
'title',
'customer',
'due',
] as const;
const NAV_API_QUERY = [
'q',
'desk',
'type',
'typeDefId',
'status',
'priority',
'assigneeId',
'title',
'customer',
'due',
] as const;
function activitiesListLocation() { function activitiesListLocation() {
const query: Record<string, string> = {}; const query: Record<string, string> = {};
@@ -76,12 +104,29 @@ async function goBack() {
} }
const auth = useAuthStore(); const auth = useAuthStore();
const id = computed(() => (typeof route.params.id === 'string' ? route.params.id : '')); const id = computed(() => (typeof route.params.id === 'string' ? route.params.id : ''));
const canReassign = computed(() => canAssignToOthers(auth.user, 'activities'));
const loading = ref(true); const loading = ref(true);
const saving = ref(false); const saving = ref(false);
const error = ref(''); const error = ref('');
const activity = ref<ActivityDto | null>(null); const activity = ref<ActivityDto | null>(null);
const canMutate = computed(() => canMutateActivity(activity.value, auth.user));
const canCollaborate = computed(() =>
canCollaborateOnActivity(activity.value, auth.user),
);
const editLocked = computed(() => saving.value || !canMutate.value);
const collabLocked = computed(() => saving.value || !canCollaborate.value);
function warnNoMutatePermission() {
error.value = 'شما مجوز ویرایش یا حذف این فعالیت را ندارید.';
}
/** کنترل‌های disabled کلیک نمی‌گیرند؛ روی والد اخطار می‌دهیم */
function onLockedEditAttempt() {
if (!canMutate.value && !saving.value) warnNoMutatePermission();
}
const canReassign = computed(
() => canMutate.value && canAssignToOthers(auth.user, 'activities'),
);
const boardStages = ref<ActivityStageDto[]>([]); const boardStages = ref<ActivityStageDto[]>([]);
const stageMoving = ref(false); const stageMoving = ref(false);
type NoteMedia = { type NoteMedia = {
@@ -429,7 +474,12 @@ function clearNoteEdit() {
} }
function canEditNote(entry: ActivityThreadEntry): boolean { function canEditNote(entry: ActivityThreadEntry): boolean {
return Boolean(entry.dateLabel && meName.value && entry.author === meName.value); return Boolean(
canCollaborate.value &&
entry.dateLabel &&
meName.value &&
entry.author === meName.value,
);
} }
function activityMediaCount(kind: 'image' | 'audio' | 'file') { function activityMediaCount(kind: 'image' | 'audio' | 'file') {
@@ -557,8 +607,8 @@ async function saveNoteEdit(): Promise<boolean> {
clearNoteEdit(); clearNoteEdit();
await load(); await load();
return true; return true;
} catch { } catch (e) {
error.value = 'ویرایش یادداشت ناموفق بود.'; error.value = apiError(e, 'شما مجوز ویرایش این فعالیت را ندارید.');
return false; return false;
} finally { } finally {
saving.value = false; saving.value = false;
@@ -567,6 +617,7 @@ async function saveNoteEdit(): Promise<boolean> {
async function persistDrafts(): Promise<boolean> { async function persistDrafts(): Promise<boolean> {
if (!id.value || !activity.value) return true; if (!id.value || !activity.value) return true;
if (!canMutate.value) return true;
if (editingNoteIndex.value !== null) { if (editingNoteIndex.value !== null) {
const noteOk = await saveNoteEdit(); const noteOk = await saveNoteEdit();
if (!noteOk) return false; if (!noteOk) return false;
@@ -598,19 +649,67 @@ async function persistDrafts(): Promise<boolean> {
activity.value = data; activity.value = data;
hydrateDraft(data); hydrateDraft(data);
return true; return true;
} catch { } catch (e) {
error.value = 'ثبت تغییرات ناموفق بود.'; error.value = apiError(e, 'شما مجوز ویرایش این فعالیت را ندارید.');
return false; return false;
} finally { } finally {
saving.value = false; saving.value = false;
} }
} }
/** true = مجاز به ترک صفحه · false = بمان روی جزئیات */
async function resolveDirty(): Promise<boolean> { async function resolveDirty(): Promise<boolean> {
if (!isDirty.value) return true; if (!isDirty.value) return true;
if (confirm('تغییرات ثبت شود؟')) return persistDrafts(); return new Promise((resolve) => {
const modal = Modal.confirm({
title: 'تغییرات ذخیره‌نشده',
content: 'تغییراتی در این فعالیت انجام داده‌اید، آیا ذخیره شود؟',
centered: true,
closable: false,
maskClosable: false,
keyboard: false,
icon: null,
footer: () =>
h('div', { class: 'ant-modal-confirm-btns' }, [
h(
AButton,
{
onClick: () => {
modal.destroy();
resolve(false);
},
},
() => 'ادامهٔ ویرایش',
),
h(
AButton,
{
onClick: () => {
discardDrafts(); discardDrafts();
return true; modal.destroy();
resolve(true);
},
},
() => 'ذخیره نکن',
),
h(
AButton,
{
type: 'primary',
onClick: () => {
void (async () => {
const ok = await persistDrafts();
if (!ok) return;
modal.destroy();
resolve(true);
})();
},
},
() => 'ذخیره',
),
]),
});
});
} }
function onBeforeUnload(event: BeforeUnloadEvent) { function onBeforeUnload(event: BeforeUnloadEvent) {
@@ -623,6 +722,10 @@ function onBeforeUnload(event: BeforeUnloadEvent) {
async function toggleChecklistItem(key: string, itemId: string, done: boolean) { async function toggleChecklistItem(key: string, itemId: string, done: boolean) {
const a = activity.value; const a = activity.value;
if (!a || fieldsBusy.value) return; if (!a || fieldsBusy.value) return;
if (!canMutate.value) {
warnNoMutatePermission();
return;
}
const list = (a.fields?.[key] as ActivityChecklistItem[] | undefined) ?? []; const list = (a.fields?.[key] as ActivityChecklistItem[] | undefined) ?? [];
const nextFields = { const nextFields = {
...(a.fields ?? {}), ...(a.fields ?? {}),
@@ -642,13 +745,9 @@ async function toggleChecklistItem(key: string, itemId: string, done: boolean) {
} }
} }
const priorityLabel: Record<ActivityPriority, string> = { const activityPriorities = useActivityPriorities();
very_low: 'خیلی کم', void activityPriorities.load();
low: 'کم', const priorityLabel = computed(() => activityPriorities.labels.value);
medium: 'متوسط',
high: 'زیاد',
very_high: 'خیلی زیاد',
};
const subtitle = computed(() => { const subtitle = computed(() => {
const a = activity.value; const a = activity.value;
@@ -726,6 +825,7 @@ function moveToStage(stageId: string) {
if (activity.value.stageId === stageId) return; if (activity.value.stageId === stageId) return;
const target = boardStages.value.find((stage) => stage.id === stageId); const target = boardStages.value.find((stage) => stage.id === stageId);
if (!target) return; if (!target) return;
const leftId = id.value;
Modal.confirm({ Modal.confirm({
title: 'جابه‌جایی مرحله', title: 'جابه‌جایی مرحله',
content: `به ستون «${target.name}» منتقل می‌شود. انجام شود؟`, content: `به ستون «${target.name}» منتقل می‌شود. انجام شود؟`,
@@ -736,7 +836,7 @@ function moveToStage(stageId: string) {
stageMoving.value = true; stageMoving.value = true;
error.value = ''; error.value = '';
try { try {
const { data } = await api.patch<ActivityDto>(`/activities/${id.value}/stage`, { stageId }); const { data } = await api.patch<ActivityDto>(`/activities/${leftId}/stage`, { stageId });
if (data.status !== target.kind) { if (data.status !== target.kind) {
message.info( message.info(
'سهم شما ثبت شد. فعالیت وقتی انجام‌شده می‌شود که همهٔ مسئول‌ها سهم خود را بزنند.', 'سهم شما ثبت شد. فعالیت وقتی انجام‌شده می‌شود که همهٔ مسئول‌ها سهم خود را بزنند.',
@@ -744,8 +844,8 @@ function moveToStage(stageId: string) {
await load(); await load();
return; return;
} }
activity.value = data; discardDrafts();
hydrateDraft(data); await advanceAfterLeavingColumn(leftId);
} catch { } catch {
error.value = 'جابه‌جایی مرحله ناموفق بود.'; error.value = 'جابه‌جایی مرحله ناموفق بود.';
throw new Error('stage-move-failed'); throw new Error('stage-move-failed');
@@ -803,20 +903,20 @@ async function loadUsers() {
async function complete(kind: 'share' | 'force' | 'undo' = 'share') { async function complete(kind: 'share' | 'force' | 'undo' = 'share') {
if (!id.value) return; if (!id.value) return;
if (kind !== 'undo' && isDone.value) return; if (kind !== 'undo' && isDone.value) return;
const leftId = id.value;
saving.value = true; saving.value = true;
error.value = ''; error.value = '';
try { try {
const params = const params =
kind === 'force' ? { force: '1' } : kind === 'undo' ? { undo: '1' } : undefined; kind === 'force' ? { force: '1' } : kind === 'undo' ? { undo: '1' } : undefined;
const { data } = await api.patch<ActivityDto>( const { data } = await api.patch<ActivityDto>(
`/activities/${id.value}/complete`, `/activities/${leftId}/complete`,
undefined, undefined,
{ params }, { params },
); );
if (data.status === 'done') { if (data.status === 'done') {
// مثل بازگشت و پیش‌نمایش: فیلتر/نمای قبلی حفظ شود
discardDrafts(); discardDrafts();
leaveToActivitiesList(); await advanceAfterLeavingColumn(leftId);
return; return;
} }
activity.value = data; activity.value = data;
@@ -830,6 +930,10 @@ async function complete(kind: 'share' | 'force' | 'undo' = 'share') {
async function setCompletionMode(mode: 'any' | 'all') { async function setCompletionMode(mode: 'any' | 'all') {
if (!id.value || activity.value?.completionMode === mode) return; if (!id.value || activity.value?.completionMode === mode) return;
if (!canMutate.value) {
warnNoMutatePermission();
return;
}
saving.value = true; saving.value = true;
error.value = ''; error.value = '';
try { try {
@@ -846,11 +950,17 @@ async function setCompletionMode(mode: 'any' | 'all') {
async function reopen() { async function reopen() {
if (!id.value || !activity.value || activity.value.status === 'open') return; if (!id.value || !activity.value || activity.value.status === 'open') return;
if (!canMutate.value) {
warnNoMutatePermission();
return;
}
const leftId = id.value;
saving.value = true; saving.value = true;
error.value = ''; error.value = '';
try { try {
await api.patch(`/activities/${id.value}`, { status: 'open' }); await api.patch(`/activities/${leftId}`, { status: 'open' });
await load(); discardDrafts();
await advanceAfterLeavingColumn(leftId);
} catch { } catch {
error.value = 'بازگشایی کار ناموفق بود.'; error.value = 'بازگشایی کار ناموفق بود.';
} finally { } finally {
@@ -887,8 +997,8 @@ async function postponeTo(iso: string) {
await api.patch(`/activities/${id.value}`, { dueAt: iso }); await api.patch(`/activities/${id.value}`, { dueAt: iso });
postponeOpen.value = false; postponeOpen.value = false;
await load(); await load();
} catch { } catch (e) {
error.value = 'تعویق فعالیت ناموفق بود.'; error.value = apiError(e, 'شما مجوز ویرایش این فعالیت را ندارید.');
} finally { } finally {
saving.value = false; saving.value = false;
} }
@@ -910,7 +1020,7 @@ async function submitComment(payload: { text: string; photoOnly: boolean }) {
commentOpen.value = false; commentOpen.value = false;
await load(); await load();
} catch (e) { } catch (e) {
error.value = 'ثبت نظر ناموفق بود.'; error.value = apiError(e, 'شما مجوز ویرایش این فعالیت را ندارید.');
throw e; throw e;
} finally { } finally {
saving.value = false; saving.value = false;
@@ -921,6 +1031,13 @@ const navIds = ref<string[]>([]);
const deskBrowse = computed( const deskBrowse = computed(
() => route.query.from === 'desk' && typeof route.query.nav === 'string' && route.query.nav.length > 0, () => route.query.from === 'desk' && typeof route.query.nav === 'string' && route.query.nav.length > 0,
); );
const navColumnStageId = computed(() => {
const fromQuery =
typeof route.query.stage === 'string' && route.query.stage && route.query.stage !== 'all'
? route.query.stage
: '';
return fromQuery || activity.value?.stageId || '';
});
const navIndex = computed(() => navIds.value.indexOf(id.value)); const navIndex = computed(() => navIds.value.indexOf(id.value));
const prevNavId = computed(() => (navIndex.value > 0 ? navIds.value[navIndex.value - 1]! : '')); const prevNavId = computed(() => (navIndex.value > 0 ? navIds.value[navIndex.value - 1]! : ''));
const nextNavId = computed(() => const nextNavId = computed(() =>
@@ -930,13 +1047,13 @@ const nextNavId = computed(() =>
); );
const showNav = computed(() => deskBrowse.value && navIndex.value >= 0); const showNav = computed(() => deskBrowse.value && navIndex.value >= 0);
function navStorageKey(token: string) { function navStorageKey(token: string, stageId: string) {
return `activity-nav:${token}`; return `activity-nav:${token}:${stageId || 'none'}`;
} }
function readNavCache(token: string): string[] | null { function readNavCache(token: string, stageId: string): string[] | null {
try { try {
const raw = sessionStorage.getItem(navStorageKey(token)); const raw = sessionStorage.getItem(navStorageKey(token, stageId));
if (!raw) return null; if (!raw) return null;
const parsed = JSON.parse(raw) as { ids?: unknown }; const parsed = JSON.parse(raw) as { ids?: unknown };
if (!Array.isArray(parsed.ids) || parsed.ids.some((item) => typeof item !== 'string')) return null; if (!Array.isArray(parsed.ids) || parsed.ids.some((item) => typeof item !== 'string')) return null;
@@ -946,42 +1063,70 @@ function readNavCache(token: string): string[] | null {
} }
} }
function writeNavCache(token: string, stageId: string, ids: string[]) {
try {
sessionStorage.setItem(navStorageKey(token, stageId), JSON.stringify({ ids }));
} catch {
/* حالت خصوصی مرورگر */
}
}
/** بعد از ترک ستون: برو بعدیِ همان ستون، وگرنه قبلی؛ اگر خالی بود برو فهرست. */
async function advanceAfterLeavingColumn(leftId: string) {
commentOpen.value = false;
postponeOpen.value = false;
if (!deskBrowse.value) {
leaveToActivitiesList();
return;
}
const list = navIds.value;
const idx = list.indexOf(leftId);
const target =
idx >= 0 && idx < list.length - 1
? list[idx + 1]!
: idx > 0
? list[idx - 1]!
: '';
const remaining = list.filter((item) => item !== leftId);
navIds.value = remaining;
const token = typeof route.query.nav === 'string' ? route.query.nav : '';
const stageId = navColumnStageId.value;
if (token) writeNavCache(token, stageId, remaining);
if (target) {
await router.push({ name: 'activity-detail', params: { id: target }, query: route.query });
return;
}
leaveToActivitiesList();
}
let navSeq = 0; let navSeq = 0;
async function loadNav() { async function loadNav() {
const seq = ++navSeq; const seq = ++navSeq;
const token = typeof route.query.nav === 'string' ? route.query.nav : ''; const token = typeof route.query.nav === 'string' ? route.query.nav : '';
const columnMissing = const stageId = navColumnStageId.value;
route.query.view === 'board' && if (!deskBrowse.value || !token || !stageId) {
(typeof route.query.stage !== 'string' || !route.query.stage || route.query.stage === 'all'); if (seq === navSeq) navIds.value = [];
if (!deskBrowse.value || !token || columnMissing) {
navIds.value = [];
return; return;
} }
const cached = readNavCache(token); const cached = readNavCache(token, stageId);
if (cached) { if (cached) {
if (seq === navSeq) navIds.value = cached; if (seq === navSeq) navIds.value = cached;
return; return;
} }
const params: Record<string, string> = { const params: Record<string, string> = {
filter: typeof route.query.filter === 'string' && route.query.filter ? route.query.filter : 'today', filter: typeof route.query.filter === 'string' && route.query.filter ? route.query.filter : 'today',
stageId,
}; };
for (const key of NAV_API_QUERY) { for (const key of NAV_API_QUERY) {
const value = route.query[key]; const value = route.query[key];
if (typeof value === 'string' && value) params[key] = value; if (typeof value === 'string' && value) params[key] = value;
} }
if (typeof route.query.board === 'string' && route.query.board) params.boardId = route.query.board; if (typeof route.query.board === 'string' && route.query.board) params.boardId = route.query.board;
if (typeof route.query.stage === 'string' && route.query.stage && route.query.stage !== 'all') {
params.stageId = route.query.stage;
}
try { try {
const { data } = await api.get<{ ids: string[] }>('/activities/nav-ids', { params }); const { data } = await api.get<{ ids: string[] }>('/activities/nav-ids', { params });
if (seq !== navSeq) return; if (seq !== navSeq) return;
const ids = Array.isArray(data.ids) ? data.ids : []; const ids = Array.isArray(data.ids) ? data.ids : [];
try { writeNavCache(token, stageId, ids);
sessionStorage.setItem(navStorageKey(token), JSON.stringify({ ids }));
} catch {
/* حالت خصوصی مرورگر */
}
navIds.value = ids; navIds.value = ids;
} catch { } catch {
if (seq === navSeq) navIds.value = []; if (seq === navSeq) navIds.value = [];
@@ -1001,18 +1146,13 @@ watch(id, () => {
postponeOpen.value = false; postponeOpen.value = false;
void load(); void load();
}); });
watch(() => route.query.nav, () => void loadNav(), { immediate: true }); watch(
onBeforeRouteLeave(async (_to, _from, next) => { () => [route.query.nav, navColumnStageId.value] as const,
if (!isDirty.value) { () => void loadNav(),
next(); { immediate: true },
return; );
} /** بدون next() — در Vue Router 4 گارد async+next باعث رد شدن بدون پرسش می‌شد */
if (confirm('تغییرات ثبت شود؟')) next(await persistDrafts()); onBeforeRouteLeave(async () => resolveDirty());
else {
discardDrafts();
next();
}
});
onMounted(() => { onMounted(() => {
window.addEventListener('beforeunload', onBeforeUnload); window.addEventListener('beforeunload', onBeforeUnload);
void load(); void load();
@@ -1049,14 +1189,14 @@ onUnmounted(() => {
<article class="card"> <article class="card">
<header class="hero"> <header class="hero">
<div> <div>
<h2> <h2 @click.capture="onLockedEditAttempt">
<input <input
v-model="draftTitle" v-model="draftTitle"
class="title-input" class="title-input"
type="text" type="text"
maxlength="200" maxlength="200"
aria-label="عنوان فعالیت" aria-label="عنوان فعالیت"
:disabled="saving" :disabled="editLocked"
/> />
</h2> </h2>
<p v-if="subtitle" class="sub"> <p v-if="subtitle" class="sub">
@@ -1090,14 +1230,14 @@ onUnmounted(() => {
/> />
</div> </div>
<dl class="meta"> <dl class="meta" @click.capture="onLockedEditAttempt">
<div> <div>
<dt> <dt>
<UiIcon :name="draftTypeView!.icon" :size="15" /> <UiIcon :name="draftTypeView!.icon" :size="15" />
نوع فعالیت نوع فعالیت
</dt> </dt>
<dd> <dd>
<select v-model="draftTypeDefId" class="meta-control" :disabled="saving" aria-label="نوع فعالیت"> <select v-model="draftTypeDefId" class="meta-control" :disabled="editLocked" aria-label="نوع فعالیت">
<option v-for="opt in typeChoices" :key="opt.id" :value="opt.id">{{ opt.name }}</option> <option v-for="opt in typeChoices" :key="opt.id" :value="opt.id">{{ opt.name }}</option>
</select> </select>
</dd> </dd>
@@ -1108,17 +1248,22 @@ onUnmounted(() => {
تاریخ و زمان تاریخ و زمان
</dt> </dt>
<dd> <dd>
<JalaliDateInput v-model="draftDue" mode="datetime" :disabled="saving" /> <JalaliDateInput v-model="draftDue" mode="datetime" :disabled="editLocked" />
</dd> </dd>
</div> </div>
<div> <div>
<dt> <dt>
<UiIcon name="flag" :size="15" class="flag" :class="draftPriority" /> <UiIcon
name="flag"
:size="15"
class="flag"
:style="{ color: activityPriorities.colorOf(draftPriority) }"
/>
اولویت اولویت
</dt> </dt>
<dd> <dd>
<select v-model="draftPriority" class="meta-control" :disabled="saving" aria-label="اولویت"> <select v-model="draftPriority" class="meta-control" :disabled="editLocked" aria-label="اولویت">
<option v-for="(label, key) in priorityLabel" :key="key" :value="key">{{ label }}</option> <option v-for="(label, key) in priorityLabel" :key="String(key)" :value="key">{{ label }}</option>
</select> </select>
</dd> </dd>
</div> </div>
@@ -1656,11 +1801,21 @@ onUnmounted(() => {
<UiIcon name="check" :size="16" /> <UiIcon name="check" :size="16" />
انجام شده انجام شده
</button> </button>
<button class="act ghost" type="button" :disabled="saving || isDone" @click="postponeOpen = true"> <button
class="act ghost"
type="button"
:disabled="collabLocked || isDone"
@click="postponeOpen = true"
>
<UiIcon name="refresh" :size="16" /> <UiIcon name="refresh" :size="16" />
تعویق تعویق
</button> </button>
<button class="act ghost" type="button" :disabled="saving" @click="commentOpen = true"> <button
class="act ghost"
type="button"
:disabled="collabLocked"
@click="commentOpen = true"
>
<UiIcon name="chat" :size="16" /> <UiIcon name="chat" :size="16" />
ثبت نظر ثبت نظر
</button> </button>
+55 -29
View File
@@ -32,6 +32,7 @@ import {
UiTextarea, UiTextarea,
} from '@/components/ui'; } from '@/components/ui';
import ActivityFieldsEditor from '@/components/activities/ActivityFieldsEditor.vue'; import ActivityFieldsEditor from '@/components/activities/ActivityFieldsEditor.vue';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { typeColorStyle, useActivityTypes } from '@/lib/activity-types'; import { typeColorStyle, useActivityTypes } from '@/lib/activity-types';
import type { import type {
ActivityBoardDto, ActivityBoardDto,
@@ -89,6 +90,8 @@ const boardId = ref('');
const defaultBoardId = computed(() => boards.value.find((b) => b.isDefault)?.id ?? ''); const defaultBoardId = computed(() => boards.value.find((b) => b.isDefault)?.id ?? '');
const activityTypes = useActivityTypes(); const activityTypes = useActivityTypes();
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const title = ref(''); const title = ref('');
const type = ref<ActivityType | ''>(''); const type = ref<ActivityType | ''>('');
const typeDefId = ref(''); const typeDefId = ref('');
@@ -130,6 +133,7 @@ const leadId = ref('');
const dealId = ref(''); const dealId = ref('');
const assigneeIds = ref<string[]>([]); const assigneeIds = ref<string[]>([]);
const completionMode = ref<'any' | 'all'>('any'); const completionMode = ref<'any' | 'all'>('any');
const editPolicy = ref<'creator' | 'assignees'>('creator');
const isDone = ref(false); const isDone = ref(false);
const needsNote = ref(false); const needsNote = ref(false);
const reminderAt = ref(''); const reminderAt = ref('');
@@ -270,13 +274,13 @@ function isEmptyValue(v: ActivityFieldValue | undefined): boolean {
return false; return false;
} }
const priorityOptions: Array<{ value: ActivityPriority; label: string; tone: string }> = [ const priorityOptions = computed(() =>
{ value: 'very_high', label: 'خیلی زیاد', tone: 'very-high' }, activityPriorities.items.value.map((row) => ({
{ value: 'high', label: 'زیاد', tone: 'high' }, value: row.key,
{ value: 'medium', label: 'متوسط', tone: 'medium' }, label: row.label,
{ value: 'low', label: 'کم', tone: 'low' }, color: row.color,
{ value: 'very_low', label: 'خیلی کم', tone: 'very-low' }, })),
]; );
const typeMeta = computed(() => activityTypes.byId.value.get(typeDefId.value) ?? null); const typeMeta = computed(() => activityTypes.byId.value.get(typeDefId.value) ?? null);
const typeFields = computed(() => typeMeta.value?.fields ?? []); const typeFields = computed(() => typeMeta.value?.fields ?? []);
@@ -401,7 +405,7 @@ const duePreview = computed(() => {
const statusText = computed(() => (isDone.value ? 'انجام شده' : 'انجام نشده')); const statusText = computed(() => (isDone.value ? 'انجام شده' : 'انجام نشده'));
const priorityText = computed( const priorityText = computed(
() => priorityOptions.find((p) => p.value === priority.value)?.label || '—', () => priorityOptions.value.find((p) => p.value === priority.value)?.label || '—',
); );
const pageTitle = computed(() => (isNew.value ? 'ایجاد فعالیت جدید' : 'ویرایش فعالیت')); const pageTitle = computed(() => (isNew.value ? 'ایجاد فعالیت جدید' : 'ویرایش فعالیت'));
const summaryReady = computed(() => Boolean(title.value.trim() || type.value || selectedPerson.value)); const summaryReady = computed(() => Boolean(title.value.trim() || type.value || selectedPerson.value));
@@ -442,6 +446,7 @@ function resetForm() {
dealId.value = ''; dealId.value = '';
assigneeIds.value = auth.user?.id ? [auth.user.id] : []; assigneeIds.value = auth.user?.id ? [auth.user.id] : [];
completionMode.value = 'any'; completionMode.value = 'any';
editPolicy.value = 'creator';
pickedRoleIds.value = []; pickedRoleIds.value = [];
pickedTeamIds.value = []; pickedTeamIds.value = [];
isDone.value = false; isDone.value = false;
@@ -531,6 +536,7 @@ async function load() {
? [auth.user.id] ? [auth.user.id]
: []; : [];
completionMode.value = data.completionMode === 'all' ? 'all' : 'any'; completionMode.value = data.completionMode === 'all' ? 'all' : 'any';
editPolicy.value = data.editPolicy === 'assignees' ? 'assignees' : 'creator';
refreshPickedGroups(); refreshPickedGroups();
isDone.value = data.status === 'done'; isDone.value = data.status === 'done';
await loadSavedPhotos(data); await loadSavedPhotos(data);
@@ -544,6 +550,16 @@ async function load() {
personId.value = incomingPerson; personId.value = incomingPerson;
} }
leadId.value = typeof route.query.leadId === 'string' ? route.query.leadId : ''; leadId.value = typeof route.query.leadId === 'string' ? route.query.leadId : '';
const incomingDeal =
typeof route.query.dealId === 'string' ? route.query.dealId : '';
if (incomingDeal) {
dealId.value = incomingDeal;
const linkedDeal = deals.value.find((d) => d.id === incomingDeal);
if (linkedDeal?.person?.id && !personId.value) {
await ensurePersonLoaded(linkedDeal.person.id);
personId.value = linkedDeal.person.id;
}
}
const incomingDef = const incomingDef =
typeof route.query.typeDefId === 'string' typeof route.query.typeDefId === 'string'
? activityTypes.byId.value.get(route.query.typeDefId) ? activityTypes.byId.value.get(route.query.typeDefId)
@@ -609,6 +625,7 @@ function payload(): CreateActivityRequest {
assigneeIds: [...assigneeIds.value], assigneeIds: [...assigneeIds.value],
assigneeId: assigneeIds.value[0] || null, assigneeId: assigneeIds.value[0] || null,
completionMode: assigneeIds.value.length > 1 ? completionMode.value : 'any', completionMode: assigneeIds.value.length > 1 ? completionMode.value : 'any',
editPolicy: editPolicy.value,
}; };
} }
@@ -1322,6 +1339,29 @@ watch([id, isNew], () => void load(), { immediate: true });
</div> </div>
</div> </div>
<div class="card">
<div class="field">
<label>ویرایش و حذف</label>
<div class="completion-mode">
<label>
<input v-model="editPolicy" type="radio" value="creator" />
فقط خودم (ایجادکننده)
</label>
<label>
<input v-model="editPolicy" type="radio" value="assignees" />
همهٔ مسئولان
</label>
</div>
<small class="hint">
{{
editPolicy === 'assignees'
? 'مسئولان هم می‌توانند این فعالیت را ویرایش یا حذف کنند.'
: 'فقط ایجادکننده می‌تواند این فعالیت را ویرایش یا حذف کند.'
}}
</small>
</div>
</div>
<div class="card"> <div class="card">
<div class="field"> <div class="field">
<div class="label-row"> <div class="label-row">
@@ -1405,7 +1445,13 @@ watch([id, isNew], () => void load(), { immediate: true });
<div class="card"> <div class="card">
<p class="pri-label">اولویت</p> <p class="pri-label">اولویت</p>
<div class="priorities"> <div class="priorities">
<label v-for="opt in priorityOptions" :key="opt.value" :class="['pri', opt.tone, { on: priority === opt.value }]"> <label
v-for="opt in priorityOptions"
:key="opt.value"
class="pri"
:class="{ on: priority === opt.value }"
:style="{ color: opt.color }"
>
<input v-model="priority" type="radio" :value="opt.value" /> <input v-model="priority" type="radio" :value="opt.value" />
<UiIcon name="flag" :size="16" /> <UiIcon name="flag" :size="16" />
<span>{{ opt.label }}</span> <span>{{ opt.label }}</span>
@@ -2328,26 +2374,6 @@ watch([id, isNew], () => void load(), { immediate: true });
flex-shrink: 0; flex-shrink: 0;
} }
.pri.very-high {
color: #dc2626;
}
.pri.high {
color: #ea580c;
}
.pri.medium {
color: #eab308;
}
.pri.low {
color: #16a34a;
}
.pri.very-low {
color: #94a3b8;
}
.pri.on span { .pri.on span {
font-weight: 600; font-weight: 600;
} }
+9
View File
@@ -45,6 +45,7 @@ import { toFaDigits } from '@/lib/jalali';
import { currencySuffix, formatMoney } from '@/lib/money'; import { currencySuffix, formatMoney } from '@/lib/money';
import CustomFieldsSection from '@/components/CustomFieldsSection.vue'; import CustomFieldsSection from '@/components/CustomFieldsSection.vue';
import EntityTimeline from '@/components/EntityTimeline.vue'; import EntityTimeline from '@/components/EntityTimeline.vue';
import RelatedActivitiesPanel from '@/components/activities/RelatedActivitiesPanel.vue';
import RelatedTasksPanel from '@/components/routines/RelatedTasksPanel.vue'; import RelatedTasksPanel from '@/components/routines/RelatedTasksPanel.vue';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.vue'; import MoneyInput from '@/components/MoneyInput.vue';
@@ -1014,6 +1015,14 @@ onMounted(load);
</a-form-item> </a-form-item>
</a-card> </a-card>
<RelatedActivitiesPanel
v-if="!isNew && id"
:style="{ marginTop: '16px' }"
:deal-id="id"
:person-id="personId || null"
:company-id="companyId || null"
:deal-title="title"
/>
<RelatedTasksPanel <RelatedTasksPanel
v-if="!isNew && id" v-if="!isNew && id"
:style="{ marginTop: '16px' }" :style="{ marginTop: '16px' }"
+1 -1
View File
@@ -1179,7 +1179,7 @@ onBeforeUnmount(() => narrowMq?.removeEventListener('change', syncNarrow));
:name="lead.contactName || lead.title" :name="lead.contactName || lead.title"
:phone="lead.mobile || lead.phone || ''" :phone="lead.mobile || lead.phone || ''"
:record-title="lead.title" :record-title="lead.title"
:company="lead.contactName ? lead.title : ''" :company="lead.trade ?? ''"
@close="smsOpen = false" @close="smsOpen = false"
/> />
</template> </template>
+41 -1
View File
@@ -97,6 +97,9 @@ const website = ref('');
const instagram = ref(''); const instagram = ref('');
const birthDate = ref(''); const birthDate = ref('');
const referrer = ref(''); const referrer = ref('');
const nationalId = ref('');
const city = ref('');
const rasteh = ref('');
const addresses = ref<string[]>(['']); const addresses = ref<string[]>(['']);
const notes = ref(''); const notes = ref('');
const tagsRaw = ref(''); const tagsRaw = ref('');
@@ -283,6 +286,16 @@ function fill(p: PersonDto) {
mood.value = p.mood || 'newcomer'; mood.value = p.mood || 'newcomer';
groupIds.value = (p.groups ?? []).map((g) => g.id); groupIds.value = (p.groups ?? []).map((g) => g.id);
customFields.value = { ...(p.customFields ?? {}) }; customFields.value = { ...(p.customFields ?? {}) };
const cf = customFields.value;
nationalId.value =
typeof cf.nationalId === 'string'
? cf.nationalId
: typeof cf.nationalId === 'number'
? String(cf.nationalId)
: '';
city.value = typeof cf.city === 'string' ? cf.city : '';
rasteh.value =
typeof cf.rasteh === 'string' || typeof cf.rasteh === 'number' ? String(cf.rasteh) : '';
loyaltyPoints.value = p.loyaltyPoints ?? 0; loyaltyPoints.value = p.loyaltyPoints ?? 0;
loyaltyTierName.value = p.loyaltyTier?.name ?? ''; loyaltyTierName.value = p.loyaltyTier?.name ?? '';
} }
@@ -344,6 +357,18 @@ function parseTags(raw: string): string[] {
} }
function payload(): CreatePersonRequest { function payload(): CreatePersonRequest {
const fields: Record<string, unknown> = { ...customFields.value };
const nid = nationalId.value.trim();
if (nid) fields.nationalId = nid;
else delete fields.nationalId;
const cityVal = city.value.trim();
if (cityVal) fields.city = cityVal;
else delete fields.city;
const rastehRaw = rasteh.value.trim();
if (rastehRaw) {
const n = Number(rastehRaw);
fields.rasteh = Number.isFinite(n) && String(n) === rastehRaw ? n : rastehRaw;
} else delete fields.rasteh;
return { return {
firstName: firstName.value, firstName: firstName.value,
lastName: lastName.value, lastName: lastName.value,
@@ -363,7 +388,7 @@ function payload(): CreatePersonRequest {
companyId: companyId.value || null, companyId: companyId.value || null,
mood: mood.value, mood: mood.value,
groupIds: groupIds.value, groupIds: groupIds.value,
customFields: customFields.value, customFields: fields,
}; };
} }
@@ -545,6 +570,21 @@ onMounted(load);
<a-input v-model:value="referrer" placeholder="نام معرف" /> <a-input v-model:value="referrer" placeholder="نام معرف" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="12">
<a-form-item label="کد ملی">
<a-input v-model:value="nationalId" dir="ltr" placeholder="کد ملی (ته‌حساب)" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="شهر">
<a-input v-model:value="city" placeholder="شهر" />
</a-form-item>
</a-col>
<a-col :xs="24" :md="12">
<a-form-item label="رسته">
<a-input v-model:value="rasteh" dir="ltr" placeholder="رسته حساب ته‌حساب" />
</a-form-item>
</a-col>
</a-row> </a-row>
<a-divider orientation="right">آدرس‌ها</a-divider> <a-divider orientation="right">آدرس‌ها</a-divider>
+37 -1
View File
@@ -183,6 +183,18 @@ const externalCode = computed(() => {
} }
return ''; return '';
}); });
function customFieldText(...keys: string[]) {
const fields = person.value?.customFields ?? {};
for (const key of keys) {
const raw = fields[key];
if (typeof raw === 'string' && raw.trim()) return raw.trim();
if (typeof raw === 'number' && Number.isFinite(raw)) return String(raw);
}
return '';
}
const nationalIdLabel = computed(() => customFieldText('nationalId', 'CodeMelli', 'codeMeli'));
const cityLabel = computed(() => customFieldText('city', 'City'));
const rastehLabel = computed(() => customFieldText('rasteh', 'Rasteh'));
const SOURCE_LABELS: Record<string, string> = { const SOURCE_LABELS: Record<string, string> = {
manual: 'دستی', manual: 'دستی',
tahesab: 'ته‌حساب', tahesab: 'ته‌حساب',
@@ -444,6 +456,9 @@ const infoEmpty = computed(() => {
!p.instagram && !p.instagram &&
!p.birthDate && !p.birthDate &&
!p.referrer && !p.referrer &&
!nationalIdLabel.value &&
!cityLabel.value &&
!rastehLabel.value &&
!(p.addresses?.length) && !(p.addresses?.length) &&
!p.company && !p.company &&
!externalCode.value && !externalCode.value &&
@@ -794,6 +809,18 @@ watch(() => route.query.tab, readTab, { immediate: true });
<dt>معرف</dt> <dt>معرف</dt>
<dd>{{ person.referrer }}</dd> <dd>{{ person.referrer }}</dd>
</div> </div>
<div v-if="nationalIdLabel" class="fact">
<dt>کد ملی</dt>
<dd dir="ltr">{{ toFaDigits(nationalIdLabel) }}</dd>
</div>
<div v-if="cityLabel" class="fact">
<dt>شهر</dt>
<dd>{{ cityLabel }}</dd>
</div>
<div v-if="rastehLabel" class="fact">
<dt>رسته</dt>
<dd dir="ltr">{{ toFaDigits(rastehLabel) }}</dd>
</div>
<div v-if="person.website" class="fact"> <div v-if="person.website" class="fact">
<dt>وب‌سایت</dt> <dt>وب‌سایت</dt>
<dd dir="ltr">{{ person.website }}</dd> <dd dir="ltr">{{ person.website }}</dd>
@@ -1119,6 +1146,15 @@ watch(() => route.query.tab, readTab, { immediate: true });
<div><dt>وب‌سایت</dt><dd>{{ person.website || '—' }}</dd></div> <div><dt>وب‌سایت</dt><dd>{{ person.website || '—' }}</dd></div>
<div><dt>اینستاگرام</dt><dd dir="ltr">{{ person.instagram || '—' }}</dd></div> <div><dt>اینستاگرام</dt><dd dir="ltr">{{ person.instagram || '—' }}</dd></div>
<div><dt>معرف</dt><dd>{{ person.referrer || '—' }}</dd></div> <div><dt>معرف</dt><dd>{{ person.referrer || '—' }}</dd></div>
<div>
<dt>کد ملی</dt>
<dd dir="ltr">{{ nationalIdLabel ? toFaDigits(nationalIdLabel) : '—' }}</dd>
</div>
<div><dt>شهر</dt><dd>{{ cityLabel || '—' }}</dd></div>
<div>
<dt>رسته</dt>
<dd dir="ltr">{{ rastehLabel ? toFaDigits(rastehLabel) : '—' }}</dd>
</div>
<div class="wide"> <div class="wide">
<dt>آدرس‌ها</dt> <dt>آدرس‌ها</dt>
<dd> <dd>
@@ -1169,7 +1205,7 @@ watch(() => route.query.tab, readTab, { immediate: true });
:history-endpoint="`/people/${id}/sms-history`" :history-endpoint="`/people/${id}/sms-history`"
:name="fullName" :name="fullName"
:phone="phoneNumber" :phone="phoneNumber"
:record-title="fullName" :record-title="person.position?.trim() || ''"
:company="person.company?.name ?? ''" :company="person.company?.name ?? ''"
@close="smsOpen = false" @close="smsOpen = false"
/> />
+38 -24
View File
@@ -3,7 +3,7 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'; import { useRoute, useRouter } from 'vue-router';
import axios from 'axios'; import axios from 'axios';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { formatJalaliNumeric, toFaDigits } from '@/lib/jalali'; import { formatRelativeDayLabel, toFaDigits } from '@/lib/jalali';
import PipelineToolbar from '@/components/pipeline/PipelineToolbar.vue'; import PipelineToolbar from '@/components/pipeline/PipelineToolbar.vue';
import type { PipelineViewMode } from '@/components/pipeline/PipelineToolbar.vue'; import type { PipelineViewMode } from '@/components/pipeline/PipelineToolbar.vue';
import PipelineBoard from '@/components/pipeline/PipelineBoard.vue'; import PipelineBoard from '@/components/pipeline/PipelineBoard.vue';
@@ -108,6 +108,7 @@ const overlayAccent = ref<PipelineStage['color']>('green');
const overlayPos = ref({ x: 0, y: 0 }); const overlayPos = ref({ x: 0, y: 0 });
const menuOpenId = ref<string | null>(null); const menuOpenId = ref<string | null>(null);
const moving = ref(false); const moving = ref(false);
let dragSessionId: string | null = null;
const pipelineOptions = computed(() => const pipelineOptions = computed(() =>
pipelines.value.map((p) => ({ pipelines.value.map((p) => ({
@@ -164,9 +165,7 @@ function applyDealsSavedFilters(filters: Record<string, unknown>) {
} }
function formatDealDate(iso: string) { function formatDealDate(iso: string) {
const d = new Date(iso); return formatRelativeDayLabel(iso);
if (Number.isNaN(d.getTime())) return iso;
return formatJalaliNumeric(d);
} }
function findAccent(dealId: string): PipelineStage['color'] { function findAccent(dealId: string): PipelineStage['color'] {
@@ -245,13 +244,8 @@ function onPointerMove(event: PointerEvent | MouseEvent) {
function onDragStart(deal: PipelineDeal, event: DragEvent) { function onDragStart(deal: PipelineDeal, event: DragEvent) {
draggingColumnId.value = null; draggingColumnId.value = null;
draggingId.value = deal.id; if (moving.value) moving.value = false;
overlayDeal.value = deal; dragSessionId = deal.id;
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
event.dataTransfer?.setData('text/plain', deal.id); event.dataTransfer?.setData('text/plain', deal.id);
event.dataTransfer!.effectAllowed = 'move'; event.dataTransfer!.effectAllowed = 'move';
if (event.dataTransfer) { if (event.dataTransfer) {
@@ -260,12 +254,25 @@ function onDragStart(deal: PipelineDeal, event: DragEvent) {
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
event.dataTransfer.setDragImage(img, 0, 0); event.dataTransfer.setDragImage(img, 0, 0);
} }
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
// DOM را بعد از dragstart عوض کن تا کروم درگ را لغو نکند
window.setTimeout(() => {
if (dragSessionId !== deal.id) return;
draggingId.value = deal.id;
overlayDeal.value = deal;
}, 0);
} }
function onDragEnd() { function onDragEnd() {
const endedId = draggingId.value; const endedId = dragSessionId ?? draggingId.value;
window.setTimeout(() => { window.setTimeout(() => {
if (draggingId.value !== endedId) return; if (dragSessionId && dragSessionId !== endedId) return;
if (draggingId.value && draggingId.value !== endedId) return;
dragSessionId = null;
draggingId.value = null; draggingId.value = null;
dropStageId.value = null; dropStageId.value = null;
overlayDeal.value = null; overlayDeal.value = null;
@@ -310,23 +317,18 @@ async function applyUpdateDealStage(
async function onDrop(stageId: string, event: DragEvent, index?: number) { async function onDrop(stageId: string, event: DragEvent, index?: number) {
event.preventDefault(); event.preventDefault();
const transfer = event.dataTransfer?.getData('text/plain') || ''; const transfer = event.dataTransfer?.getData('text/plain') || '';
const draggedCardId = draggingId.value; const draggedCardId = dragSessionId || draggingId.value;
const columnId = draggingColumnId.value; const columnId = draggingColumnId.value;
dropStageId.value = null; dropStageId.value = null;
dragSessionId = null;
draggingId.value = null; draggingId.value = null;
overlayDeal.value = null; overlayDeal.value = null;
draggingColumnId.value = null; draggingColumnId.value = null;
const isStageDrag = transfer.startsWith('stage:'); // کارت بر payload ستون اولویت دارد
if (isStageDrag || (!transfer && !draggedCardId && columnId)) { const dealId =
const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId; draggedCardId || (transfer && !transfer.startsWith('stage:') ? transfer : '');
if (fromId) await reorderColumn(fromId, stageId); if (dealId) {
return;
}
const dealId = (!isStageDrag && transfer) || draggedCardId || '';
if (!dealId || moving.value) return;
const current = stages.value.find((stage) => stage.deals.some((deal) => deal.id === dealId)); const current = stages.value.find((stage) => stage.deals.some((deal) => deal.id === dealId));
if (current?.id === stageId && index == null) return; if (current?.id === stageId && index == null) return;
@@ -340,7 +342,19 @@ async function onDrop(stageId: string, event: DragEvent, index?: number) {
}); });
if (unchanged) return; if (unchanged) return;
// اگر جابه‌جایی قبلی هنوز در جریان است، این یکی را صف نکن — فقط رد نکن بی‌صدا با early return قدیمی
if (moving.value) {
moving.value = false;
}
await applyUpdateDealStage(dealId, stageId, index); await applyUpdateDealStage(dealId, stageId, index);
return;
}
const isStageDrag = transfer.startsWith('stage:');
if (isStageDrag || columnId) {
const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId;
if (fromId) await reorderColumn(fromId, stageId);
}
} }
function apiMessage(e: unknown, fallback: string) { function apiMessage(e: unknown, fallback: string) {
+31 -21
View File
@@ -56,6 +56,7 @@ const busy = ref(false);
const importMsg = ref(''); const importMsg = ref('');
const draggingId = ref<string | null>(null); const draggingId = ref<string | null>(null);
let dragSessionId: string | null = null;
const draggingColumnId = ref<string | null>(null); const draggingColumnId = ref<string | null>(null);
const dropStageId = ref<string | null>(null); const dropStageId = ref<string | null>(null);
const overlayDeal = ref<PipelineDeal | null>(null); const overlayDeal = ref<PipelineDeal | null>(null);
@@ -178,13 +179,8 @@ function onPointerMove(event: PointerEvent | MouseEvent) {
function onDragStart(deal: PipelineDeal, event: DragEvent) { function onDragStart(deal: PipelineDeal, event: DragEvent) {
draggingColumnId.value = null; draggingColumnId.value = null;
draggingId.value = deal.id; if (moving.value) moving.value = false;
overlayDeal.value = deal; dragSessionId = deal.id;
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
event.dataTransfer?.setData('text/plain', deal.id); event.dataTransfer?.setData('text/plain', deal.id);
event.dataTransfer!.effectAllowed = 'move'; event.dataTransfer!.effectAllowed = 'move';
if (event.dataTransfer) { if (event.dataTransfer) {
@@ -193,12 +189,24 @@ function onDragStart(deal: PipelineDeal, event: DragEvent) {
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
event.dataTransfer.setDragImage(img, 0, 0); event.dataTransfer.setDragImage(img, 0, 0);
} }
overlayAccent.value = findAccent(deal.id);
overlayPos.value = {
x: (event.clientX || 0) + 12,
y: (event.clientY || 0) + 12,
};
window.setTimeout(() => {
if (dragSessionId !== deal.id) return;
draggingId.value = deal.id;
overlayDeal.value = deal;
}, 0);
} }
function onDragEnd() { function onDragEnd() {
const endedId = draggingId.value; const endedId = dragSessionId ?? draggingId.value;
window.setTimeout(() => { window.setTimeout(() => {
if (draggingId.value !== endedId) return; if (dragSessionId && dragSessionId !== endedId) return;
if (draggingId.value && draggingId.value !== endedId) return;
dragSessionId = null;
draggingId.value = null; draggingId.value = null;
dropStageId.value = null; dropStageId.value = null;
overlayDeal.value = null; overlayDeal.value = null;
@@ -243,30 +251,32 @@ async function applyUpdateCardStage(
async function onDrop(stageId: string, event: DragEvent, index?: number) { async function onDrop(stageId: string, event: DragEvent, index?: number) {
event.preventDefault(); event.preventDefault();
const transfer = event.dataTransfer?.getData('text/plain') || ''; const transfer = event.dataTransfer?.getData('text/plain') || '';
const draggedCardId = draggingId.value; const draggedCardId = dragSessionId || draggingId.value;
const columnId = draggingColumnId.value; const columnId = draggingColumnId.value;
dropStageId.value = null; dropStageId.value = null;
dragSessionId = null;
draggingId.value = null; draggingId.value = null;
overlayDeal.value = null; overlayDeal.value = null;
draggingColumnId.value = null; draggingColumnId.value = null;
const isStageDrag = transfer.startsWith('stage:'); const cardId =
if (isStageDrag || (!transfer && !draggedCardId && columnId)) { draggedCardId || (transfer && !transfer.startsWith('stage:') ? transfer : '');
const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId; if (cardId) {
if (fromId) await reorderColumn(fromId, stageId);
return;
}
const cardId = (!isStageDrag && transfer) || draggedCardId || '';
if (!cardId || moving.value) return;
const current = stages.value.find((s) => s.deals.some((d) => d.id === cardId)); const current = stages.value.find((s) => s.deals.some((d) => d.id === cardId));
const currentIndex = current?.deals.findIndex((d) => d.id === cardId) ?? -1; const currentIndex = current?.deals.findIndex((d) => d.id === cardId) ?? -1;
if (current?.id === stageId && (index == null || index === currentIndex)) { if (current?.id === stageId && (index == null || index === currentIndex)) {
return; return;
} }
if (moving.value) moving.value = false;
await applyUpdateCardStage(cardId, stageId, index); await applyUpdateCardStage(cardId, stageId, index);
return;
}
const isStageDrag = transfer.startsWith('stage:');
if (isStageDrag || columnId) {
const fromId = isStageDrag ? transfer.slice('stage:'.length) : columnId;
if (fromId) await reorderColumn(fromId, stageId);
}
} }
function onAddCard(stageId: string) { function onAddCard(stageId: string) {
+47 -5
View File
@@ -148,6 +148,41 @@ async function saveAutoSync() {
autoSyncSaving.value = false; autoSyncSaving.value = false;
} }
} }
/** همهٔ مشتریان ته‌حساب را می‌خواند: تازه‌ها وارد، لینک‌شده‌ها پروفایل‌شان به‌روز می‌شود */
async function syncCustomersNow() {
if (!sync.connectionId) {
error.value = 'اتصال را انتخاب کنید.';
return;
}
syncBusy.value = true;
importOverlay.open = true;
importOverlay.progress = null;
importOverlay.message =
'در حال همگام‌سازی همهٔ مشتریان… نام، موبایل، کد ملی، آدرس، شهر، رسته و گروه به‌روز می‌شود.';
error.value = '';
ok.value = '';
try {
const { data } = await api.post<{
imported: number;
updated: number;
duplicate: number;
failed: number;
summary: string;
error: string | null;
}>('/integrations/tahesab/sync/customers-now', {
connectionId: sync.connectionId,
});
ok.value = data.summary;
if (data.error) error.value = data.error;
await load();
} catch (e) {
error.value = apiErr(e, 'همگام‌سازی مشتریان ناموفق بود');
} finally {
syncBusy.value = false;
importOverlay.open = false;
}
}
/** همان قاعدهٔ سرور: موبایل ایران 09… است، بقیهٔ شماره‌ها فقط رقم‌اند. */ /** همان قاعدهٔ سرور: موبایل ایران 09… است، بقیهٔ شماره‌ها فقط رقم‌اند. */
function customerPhoneKey(value?: string | null): string { function customerPhoneKey(value?: string | null): string {
const fa = '۰۱۲۳۴۵۶۷۸۹'; const fa = '۰۱۲۳۴۵۶۷۸۹';
@@ -1008,10 +1043,9 @@ onMounted(load);
<div class="sync-sub-section"> <div class="sync-sub-section">
<h4 class="sync-subhead">بروزرسانی خودکار</h4> <h4 class="sync-subhead">بروزرسانی خودکار</h4>
<p class="sync-sub-desc"> <p class="sync-sub-desc">
تعداد دفعات در روز و ساعت هر بار را برای همین اتصال مشخص کنید. سرور در آن ساعت‌ها، به وقت تهران، «همگام‌سازی الان» همهٔ مشتریان ته‌حساب را می‌خواند: تازه‌ها را وارد می‌کند و برای مشتری‌های از قبل
مشتریان تازه را وارد می‌کند و نام مشتری‌های قبلی را هم با ته‌حساب تازه می‌کند. اگر شماره یکی باشد لینک‌شده نام، موبایل، کد ملی، آدرس، شهر، رسته و گروه را از ته‌حساب تازه می‌کند. زمان‌بندی زیر
همان مشتری می‌ماند و کد دیگر به‌عنوان مشتری تازه وارد نمی‌شود. شماره به شکل ۰۹۱۲ ذخیره می‌شود. همان کار را در ساعت‌های انتخابی (به وقت تهران) تکرار می‌کند. خاموش یعنی فقط ورود دستی.
خاموش یعنی فقط ورود دستی.
</p> </p>
<UiField label="تعداد در روز"> <UiField label="تعداد در روز">
<UiSelect <UiSelect
@@ -1044,8 +1078,16 @@ onMounted(load);
</div> </div>
<div class="sync-buttons"> <div class="sync-buttons">
<UiButton <UiButton
:loading="syncBusy"
:disabled="!sync.connectionId || syncBusy || autoSyncSaving"
@click="syncCustomersNow"
>
همگام‌سازی الان (وارد + به‌روز کردن قبلی‌ها)
</UiButton>
<UiButton
variant="secondary"
:loading="autoSyncSaving" :loading="autoSyncSaving"
:disabled="!sync.connectionId" :disabled="!sync.connectionId || syncBusy"
@click="saveAutoSync" @click="saveAutoSync"
> >
ذخیره زمان‌بندی ذخیره زمان‌بندی
File diff suppressed because it is too large Load Diff
@@ -17,7 +17,8 @@ import {
} from '@/components/ui'; } from '@/components/ui';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali'; import { toFaDigits } from '@/lib/jalali';
import { PRIORITY_LABELS, ROUTINES_CTX, apiError, formatDayNumeric, todayKey } from '@/lib/routines'; import { useActivityPriorities } from '@/lib/activity-priorities';
import { ROUTINES_CTX, apiError, formatDayNumeric, todayKey } from '@/lib/routines';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
const shell = inject(ROUTINES_CTX)!; const shell = inject(ROUTINES_CTX)!;
@@ -73,7 +74,11 @@ const targetOptions = [
{ value: 'team' as const, label: 'همه اعضای یک تیم' }, { value: 'team' as const, label: 'همه اعضای یک تیم' },
]; ];
const priorities = Object.entries(PRIORITY_LABELS) as Array<[ActivityPriority, string]>; const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const priorities = computed(() =>
activityPriorities.items.value.map((r) => [r.key, r.label] as [ActivityPriority, string]),
);
const entityLinks = Object.entries(ROUTINE_ENTITY_LINK_LABELS) as Array<[RoutineEntityLink, string]>; const entityLinks = Object.entries(ROUTINE_ENTITY_LINK_LABELS) as Array<[RoutineEntityLink, string]>;
const reminderOptions = [ const reminderOptions = [
{ value: '', label: 'طبق تنظیمات هر کاربر' }, { value: '', label: 'طبق تنظیمات هر کاربر' },
@@ -7,8 +7,8 @@ import { UiBadge, UiEmptyState, UiSearch } from '@/components/ui';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { useAuthStore } from '@/stores/auth'; import { useAuthStore } from '@/stores/auth';
import { toFaDigits } from '@/lib/jalali'; import { toFaDigits } from '@/lib/jalali';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { import {
PRIORITY_LABELS,
PRIORITY_VARIANTS, PRIORITY_VARIANTS,
ROUTINES_CTX, ROUTINES_CTX,
apiError, apiError,
@@ -18,6 +18,8 @@ import {
} from '@/lib/routines'; } from '@/lib/routines';
const shell = inject(ROUTINES_CTX)!; const shell = inject(ROUTINES_CTX)!;
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const auth = useAuthStore(); const auth = useAuthStore();
const meId = computed(() => auth.user?.id ?? ''); const meId = computed(() => auth.user?.id ?? '');
@@ -80,7 +82,7 @@ const filtered = computed(() => {
<p v-if="r.description" class="desc">{{ r.description }}</p> <p v-if="r.description" class="desc">{{ r.description }}</p>
<div class="tags"> <div class="tags">
<UiBadge v-if="r.category" size="sm">{{ r.category.name }}</UiBadge> <UiBadge v-if="r.category" size="sm">{{ r.category.name }}</UiBadge>
<UiBadge size="sm" :variant="PRIORITY_VARIANTS[r.priority]">{{ PRIORITY_LABELS[r.priority] }}</UiBadge> <UiBadge size="sm" :variant="PRIORITY_VARIANTS[r.priority]">{{ activityPriorities.labelOf(r.priority) }}</UiBadge>
<UiBadge v-if="r.isMandatory" size="sm" variant="warning">اجباری</UiBadge> <UiBadge v-if="r.isMandatory" size="sm" variant="warning">اجباری</UiBadge>
<UiBadge v-if="r.reportRequired" size="sm" variant="info">گزارش الزامی</UiBadge> <UiBadge v-if="r.reportRequired" size="sm" variant="info">گزارش الزامی</UiBadge>
<UiBadge v-if="r.team" size="sm" variant="accent">تیم {{ r.team.name }}</UiBadge> <UiBadge v-if="r.team" size="sm" variant="accent">تیم {{ r.team.name }}</UiBadge>
@@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, inject, onMounted, reactive, ref, watch } from 'vue'; import { computed, inject, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { Select as ASelect } from 'ant-design-vue';
import type { RoutineCategoryDto, RoutineDto } from '@mento/shared'; import type { RoutineCategoryDto, RoutineDto } from '@mento/shared';
import UiIcon from '@/components/UiIcon.vue'; import UiIcon from '@/components/UiIcon.vue';
import UserAvatar from '@/components/UserAvatar.vue'; import UserAvatar from '@/components/UserAvatar.vue';
@@ -28,7 +29,8 @@ const loading = ref(true);
const error = ref(''); const error = ref('');
const q = ref(''); const q = ref('');
const status = ref<'all' | 'active' | 'inactive'>('all'); const status = ref<'all' | 'active' | 'inactive'>('all');
const assignee = ref(''); const assignee = ref<string | undefined>(undefined);
const creator = ref<string | undefined>(undefined);
const busyId = ref<string | null>(null); const busyId = ref<string | null>(null);
const menuFor = ref<string | null>(null); const menuFor = ref<string | null>(null);
@@ -60,6 +62,7 @@ const filtered = computed(() => {
if (status.value === 'active' && !r.isActive) return false; if (status.value === 'active' && !r.isActive) return false;
if (status.value === 'inactive' && r.isActive) return false; if (status.value === 'inactive' && r.isActive) return false;
if (assignee.value && r.assignee?.id !== assignee.value && `team:${r.team?.id}` !== assignee.value) return false; if (assignee.value && r.assignee?.id !== assignee.value && `team:${r.team?.id}` !== assignee.value) return false;
if (creator.value && (r.createdBy?.id ?? r.createdById) !== creator.value) return false;
if (term && !r.title.includes(term)) return false; if (term && !r.title.includes(term)) return false;
return true; return true;
}); });
@@ -208,21 +211,57 @@ async function deleteCat(c: RoutineCategoryDto) {
const users = computed(() => shell.context.value?.users ?? []); const users = computed(() => shell.context.value?.users ?? []);
const teams = computed(() => shell.context.value?.teams ?? []); const teams = computed(() => shell.context.value?.teams ?? []);
const assigneeFilterOptions = computed(() => [
...users.value.map((u) => ({ value: u.id, label: u.fullName })),
...teams.value.map((t) => ({ value: `team:${t.id}`, label: `تیم ${t.name}` })),
]);
const creatorFilterOptions = computed(() =>
users.value.map((u) => ({ value: u.id, label: u.fullName })),
);
function filterSelectOption(input: string, option?: { label?: string }) {
const q = input.trim().toLocaleLowerCase('fa');
if (!q) return true;
return String(option?.label ?? '')
.toLocaleLowerCase('fa')
.includes(q);
}
function selectPopupContainer(node: HTMLElement) {
return node.parentElement ?? document.body;
}
</script> </script>
<template> <template>
<div class="manage"> <div class="manage">
<div class="toolbar"> <div class="toolbar">
<UiSearch v-model="q" placeholder="جستجوی عنوان…" class="search" /> <UiSearch v-model="q" placeholder="جستجوی عنوان…" class="search" />
<UiSelect v-model="assignee" size="sm" class="who"> <div class="who">
<option value="">همه مسئول‌ها</option> <ASelect
<optgroup label="کاربران"> v-model:value="assignee"
<option v-for="u in users" :key="u.id" :value="u.id">{{ u.fullName }}</option> allow-clear
</optgroup> show-search
<optgroup v-if="teams.length" label="تیم‌ها"> placeholder="همه مسئول‌ها"
<option v-for="t in teams" :key="t.id" :value="`team:${t.id}`">{{ t.name }}</option> :options="assigneeFilterOptions"
</optgroup> :filter-option="filterSelectOption"
</UiSelect> :get-popup-container="selectPopupContainer"
style="width: 100%"
/>
</div>
<div class="who">
<ASelect
v-model:value="creator"
allow-clear
show-search
placeholder="همه سازنده‌ها"
:options="creatorFilterOptions"
:filter-option="filterSelectOption"
:get-popup-container="selectPopupContainer"
style="width: 100%"
/>
</div>
<UiSegmented v-model="status" :options="statusOptions" /> <UiSegmented v-model="status" :options="statusOptions" />
<span class="spacer" /> <span class="spacer" />
<UiButton variant="ghost" size="sm" @click="catsOpen = true; editCat(null)"> <UiButton variant="ghost" size="sm" @click="catsOpen = true; editCat(null)">
@@ -259,6 +298,7 @@ const teams = computed(() => shell.context.value?.teams ?? []);
<tr> <tr>
<th>عنوان</th> <th>عنوان</th>
<th>مسئول</th> <th>مسئول</th>
<th>سازنده</th>
<th>تکرار</th> <th>تکرار</th>
<th>ساعت</th> <th>ساعت</th>
<th>وضعیت</th> <th>وضعیت</th>
@@ -288,6 +328,13 @@ const teams = computed(() => shell.context.value?.teams ?? []);
{{ r.assignee.fullName }} {{ r.assignee.fullName }}
</span> </span>
</td> </td>
<td>
<span v-if="r.createdBy" class="who-cell">
<UserAvatar :name="r.createdBy.fullName" :user-id="r.createdBy.id" :size="24" />
{{ r.createdBy.fullName }}
</span>
<span v-else>—</span>
</td>
<td class="nowrap">{{ r.recurrenceLabel }}</td> <td class="nowrap">{{ r.recurrenceLabel }}</td>
<td class="nowrap">{{ toFaDigits(r.timeOfDay) }}</td> <td class="nowrap">{{ toFaDigits(r.timeOfDay) }}</td>
<td> <td>
@@ -9,9 +9,9 @@ import RoutineTaskModals from '@/components/routines/RoutineTaskModals.vue';
import { UiBadge, UiButton, UiEmptyState, UiSelect } from '@/components/ui'; import { UiBadge, UiButton, UiEmptyState, UiSelect } from '@/components/ui';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali'; import { toFaDigits } from '@/lib/jalali';
import { useActivityPriorities } from '@/lib/activity-priorities';
import { import {
ENTITY_TYPE_LABELS, ENTITY_TYPE_LABELS,
PRIORITY_LABELS,
PRIORITY_VARIANTS, PRIORITY_VARIANTS,
ROUTINES_CTX, ROUTINES_CTX,
apiError, apiError,
@@ -24,6 +24,8 @@ import {
import { useRoutineTaskActions } from '@/lib/useRoutineTaskActions'; import { useRoutineTaskActions } from '@/lib/useRoutineTaskActions';
const shell = inject(ROUTINES_CTX)!; const shell = inject(ROUTINES_CTX)!;
const activityPriorities = useActivityPriorities();
void activityPriorities.load();
const items = ref<RoutineTaskDto[]>([]); const items = ref<RoutineTaskDto[]>([]);
const loading = ref(true); const loading = ref(true);
@@ -133,7 +135,7 @@ const showAssignee = computed(() => isManager.value && who.value !== '');
</span> </span>
</td> </td>
<td> <td>
<UiBadge size="sm" :variant="PRIORITY_VARIANTS[t.priority]">{{ PRIORITY_LABELS[t.priority] }}</UiBadge> <UiBadge size="sm" :variant="PRIORITY_VARIANTS[t.priority]">{{ activityPriorities.labelOf(t.priority) }}</UiBadge>
</td> </td>
<td> <td>
<RouterLink <RouterLink
+179 -24
View File
@@ -6,15 +6,21 @@ import type { FinancialAccountDto, FinancialCategoryDto, FinancialDocumentDto }
import { UiButton, UiCard, UiField, UiInput, UiPageHeader } from '@/components/ui'; import { UiButton, UiCard, UiField, UiInput, UiPageHeader } from '@/components/ui';
import MoneyInput from '@/components/MoneyInput.vue'; import MoneyInput from '@/components/MoneyInput.vue';
import TreasuryNav from '@/components/treasury/TreasuryNav.vue'; import TreasuryNav from '@/components/treasury/TreasuryNav.vue';
import { FormFileTooLargeError, prepareFormFieldFile } from '@/lib/form-file-compress';
import { toman } from './treasury-format'; import { toman } from './treasury-format';
const props = defineProps<{ kind: 'income' | 'expense' }>(); 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 rows = ref<FinancialDocumentDto[]>([]);
const categories = ref<FinancialCategoryDto[]>([]); const categories = ref<FinancialCategoryDto[]>([]);
const accounts = ref<FinancialAccountDto[]>([]); const accounts = ref<FinancialAccountDto[]>([]);
const error = ref(''); const error = ref('');
const ok = ref(''); const ok = ref('');
const saving = ref(false); const saving = ref(false);
const photoBusy = ref(false);
const pendingPhotos = ref<PendingPhoto[]>([]);
const q = ref(''); const q = ref('');
const form = ref({ const form = ref({
title: '', title: '',
@@ -43,6 +49,76 @@ function apiMessage(e: unknown) {
return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.'; 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() { async function load() {
const [docs, cats, acc] = await Promise.all([ const [docs, cats, acc] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind: props.kind, q: q.value || undefined } }), api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind: props.kind, q: q.value || undefined } }),
@@ -59,7 +135,7 @@ async function createDoc() {
error.value = ''; error.value = '';
ok.value = ''; ok.value = '';
try { try {
await api.post('/treasury/documents', { const { data } = await api.post<FinancialDocumentDto>('/treasury/documents', {
kind: props.kind, kind: props.kind,
title: form.value.title, title: form.value.title,
amount: form.value.amount, amount: form.value.amount,
@@ -71,18 +147,22 @@ async function createDoc() {
reference: form.value.reference || null, reference: form.value.reference || null,
notes: form.value.notes || null, notes: form.value.notes || null,
}); });
form.value = { const photos = [...pendingPhotos.value];
title: '', let attached = 0;
amount: '', for (const photo of photos) {
categoryId: '', try {
partyName: '', await uploadPreparedFile(data.id, photo.file);
accountId: '', attached += 1;
settleAmount: '', } catch (e) {
method: 'transfer', error.value = apiMessage(e);
reference: '', break;
notes: '', }
}; }
ok.value = 'سند ثبت شد. اگر مبلغ دریافت/پرداخت صفر باشد موجودی حساب تغییر نمی‌کند.'; resetForm();
ok.value =
attached > 0
? `سند ثبت شد و ${attached} عکس پیوست شد.`
: 'سند ثبت شد. اگر مبلغ دریافت/پرداخت صفر باشد موجودی حساب تغییر نمی‌کند.';
await load(); await load();
} catch (e) { } catch (e) {
error.value = apiMessage(e); error.value = apiMessage(e);
@@ -115,16 +195,22 @@ async function downloadAttachment(id: string, fileName: string) {
} }
async function upload(id: string, event: Event) { 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; if (!file) return;
const body = new FormData(); error.value = '';
body.append('file', file); ok.value = '';
photoBusy.value = true;
try { try {
await api.post(`/treasury/documents/${id}/attachments`, body); const prepared = await prepareTreasuryImage(file);
ok.value = 'پیوست ذخیره شد.'; await uploadPreparedFile(id, prepared.file);
ok.value = 'عکس پیوست ذخیره شد.';
await load(); await load();
} catch (e) { } 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, () => { watch(() => props.kind, () => {
resetForm();
error.value = '';
ok.value = '';
void load(); void load();
}); });
@@ -184,8 +273,30 @@ onMounted(() => {
</UiField> </UiField>
<UiField label="پیگیری"><UiInput v-model="form.reference" /></UiField> <UiField label="پیگیری"><UiInput v-model="form.reference" /></UiField>
</div> </div>
<UiButton :loading="saving" @click="createDoc">ثبت</UiButton> <div class="photos">
<UiButton variant="secondary" @click="downloadExcel">خروجی اکسل</UiButton> <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> </UiCard>
<UiField label="جستجو"><UiInput v-model="q" @change="load" /></UiField> <UiField label="جستجو"><UiInput v-model="q" @change="load" /></UiField>
<div class="list"> <div class="list">
@@ -210,9 +321,9 @@ onMounted(() => {
> >
{{ file.fileName }} {{ file.fileName }}
</button> </button>
<label v-if="row.status !== 'void'" class="file"> <label v-if="row.status !== 'void'" class="file" :class="{ busy: photoBusy }">
پیوست {{ photoBusy ? '…' : 'عکس پیوست' }}
<input type="file" @change="upload(row.id, $event)" /> <input type="file" accept="image/*" :disabled="photoBusy || saving" @change="upload(row.id, $event)" />
</label> </label>
</div> </div>
</article> </article>
@@ -231,7 +342,51 @@ onMounted(() => {
.side { display: grid; justify-items: end; gap: 0.3rem; } .side { display: grid; justify-items: end; gap: 0.3rem; }
.side button, .file { border: 0; background: transparent; color: #b91c1c; cursor: pointer; font: inherit; } .side button, .file { border: 0; background: transparent; color: #b91c1c; cursor: pointer; font: inherit; }
.file { color: #0f766e; font-weight: 700; } .file { color: #0f766e; font-weight: 700; }
.file.busy { opacity: 0.6; pointer-events: none; }
.file input { display: 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; } .err { color: #b91c1c; font-weight: 700; }
.ok { color: #0f766e; font-weight: 700; } .ok { color: #0f766e; font-weight: 700; }
</style> </style>
@@ -6,13 +6,10 @@ import {
Button as AButton, Button as AButton,
Card as ACard, Card as ACard,
Col as ACol, Col as ACol,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex, Flex as AFlex,
Form as AForm, Form as AForm,
FormItem as AFormItem, FormItem as AFormItem,
Input as AInput, Input as AInput,
List as AList,
Row as ARow, Row as ARow,
Segmented as ASegmented, Segmented as ASegmented,
Select as ASelect, Select as ASelect,
@@ -30,16 +27,20 @@ import type {
} from '@mento/shared'; } from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.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 TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue'; import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
import { useSettleDefault } from '@/components/treasury/useSettleDefault'; 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 { useTreasuryMobile } from './useTreasuryMobile';
import { parseMoneyNumber } from '@/lib/money'; import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography; const { Text: ATypographyText } = Typography;
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option; const ASelectOption = ASelect.Option;
const isMobile = useTreasuryMobile(); const isMobile = useTreasuryMobile();
@@ -52,6 +53,7 @@ const accounts = ref<FinancialAccountDto[]>([]);
const error = ref(''); const error = ref('');
const ok = ref(''); const ok = ref('');
const saving = ref(false); const saving = ref(false);
const pendingPhotos = ref<TreasuryPendingPhoto[]>([]);
const q = ref(''); const q = ref('');
const form = ref({ const form = ref({
title: '', title: '',
@@ -95,17 +97,6 @@ function apiMessage(e: unknown) {
return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.'; 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() { async function load() {
const [docs, cats, acc, bals, receivables] = await Promise.all([ const [docs, cats, acc, bals, receivables] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }), api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
@@ -202,7 +193,17 @@ async function createDoc() {
notes: form.value.notes || null, notes: form.value.notes || null,
bookedAt: form.value.bookedAt || undefined, 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(); settleMirror.reset();
pendingPhotos.value = [];
form.value = { form.value = {
title: '', title: '',
amount: '', amount: '',
@@ -215,11 +216,12 @@ async function createDoc() {
notes: '', notes: '',
bookedAt: formatLocalDateInput(new Date()), bookedAt: formatLocalDateInput(new Date()),
}; };
ok.value = collectsBalance const base = collectsBalance
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.` ? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
: data.reference : data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}` ? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.'; : 'سند ثبت شد.';
ok.value = attached > 0 ? `${base} ${attached} عکس پیوست شد.` : base;
await load(); await load();
} catch (e) { } catch (e) {
error.value = apiMessage(e); error.value = apiMessage(e);
@@ -279,15 +281,13 @@ const partyPosition = computed(() => {
return partyNetPosition(receivable, payable); return partyNetPosition(receivable, payable);
}); });
async function voidDoc(id: string) { const selectedAccountBalance = computed(() => {
if (!window.confirm('این سند و گردش متصل به آن باطل شود؟')) return; const id = form.value.accountId;
try { if (!id) return null;
await api.post(`/treasury/documents/${id}/void`, { reason: 'ابطال توسط مدیر' }); const account = accounts.value.find((row) => row.id === id);
await load(); if (!account) return null;
} catch (e) { return accountBalanceTone(account.balance);
error.value = apiMessage(e); });
}
}
onMounted(() => { onMounted(() => {
void load().catch(() => { void load().catch(() => {
@@ -301,11 +301,10 @@ onMounted(() => {
<a-alert v-if="error" type="error" show-icon :message="error" /> <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="ok" type="success" show-icon :message="ok" />
<a-card :bordered="false"> <a-card :bordered="false" title="سند جدید">
<a-flex align="center" justify="space-between" wrap="wrap" gap="small"> <template #extra>
<a-typography-text strong>سند جدید</a-typography-text>
<a-segmented v-model:value="entryMode" :options="entryOptions" /> <a-segmented v-model:value="entryMode" :options="entryOptions" />
</a-flex> </template>
<a-form <a-form
layout="vertical" layout="vertical"
:model="form" :model="form"
@@ -339,7 +338,8 @@ onMounted(() => {
<a-input v-model:value="form.title" /> <a-input v-model:value="form.title" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item <a-form-item
label="مبلغ کل" label="مبلغ کل"
name="amount" name="amount"
@@ -348,7 +348,7 @@ onMounted(() => {
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" /> <MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item <a-form-item
:label="settleLabel" :label="settleLabel"
name="settleAmount" name="settleAmount"
@@ -362,14 +362,22 @@ onMounted(() => {
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8"> <a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="مانده این سند"> <a-form-item label="مانده این سند">
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text> <MoneyInput
addon-after="تومان"
:model-value="remainingAmount"
:decimals="0"
disabled
/>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId"> <a-form-item label="دسته‌بندی" name="categoryId">
<a-select show-search option-filter-prop="label" <a-select
show-search
option-filter-prop="label"
v-model:value="form.categoryId" v-model:value="form.categoryId"
allow-clear allow-clear
style="width: 100%" style="width: 100%"
@@ -381,9 +389,22 @@ onMounted(() => {
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="حساب" name="accountId" :rules="accountRules"> <a-form-item name="accountId" :rules="accountRules">
<a-select show-search option-filter-prop="label" <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"
>
{{ selectedAccountBalance.text }}
</a-typography-text>
</a-flex>
</template>
<a-select
show-search
option-filter-prop="label"
v-model:value="form.accountId" v-model:value="form.accountId"
allow-clear allow-clear
style="width: 100%" style="width: 100%"
@@ -395,7 +416,7 @@ onMounted(() => {
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="روش" name="method"> <a-form-item label="روش" name="method">
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%"> <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"> <a-select-option v-for="opt in methodOptions" :key="opt.value" :value="opt.value" :label="opt.label">
@@ -404,84 +425,38 @@ onMounted(() => {
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تاریخ" name="bookedAt"> <a-form-item label="تاریخ" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" /> <JalaliDateInput v-model="form.bookedAt" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :span="24"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="توضیحات" name="notes"> <a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" /> <a-input v-model:value="form.notes" />
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> <a-col :xs="24" :sm="12" :md="8">
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button> <a-form-item label="عکس فاکتور / رسید">
</a-form> <TreasuryDocPhotoField v-model="pendingPhotos" :disabled="saving" />
<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-form-item>
</a-col> </a-col>
</a-row> </a-row>
<a-space>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-space>
</a-form> </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-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> </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> </a-flex>
</template> </template>
@@ -6,14 +6,11 @@ import {
Button as AButton, Button as AButton,
Card as ACard, Card as ACard,
Col as ACol, Col as ACol,
Divider as ADivider,
Empty as AEmpty,
Flex as AFlex, Flex as AFlex,
Form as AForm, Form as AForm,
FormItem as AFormItem, FormItem as AFormItem,
Grid, Grid,
Input as AInput, Input as AInput,
List as AList,
Row as ARow, Row as ARow,
Segmented as ASegmented, Segmented as ASegmented,
Select as ASelect, Select as ASelect,
@@ -31,15 +28,19 @@ import type {
} from '@mento/shared'; } from '@mento/shared';
import JalaliDateInput from '@/components/JalaliDateInput.vue'; import JalaliDateInput from '@/components/JalaliDateInput.vue';
import MoneyInput from '@/components/MoneyInput.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 TreasuryPartyBalanceTable from '@/components/treasury/TreasuryPartyBalanceTable.vue';
import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue'; import TreasuryPartySelect from '@/components/treasury/TreasuryPartySelect.vue';
import { useSettleDefault } from '@/components/treasury/useSettleDefault'; 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'; import { parseMoneyNumber } from '@/lib/money';
const { Text: ATypographyText } = Typography; const { Text: ATypographyText } = Typography;
const AListItem = AList.Item;
const AListItemMeta = AList.Item.Meta;
const ASelectOption = ASelect.Option; const ASelectOption = ASelect.Option;
const screens = Grid.useBreakpoint(); const screens = Grid.useBreakpoint();
const isMobile = computed(() => !screens.value.md); const isMobile = computed(() => !screens.value.md);
@@ -53,6 +54,7 @@ const accounts = ref<FinancialAccountDto[]>([]);
const error = ref(''); const error = ref('');
const ok = ref(''); const ok = ref('');
const saving = ref(false); const saving = ref(false);
const pendingPhotos = ref<TreasuryPendingPhoto[]>([]);
const q = ref(''); const q = ref('');
function emptyForm() { function emptyForm() {
@@ -130,6 +132,14 @@ const partyPosition = computed(() => {
return partyNetPosition(receivable, payable); 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, () => { watch(entryMode, () => {
settleMirror.reset(); settleMirror.reset();
form.value.amount = ''; form.value.amount = '';
@@ -156,17 +166,6 @@ function apiMessage(e: unknown) {
return Array.isArray(msg) ? msg.join('، ') : msg || 'ذخیره ناموفق بود.'; 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() { async function load() {
const [docs, cats, acc, bals, payables] = await Promise.all([ const [docs, cats, acc, bals, payables] = await Promise.all([
api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }), api.get<FinancialDocumentDto[]>('/treasury/documents', { params: { kind, q: q.value || undefined } }),
@@ -201,6 +200,7 @@ async function load() {
function resetForm() { function resetForm() {
settleMirror.reset(); settleMirror.reset();
form.value = emptyForm(); form.value = emptyForm();
pendingPhotos.value = [];
error.value = ''; error.value = '';
ok.value = ''; ok.value = '';
} }
@@ -266,12 +266,22 @@ async function createDoc() {
notes: form.value.notes || null, notes: form.value.notes || null,
bookedAt: form.value.bookedAt || undefined, 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(); resetForm();
ok.value = collectsBalance const base = collectsBalance
? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.` ? `${toman(settleAmount)} از ماندهٔ طرف حساب کم شد.`
: data.reference : data.reference
? `سند ثبت شد. شماره پیگیری: ${data.reference}` ? `سند ثبت شد. شماره پیگیری: ${data.reference}`
: 'سند ثبت شد.'; : 'سند ثبت شد.';
ok.value = attached > 0 ? `${base} ${attached} عکس پیوست شد.` : base;
await load(); await load();
} catch (e) { } catch (e) {
error.value = apiMessage(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(() => { onMounted(() => {
void load().catch(() => { void load().catch(() => {
error.value = 'بارگذاری ناموفق بود.'; error.value = 'بارگذاری ناموفق بود.';
@@ -302,11 +302,10 @@ onMounted(() => {
<a-alert v-if="error" type="error" show-icon :message="error" /> <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="ok" type="success" show-icon :message="ok" />
<a-card :bordered="false"> <a-card :bordered="false" title="سند جدید">
<a-flex align="center" justify="space-between" wrap="wrap" gap="small"> <template #extra>
<a-typography-text strong>سند جدید</a-typography-text>
<a-segmented v-model:value="entryMode" :options="entryOptions" /> <a-segmented v-model:value="entryMode" :options="entryOptions" />
</a-flex> </template>
<a-form <a-form
layout="vertical" layout="vertical"
:model="form" :model="form"
@@ -340,7 +339,8 @@ onMounted(() => {
<a-input v-model:value="form.title" /> <a-input v-model:value="form.title" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item <a-form-item
label="مبلغ کل" label="مبلغ کل"
name="amount" name="amount"
@@ -349,7 +349,7 @@ onMounted(() => {
<MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" /> <MoneyInput addon-after="تومان" v-model="form.amount" :decimals="0" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item <a-form-item
:label="settleLabel" :label="settleLabel"
name="settleAmount" name="settleAmount"
@@ -363,14 +363,22 @@ onMounted(() => {
/> />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8"> <a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="مانده این سند"> <a-form-item label="مانده این سند">
<a-typography-text>{{ toman(remainingAmount) }}</a-typography-text> <MoneyInput
addon-after="تومان"
:model-value="remainingAmount"
:decimals="0"
disabled
/>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :xs="24" :md="8">
<a-col v-if="!isSettlement" :xs="24" :sm="12" :md="8">
<a-form-item label="دسته‌بندی" name="categoryId"> <a-form-item label="دسته‌بندی" name="categoryId">
<a-select show-search option-filter-prop="label" <a-select
show-search
option-filter-prop="label"
v-model:value="form.categoryId" v-model:value="form.categoryId"
allow-clear allow-clear
style="width: 100%" style="width: 100%"
@@ -382,9 +390,22 @@ onMounted(() => {
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="حساب" name="accountId" :rules="accountRules"> <a-form-item name="accountId" :rules="accountRules">
<a-select show-search option-filter-prop="label" <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"
>
{{ selectedAccountBalance.text }}
</a-typography-text>
</a-flex>
</template>
<a-select
show-search
option-filter-prop="label"
v-model:value="form.accountId" v-model:value="form.accountId"
allow-clear allow-clear
style="width: 100%" style="width: 100%"
@@ -401,7 +422,7 @@ onMounted(() => {
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="روش" name="method"> <a-form-item label="روش" name="method">
<a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%"> <a-select show-search option-filter-prop="label" v-model:value="form.method" style="width: 100%">
<a-select-option <a-select-option
@@ -415,83 +436,38 @@ onMounted(() => {
</a-select> </a-select>
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col :xs="24" :md="8"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="تاریخ" name="bookedAt"> <a-form-item label="تاریخ" name="bookedAt">
<JalaliDateInput v-model="form.bookedAt" /> <JalaliDateInput v-model="form.bookedAt" />
</a-form-item> </a-form-item>
</a-col> </a-col>
<a-col v-if="!isSettlement" :xs="24" :md="16"> <a-col :xs="24" :sm="12" :md="8">
<a-form-item label="توضیحات" name="notes"> <a-form-item label="توضیحات" name="notes">
<a-input v-model:value="form.notes" /> <a-input v-model:value="form.notes" />
</a-form-item> </a-form-item>
</a-col> </a-col>
</a-row> <a-col :xs="24" :sm="12" :md="8">
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button> <a-form-item label="عکس فاکتور / رسید">
</a-form> <TreasuryDocPhotoField v-model="pendingPhotos" :disabled="saving" />
<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-form-item>
</a-col> </a-col>
</a-row> </a-row>
<a-space>
<a-button type="primary" html-type="submit" :block="isMobile" :loading="saving">ثبت</a-button>
</a-space>
</a-form> </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-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> </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> </a-flex>
</template> </template>
@@ -11,3 +11,13 @@ export function partyNetPosition(receivable: number, payable: number) {
if (net < 0) return { text: `بس ${toman(-net)}`, type: 'success' as const }; if (net < 0) return { text: `بس ${toman(-net)}`, type: 'success' as const };
return { text: `مانده ${toman(0)}`, type: 'secondary' 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 };
}
+166 -6
View File
@@ -646,14 +646,17 @@ export const DATA_ACCESS_LEGACY_SCOPE: Record<DataAccessSection, DataScope | nul
}; };
/** /**
* یک قانون: فیلدهای پرشده با AND. * یک قانون: فیلدهای پرشده با OR (هر بُعد کافی است).
* قوانین متعدد در SectionDataAccess با OR ترکیب می‌شوند. * قوانین متعدد در SectionDataAccess هم با OR ترکیب می‌شوند.
* ابعاد بلااستفاده برای یک بخش نادیده گرفته می‌شوند. * ابعاد بلااستفاده برای یک بخش نادیده گرفته می‌شوند.
*/ */
export type DataAccessRule = { export type DataAccessRule = {
/** self / team → مالک / مسئول / نویسنده (بسته به بخش) */ /** self / team → مالک / مسئول / نویسنده (بسته به بخش) */
owners?: DataAccessOwnerKind[]; owners?: DataAccessOwnerKind[];
/** مشتریان: گروه‌ها */ /**
* @deprecated دید گروه مشتریان از مسئول‌گروه است، نه این فیلد.
* در پارس باقی می‌ماند برای سازگاری؛ در فیلتر دسترسی نادیده گرفته می‌شود.
*/
groupIds?: string[]; groupIds?: string[];
/** مشتریان: importSource/sourceRef · لیدها: source · یادداشت: noteType · تیکت: status */ /** مشتریان: importSource/sourceRef · لیدها: source · یادداشت: noteType · تیکت: status */
sources?: string[]; sources?: string[];
@@ -889,6 +892,7 @@ export type RolePermissionKey =
| "treasury_reports" | "treasury_reports"
| "treasury_audit" | "treasury_audit"
| "treasury_categories" | "treasury_categories"
| "treasury_documents_manage"
| "behavior"; | "behavior";
/** بخشی که مسئولش را می‌شود به کاربر دیگری داد */ /** بخشی که مسئولش را می‌شود به کاربر دیگری داد */
@@ -944,6 +948,7 @@ export const ROLE_PERMISSION_ITEMS: Array<{
{ key: "treasury_reports", label: "مالی — گزارش" }, { key: "treasury_reports", label: "مالی — گزارش" },
{ key: "treasury_audit", label: "مالی — سوابق" }, { key: "treasury_audit", label: "مالی — سوابق" },
{ key: "treasury_categories", label: "مالی — دسته‌بندی" }, { key: "treasury_categories", label: "مالی — دسته‌بندی" },
{ key: "treasury_documents_manage", label: "مالی — ویرایش و حذف اسناد" },
{ key: "behavior", label: "شخصیت‌شناسی و دستیار فروش" }, { key: "behavior", label: "شخصیت‌شناسی و دستیار فروش" },
]; ];
@@ -987,6 +992,15 @@ export function treasurySectionAllowed(
return perms.includes(section); return perms.includes(section);
} }
/** ویرایش/حذف اسناد مالی — مالک، مدیر، یا کلید اختصاصی در نقش/override */
export function canManageTreasuryDocuments(
role: string | null | undefined,
permissions: readonly string[] | null | undefined,
): boolean {
if (role === "owner" || role === "admin") return true;
return (permissions ?? []).includes("treasury_documents_manage");
}
export interface OrgRoleMemberDto { export interface OrgRoleMemberDto {
id: string; id: string;
fullName: string; fullName: string;
@@ -1324,6 +1338,11 @@ export interface CustomerGroupSummaryDto {
source?: "manual" | "tahesab"; source?: "manual" | "tahesab";
} }
export interface CustomerGroupAssigneeDto {
id: string;
fullName: string;
}
export interface CustomerGroupDto { export interface CustomerGroupDto {
id: string; id: string;
name: string; name: string;
@@ -1336,11 +1355,14 @@ export interface CustomerGroupDto {
/** گروه اصلی؛ خالی یعنی خودش اصلی است */ /** گروه اصلی؛ خالی یعنی خودش اصلی است */
parentId?: string | null; parentId?: string | null;
parentName?: string | null; parentName?: string | null;
/** مسئولان گروه (اختیاری) */
assignees: CustomerGroupAssigneeDto[];
} }
export interface CreateCustomerGroupRequest { export interface CreateCustomerGroupRequest {
name: string; name: string;
color?: CustomerGroupColor; color?: CustomerGroupColor;
assigneeIds?: string[];
} }
export interface UpdateCustomerGroupRequest { export interface UpdateCustomerGroupRequest {
@@ -1348,6 +1370,8 @@ export interface UpdateCustomerGroupRequest {
color?: CustomerGroupColor; color?: CustomerGroupColor;
/** null = برداشتن گروه اصلی */ /** null = برداشتن گروه اصلی */
parentId?: string | null; parentId?: string | null;
/** جایگزینی کامل فهرست مسئولان */
assigneeIds?: string[];
} }
export interface CompanySummaryDto { export interface CompanySummaryDto {
@@ -1613,6 +1637,13 @@ export interface DealDto {
lineItems: DealLineItemDto[]; lineItems: DealLineItemDto[];
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
/**
* فقط در برد کانبان پر می‌شود:
* none=بدون فعالیت، overdue=عقب‌افتاده، upcoming=آینده، done=انجام‌شده
*/
activityCue?: DealActivityCue;
/** لیست مرتب‌شدهٔ فعالیت‌های باز/انجام‌شده برای پاپ‌آپ کارت */
activitySummaries?: DealActivitySummaryDto[];
} }
export interface PipelineBoardStageDto extends PipelineStageDto { export interface PipelineBoardStageDto extends PipelineStageDto {
@@ -1839,7 +1870,86 @@ export interface MoveDealRequest {
export type ActivityType = "call" | "meeting" | "task" | "note"; export type ActivityType = "call" | "meeting" | "task" | "note";
export type ActivityStatus = "open" | "done" | "canceled"; export type ActivityStatus = "open" | "done" | "canceled";
/** وضعیت فعالیت مرتبط با معامله برای نشانگر کارت کانبان */
export type DealActivityCue = "none" | "upcoming" | "overdue" | "done";
/** خلاصهٔ کوتاه فعالیت روی کارت معامله */
export interface DealActivitySummaryDto {
id: string;
title: string;
type: ActivityType;
status: ActivityStatus;
dueAt: string | null;
/** وضعیت نسبی همین آیتم برای رنگ نقطه */
cue: Exclude<DealActivityCue, "none">;
}
export type ActivityPriority = "very_low" | "low" | "medium" | "high" | "very_high"; export type ActivityPriority = "very_low" | "low" | "medium" | "high" | "very_high";
/** ترتیب نمایش ثابت (تعداد تغییر نمی‌کند) */
export const ACTIVITY_PRIORITY_KEYS: ActivityPriority[] = [
"very_high",
"high",
"medium",
"low",
"very_low",
];
export type ActivityPrioritySetting = {
key: ActivityPriority;
label: string;
/** رنگ متن/پرچم — #RRGGBB */
color: string;
};
export const DEFAULT_ACTIVITY_PRIORITY_SETTINGS: ActivityPrioritySetting[] = [
{ key: "very_high", label: "خیلی زیاد", color: "#dc2626" },
{ key: "high", label: "زیاد", color: "#ea580c" },
{ key: "medium", label: "متوسط", color: "#eab308" },
{ key: "low", label: "کم", color: "#16a34a" },
{ key: "very_low", label: "خیلی کم", color: "#94a3b8" },
];
const PRIORITY_KEY_SET = new Set<string>(ACTIVITY_PRIORITY_KEYS);
const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
/** ادغام تنظیم ذخیره‌شده با پیش‌فرض‌ها؛ همیشه ۵ سطح کامل */
export function parseActivityPrioritySettings(raw: unknown): ActivityPrioritySetting[] {
const overrides = new Map<ActivityPriority, { label?: string; color?: string }>();
const bag =
raw && typeof raw === "object" && !Array.isArray(raw)
? (raw as Record<string, unknown>)
: Array.isArray(raw)
? Object.fromEntries(
raw
.filter((r): r is Record<string, unknown> => !!r && typeof r === "object")
.map((r) => [String(r.key ?? ""), r]),
)
: {};
for (const [key, val] of Object.entries(bag)) {
if (!PRIORITY_KEY_SET.has(key) || !val || typeof val !== "object" || Array.isArray(val)) continue;
const row = val as Record<string, unknown>;
const label = typeof row.label === "string" ? row.label.trim() : "";
const color = typeof row.color === "string" ? row.color.trim() : "";
overrides.set(key as ActivityPriority, {
...(label ? { label: label.slice(0, 40) } : {}),
...(HEX_COLOR.test(color) ? { color } : {}),
});
}
return DEFAULT_ACTIVITY_PRIORITY_SETTINGS.map((d) => {
const o = overrides.get(d.key);
return {
key: d.key,
label: o?.label || d.label,
color: o?.color || d.color,
};
});
}
export type UpdateActivityPrioritiesRequest = {
items: Array<{ key: ActivityPriority; label: string; color: string }>;
};
export type ActivityFilter = "today" | "overdue" | "upcoming" | "done" | "all"; export type ActivityFilter = "today" | "overdue" | "upcoming" | "done" | "all";
export type ActivityStageColor = "green" | "orange" | "purple" | "blue" | "rose" | "slate"; export type ActivityStageColor = "green" | "orange" | "purple" | "blue" | "rose" | "slate";
@@ -2124,6 +2234,14 @@ export interface ActivityImageDto {
export type ActivityCompletionMode = "any" | "all"; export type ActivityCompletionMode = "any" | "all";
/** چه کسانی می‌توانند فعالیت را ویرایش یا حذف کنند (علاوه بر owner/admin) */
export type ActivityEditPolicy = "creator" | "assignees";
export const ACTIVITY_EDIT_POLICY_LABELS: Record<ActivityEditPolicy, string> = {
creator: "فقط ایجادکننده",
assignees: "همهٔ مسئولان",
};
export interface ActivityDto { export interface ActivityDto {
id: string; id: string;
type: ActivityType; type: ActivityType;
@@ -2145,6 +2263,8 @@ export interface ActivityDto {
completionMode?: ActivityCompletionMode; completionMode?: ActivityCompletionMode;
/** شناسهٔ مسئولانی که سهم خود را در حالت all ثبت کرده‌اند */ /** شناسهٔ مسئولانی که سهم خود را در حالت all ثبت کرده‌اند */
completedByIds?: string[]; completedByIds?: string[];
/** پیش‌فرض creator؛ assignees یعنی همهٔ مسئولان هم می‌توانند ویرایش/حذف کنند */
editPolicy?: ActivityEditPolicy;
/** manual یا didar؛ برای جدا کردن سابقهٔ قبلی */ /** manual یا didar؛ برای جدا کردن سابقهٔ قبلی */
importSource?: string; importSource?: string;
promotedFromPriorAt?: string | null; promotedFromPriorAt?: string | null;
@@ -2204,6 +2324,8 @@ export interface CreateActivityRequest {
assigneeIds?: string[]; assigneeIds?: string[];
/** پیش‌فرض any. فقط وقتی چند مسئول دارد معنی دارد */ /** پیش‌فرض any. فقط وقتی چند مسئول دارد معنی دارد */
completionMode?: ActivityCompletionMode; completionMode?: ActivityCompletionMode;
/** پیش‌فرض creator */
editPolicy?: ActivityEditPolicy;
} }
export interface UpdateActivityRequest { export interface UpdateActivityRequest {
@@ -2229,6 +2351,7 @@ export interface UpdateActivityRequest {
assigneeId?: string | null; assigneeId?: string | null;
assigneeIds?: string[]; assigneeIds?: string[];
completionMode?: ActivityCompletionMode; completionMode?: ActivityCompletionMode;
editPolicy?: ActivityEditPolicy;
} }
export interface ActivitySummaryDto { export interface ActivitySummaryDto {
@@ -4772,8 +4895,11 @@ export const MESSAGE_AUTOMATION_FIELDS = [
{ token: "{نام}", label: "نام مشتری" }, { token: "{نام}", label: "نام مشتری" },
{ token: "{شماره}", label: "شماره موبایل" }, { token: "{شماره}", label: "شماره موبایل" },
{ token: "{تاریخ}", label: "تاریخ ارسال" }, { token: "{تاریخ}", label: "تاریخ ارسال" },
{ token: "{عنوان}", label: "عنوان رکورد" }, { token: "{عنوان}", label: "عنوان / سمت" },
{ token: "{شرکت}", label: "نام شرکت" }, { token: "{شرکت}", label: "شرکت مشتری" },
{ token: "{از طرف}", label: "نام سازمان فرستنده" },
{ token: "{مانده ریالی}", label: "مانده مالی (ریالی)" },
{ token: "{مانده فلزی}", label: "مانده وزنی فلزات" },
] as const; ] as const;
/** First-part Persian SMS limit (legacy UI estimate). Prefer countSmsParts(). */ /** First-part Persian SMS limit (legacy UI estimate). Prefer countSmsParts(). */
@@ -5295,6 +5421,39 @@ export interface OutboundSmsHistoryResponse {
items: OutboundSmsLogDto[]; items: OutboundSmsLogDto[];
} }
/* ——— قالب‌های آمادهٔ پیامک دستی (سازمانی) ——— */
export type SmsTemplateDto = {
id: string;
name: string;
body: string;
};
export const SMS_TEMPLATE_MAX = 40;
export const SMS_TEMPLATE_NAME_MAX = 80;
export const SMS_TEMPLATE_BODY_MAX = 500;
/** نرمال‌سازی لیست ذخیره‌شده؛ آیتم‌های ناقص حذف می‌شوند */
export function parseSmsTemplates(raw: unknown): SmsTemplateDto[] {
if (!Array.isArray(raw)) return [];
const out: SmsTemplateDto[] = [];
for (const row of raw) {
if (!row || typeof row !== "object") continue;
const rec = row as Record<string, unknown>;
const id = typeof rec.id === "string" ? rec.id.trim() : "";
const name = typeof rec.name === "string" ? rec.name.trim() : "";
const body = typeof rec.body === "string" ? rec.body.trim() : "";
if (!id || !name || body.length < 2) continue;
out.push({
id,
name: name.slice(0, SMS_TEMPLATE_NAME_MAX),
body: body.slice(0, SMS_TEMPLATE_BODY_MAX),
});
if (out.length >= SMS_TEMPLATE_MAX) break;
}
return out;
}
/* ——— پیامک گروهی ——— */ /* ——— پیامک گروهی ——— */
export type SmsCampaignStatus = export type SmsCampaignStatus =
@@ -6401,6 +6560,7 @@ export interface RoutineDto {
isActive: boolean; isActive: boolean;
/** سازندهٔ روتین؛ عضو عادی فقط روتین خودش را ویرایش می‌کند */ /** سازندهٔ روتین؛ عضو عادی فقط روتین خودش را ویرایش می‌کند */
createdById: string | null; createdById: string | null;
createdBy: UserSummaryDto | null;
recurrenceLabel: string; recurrenceLabel: string;
/** درصد اجرا در ۳۰ روز اخیر */ /** درصد اجرا در ۳۰ روز اخیر */
executionRate: number | null; executionRate: number | null;
@@ -6652,7 +6812,7 @@ export interface FinancialDocumentDto {
reference: string | null; reference: string | null;
notes: string | null; notes: string | null;
createdAt: string; createdAt: string;
attachments?: Array<{ id: string; fileName: string }>; attachments?: Array<{ id: string; fileName: string; mimeType?: string }>;
} }
export interface FinancialMovementDto { export interface FinancialMovementDto {