Compare commits

...
10 Commits
Author SHA1 Message Date
s.esmaeili 1ae87c97b7 feat(ui): standardize design system, modals, sidebar, and form inputs
- Implement unified design system tokens, 10px radius, and IRANSans typography
- Modernize sidebar with Gemini-style collapsed expander, square 1:1 items, and elevated profile flyout
- Standardize all modal dialogs with 16px padding, fixed header/footer, 16px medium title, and sticky bottom actions
- Refactor DealFormView and CustomFieldsSection with standard UiField, UiInput, and UiSelect components
- Add draggable bottom-left QuickCreate floating action button
2026-09-12 01:33:07 +03:30
MahdiandCursor 9a991fc1f1 Add salesperson commissions on issued invoices and a cheque register.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-11 01:09:59 +03:30
MahdiandCursor 535c428270 Align controls to 36/10 and make create modals full-screen on mobile.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 23:45:11 +03:30
MahdiandCursor 212d02f664 Add a small internal warehouse and party balances when Tahesab is off.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 22:24:16 +03:30
MahdiandCursor 55432ff979 Let ECharts infer dashboard tooltip types so vue-tsc accepts the build.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 02:42:55 +03:30
MahdiandCursor 601bc163b3 Fix dashboard chart types so the production web build can pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 01:29:14 +03:30
MahdiandCursor b8ad4037b6 Unify the web UI on shared controls and let pipeline columns be managed on the board.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-10 01:22:24 +03:30
MahdiandCursor f1aba1b386 Let automations fire on more CRM events and open the studio from the main nav.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 21:43:17 +03:30
MahdiandCursor 51684daa61 Let the sidebar collapse to an icon rail with a logo-and-profile cap.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 17:51:40 +03:30
MahdiandCursor 3ec87ff912 Give automations a visual chain with conditions and SMS, and match the pipeline board to the sales mockup.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-09 13:12:13 +03:30
137 changed files with 15366 additions and 6025 deletions
@@ -0,0 +1,19 @@
CREATE TYPE "AutomationTrigger_new" AS ENUM (
'person_created',
'lead_submitted',
'deal_created',
'deal_stage_changed',
'deal_won',
'deal_lost',
'ticket_created',
'ticket_resolved',
'invoice_paid'
);
ALTER TABLE "AutomationRule"
ALTER COLUMN "trigger" TYPE "AutomationTrigger_new"
USING ("trigger"::text::"AutomationTrigger_new");
ALTER TYPE "AutomationTrigger" RENAME TO "AutomationTrigger_old";
ALTER TYPE "AutomationTrigger_new" RENAME TO "AutomationTrigger";
DROP TYPE "AutomationTrigger_old";
@@ -0,0 +1,21 @@
CREATE TYPE "AutomationTrigger_new" AS ENUM (
'person_created',
'lead_submitted',
'deal_created',
'deal_stage_changed',
'deal_won',
'deal_lost',
'ticket_created',
'ticket_resolved',
'invoice_issued',
'invoice_paid',
'activity_done'
);
ALTER TABLE "AutomationRule"
ALTER COLUMN "trigger" TYPE "AutomationTrigger_new"
USING ("trigger"::text::"AutomationTrigger_new");
ALTER TYPE "AutomationTrigger" RENAME TO "AutomationTrigger_old";
ALTER TYPE "AutomationTrigger_new" RENAME TO "AutomationTrigger";
DROP TYPE "AutomationTrigger_old";
@@ -0,0 +1,80 @@
-- CreateTable
CREATE TABLE "Warehouse" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"isDefault" BOOLEAN NOT NULL DEFAULT true,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Warehouse_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "StockMovement" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"warehouseId" TEXT NOT NULL,
"productId" TEXT NOT NULL,
"type" TEXT NOT NULL,
"quantity" DECIMAL(18,2) NOT NULL,
"note" TEXT,
"invoiceId" TEXT,
"occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "StockMovement_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "PartyOpeningBalance" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"personId" TEXT NOT NULL,
"amount" DECIMAL(18,2) NOT NULL,
"currency" TEXT NOT NULL DEFAULT 'IRR',
"note" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "PartyOpeningBalance_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "Warehouse_organizationId_isDefault_idx" ON "Warehouse"("organizationId", "isDefault");
-- CreateIndex
CREATE INDEX "StockMovement_organizationId_productId_occurredAt_idx" ON "StockMovement"("organizationId", "productId", "occurredAt");
-- CreateIndex
CREATE INDEX "StockMovement_invoiceId_idx" ON "StockMovement"("invoiceId");
-- CreateIndex
CREATE INDEX "StockMovement_warehouseId_idx" ON "StockMovement"("warehouseId");
-- CreateIndex
CREATE UNIQUE INDEX "PartyOpeningBalance_organizationId_personId_key" ON "PartyOpeningBalance"("organizationId", "personId");
-- CreateIndex
CREATE INDEX "PartyOpeningBalance_personId_idx" ON "PartyOpeningBalance"("personId");
-- AddForeignKey
ALTER TABLE "Warehouse" ADD CONSTRAINT "Warehouse_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StockMovement" ADD CONSTRAINT "StockMovement_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StockMovement" ADD CONSTRAINT "StockMovement_warehouseId_fkey" FOREIGN KEY ("warehouseId") REFERENCES "Warehouse"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StockMovement" ADD CONSTRAINT "StockMovement_productId_fkey" FOREIGN KEY ("productId") REFERENCES "Product"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "StockMovement" ADD CONSTRAINT "StockMovement_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "Invoice"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "PartyOpeningBalance" ADD CONSTRAINT "PartyOpeningBalance_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "PartyOpeningBalance" ADD CONSTRAINT "PartyOpeningBalance_personId_fkey" FOREIGN KEY ("personId") REFERENCES "Person"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,75 @@
-- AlterTable
ALTER TABLE "User" ADD COLUMN "commissionPercent" DECIMAL(8,2) NOT NULL DEFAULT 0;
-- AlterTable
ALTER TABLE "Invoice" ADD COLUMN "commissionPercent" DECIMAL(8,2),
ADD COLUMN "commissionFixedAmount" DECIMAL(18,2);
-- CreateTable
CREATE TABLE "CommissionEntry" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"invoiceId" TEXT NOT NULL,
"percent" DECIMAL(8,2) NOT NULL,
"amount" DECIMAL(18,2) NOT NULL,
"currency" TEXT NOT NULL DEFAULT 'IRR',
"status" TEXT NOT NULL DEFAULT 'posted',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "CommissionEntry_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Cheque" (
"id" TEXT NOT NULL,
"organizationId" TEXT NOT NULL,
"paymentId" TEXT NOT NULL,
"invoiceId" TEXT NOT NULL,
"number" TEXT NOT NULL,
"bank" TEXT NOT NULL,
"dueDate" TIMESTAMP(3) NOT NULL,
"status" TEXT NOT NULL DEFAULT 'pending',
"notes" TEXT,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "Cheque_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "CommissionEntry_invoiceId_key" ON "CommissionEntry"("invoiceId");
-- CreateIndex
CREATE INDEX "CommissionEntry_organizationId_userId_createdAt_idx" ON "CommissionEntry"("organizationId", "userId", "createdAt");
-- CreateIndex
CREATE INDEX "CommissionEntry_status_idx" ON "CommissionEntry"("status");
-- CreateIndex
CREATE UNIQUE INDEX "Cheque_paymentId_key" ON "Cheque"("paymentId");
-- CreateIndex
CREATE INDEX "Cheque_organizationId_status_dueDate_idx" ON "Cheque"("organizationId", "status", "dueDate");
-- CreateIndex
CREATE INDEX "Cheque_invoiceId_idx" ON "Cheque"("invoiceId");
-- AddForeignKey
ALTER TABLE "CommissionEntry" ADD CONSTRAINT "CommissionEntry_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CommissionEntry" ADD CONSTRAINT "CommissionEntry_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "CommissionEntry" ADD CONSTRAINT "CommissionEntry_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "Invoice"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Cheque" ADD CONSTRAINT "Cheque_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Cheque" ADD CONSTRAINT "Cheque_paymentId_fkey" FOREIGN KEY ("paymentId") REFERENCES "Payment"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Cheque" ADD CONSTRAINT "Cheque_invoiceId_fkey" FOREIGN KEY ("invoiceId") REFERENCES "Invoice"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+121
View File
@@ -108,8 +108,17 @@ enum TicketPriority {
}
enum AutomationTrigger {
person_created
lead_submitted
deal_created
deal_stage_changed
deal_won
deal_lost
ticket_created
ticket_resolved
invoice_issued
invoice_paid
activity_done
}
enum AutomationAction {
@@ -171,6 +180,11 @@ model Organization {
noteAiSuggestions NoteAiSuggestion[]
accountingConnections AccountingConnection[]
accountingSyncJobs AccountingSyncJob[]
warehouses Warehouse[]
stockMovements StockMovement[]
partyOpenings PartyOpeningBalance[]
commissionEntries CommissionEntry[]
cheques Cheque[]
}
model User {
@@ -197,6 +211,8 @@ model User {
noteAttachments NoteAttachment[] @relation("NoteAttachmentUploader")
notifications Notification[]
salesGoals SalesGoal[] @relation("SalesGoalUser")
commissionPercent Decimal @default(0) @db.Decimal(8, 2)
commissionEntries CommissionEntry[]
assignedTickets Ticket[] @relation("TicketAssignee")
reportedTickets Ticket[] @relation("TicketReporter")
ticketMessages TicketMessage[] @relation("TicketMessageAuthor")
@@ -274,6 +290,7 @@ model Person {
memoryItems MemoryItem[]
accountingLinks PersonAccountingLink[]
accountingDocuments AccountingDocumentLog[]
openingBalances PartyOpeningBalance[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -536,6 +553,7 @@ model Product {
lineItems DealLineItem[]
quoteLineItems QuoteLineItem[]
invoiceLineItems InvoiceLineItem[]
stockMovements StockMovement[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -716,6 +734,11 @@ model Invoice {
lineItems InvoiceLineItem[]
payments Payment[]
installments InvoiceInstallment[]
stockMovements StockMovement[]
commissionPercent Decimal? @db.Decimal(8, 2)
commissionFixedAmount Decimal? @db.Decimal(18, 2)
commissionEntry CommissionEntry?
cheques Cheque[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -757,6 +780,7 @@ model Payment {
notes String?
installmentId String? @unique
installment InvoiceInstallment? @relation(fields: [installmentId], references: [id], onDelete: SetNull)
cheque Cheque?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -1201,3 +1225,100 @@ model AccountingSyncJob {
@@index([organizationId, createdAt])
}
/// انبار داخلی — وقتی ته‌حساب وصل نیست
model Warehouse {
id String @id @default(cuid())
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
name String
isDefault Boolean @default(true)
movements StockMovement[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([organizationId, isDefault])
}
/// گردش کالا؛ مقدار مثبت ورود، منفی خروج
model StockMovement {
id String @id @default(cuid())
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
warehouseId String
warehouse Warehouse @relation(fields: [warehouseId], references: [id], onDelete: Cascade)
productId String
product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
/// opening | purchase | sale | credit | adjustment
type String
quantity Decimal @db.Decimal(18, 2)
note String?
invoiceId String?
invoice Invoice? @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
occurredAt DateTime @default(now())
createdAt DateTime @default(now())
@@index([organizationId, productId, occurredAt])
@@index([invoiceId])
@@index([warehouseId])
}
/// پورسانت کارشناس بعد از صدور فاکتور
model CommissionEntry {
id String @id @default(cuid())
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
invoiceId String @unique
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
percent Decimal @db.Decimal(8, 2)
amount Decimal @db.Decimal(18, 2)
currency String @default("IRR")
/// posted | void
status String @default("posted")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([organizationId, userId, createdAt])
@@index([status])
}
/// چک دریافتی وصل به پرداخت فاکتور
model Cheque {
id String @id @default(cuid())
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
paymentId String @unique
payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)
invoiceId String
invoice Invoice @relation(fields: [invoiceId], references: [id], onDelete: Cascade)
number String
bank String
dueDate DateTime
/// pending | cleared | bounced
status String @default("pending")
notes String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([organizationId, status, dueDate])
@@index([invoiceId])
}
/// مانده اول دوره طرف‌حساب (مثبت = بدهکار ما)
model PartyOpeningBalance {
id String @id @default(cuid())
organizationId String
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
personId String
person Person @relation(fields: [personId], references: [id], onDelete: Cascade)
amount Decimal @db.Decimal(18, 2)
currency String @default("IRR")
note String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@unique([organizationId, personId])
@@index([personId])
}
+2 -1
View File
@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { ActivitiesController } from './activities.controller';
import { ActivitiesService } from './activities.service';
import { NotificationsModule } from '../notifications/notifications.module';
import { AutomationsModule } from '../automations/automations.module';
@Module({
imports: [NotificationsModule],
imports: [NotificationsModule, AutomationsModule],
controllers: [ActivitiesController],
providers: [ActivitiesService],
exports: [ActivitiesService],
@@ -14,6 +14,7 @@ import type {
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { NotificationsService } from '../notifications/notifications.service';
import { AutomationsService } from '../automations/automations.service';
import { type Actor, assigneeWhere, ownerWhere } from '../common/record-scope';
type ActivityActor = Pick<Actor, 'userId' | 'role'>;
@@ -53,6 +54,7 @@ export class ActivitiesService {
constructor(
private readonly prisma: PrismaService,
private readonly notifications: NotificationsService,
private readonly automations: AutomationsService,
) {}
async summary(
@@ -245,11 +247,18 @@ export class ActivitiesService {
dto.status === 'done' ? new Date() : dto.status === 'open' ? null : undefined;
}
const existing = await this.prisma.activity.findFirst({
where: { id, organizationId },
select: { status: true },
});
const row = await this.prisma.activity.update({
where: { id },
data,
include,
});
if (dto.status === 'done' && existing?.status !== 'done') {
await this.fireDone(organizationId, row);
}
return this.toDto(row);
}
@@ -259,11 +268,18 @@ export class ActivitiesService {
actor: ActivityActor,
): Promise<ActivityDto> {
await this.ensureExists(organizationId, id, actor);
const existing = await this.prisma.activity.findFirst({
where: { id, organizationId },
select: { status: true },
});
const row = await this.prisma.activity.update({
where: { id },
data: { status: 'done', completedAt: new Date() },
include,
});
if (existing?.status !== 'done') {
await this.fireDone(organizationId, row);
}
return this.toDto(row);
}
@@ -350,6 +366,30 @@ export class ActivitiesService {
}
}
private async fireDone(
organizationId: string,
row: {
id: string;
title: string;
person: { id: string } | null;
company: { id: string } | null;
deal: { id: string } | null;
assignee: { id: string } | null;
},
) {
await this.automations.runTrigger('activity_done', {
organizationId,
entityType: 'activity',
entityId: row.id,
title: row.title,
personId: row.person?.id ?? null,
companyId: row.company?.id ?? null,
dealId: row.deal?.id ?? null,
assigneeId: row.assignee?.id ?? null,
ownerId: row.assignee?.id ?? null,
});
}
private async ensureExists(
organizationId: string,
id: string,
+4
View File
@@ -27,6 +27,8 @@ import { AutomationsModule } from './automations/automations.module';
import { AiModule } from './ai/ai.module';
import { MemoryModule } from './memory/memory.module';
import { TahesabModule } from './integrations/tahesab/tahesab.module';
import { InventoryModule } from './inventory/inventory.module';
import { FinanceModule } from './finance/finance.module';
@Module({
imports: [
@@ -51,6 +53,8 @@ import { TahesabModule } from './integrations/tahesab/tahesab.module';
LeadFormsModule,
QuotesModule,
InvoicesModule,
InventoryModule,
FinanceModule,
SalesModule,
TicketsModule,
FaqModule,
@@ -2,13 +2,14 @@ import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { LoyaltyModule } from '../loyalty/loyalty.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { SmsService } from '../common/sms.service';
import { AutomationsController } from './automations.controller';
import { AutomationsService } from './automations.service';
@Module({
imports: [AuthModule, NotificationsModule, LoyaltyModule],
controllers: [AutomationsController],
providers: [AutomationsService],
providers: [AutomationsService, SmsService],
exports: [AutomationsService],
})
export class AutomationsModule {}
+276 -31
View File
@@ -1,20 +1,38 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import type {
AutomationAction,
AutomationConditionField,
AutomationConditionOp,
AutomationNotifyChannel,
AutomationRuleConfig,
AutomationRuleDto,
AutomationStep,
AutomationTrigger,
CreateAutomationRuleRequest,
UpdateAutomationRuleRequest,
} from '@mento/shared';
import {
MAX_AUTOMATION_STEPS,
automationStepToConfig,
firstAutomationAction,
isAutomationCondition,
normalizeAutomationSteps,
packAutomationConfig,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { NotificationsService } from '../notifications/notifications.service';
import { LoyaltyService } from '../loyalty/loyalty.service';
import { SmsService } from '../common/sms.service';
export type AutomationContext = {
organizationId: string;
entityType: 'deal' | 'ticket';
entityType: 'deal' | 'ticket' | 'person' | 'invoice' | 'activity';
entityId: string;
title: string;
personId?: string | null;
@@ -24,12 +42,22 @@ export type AutomationContext = {
assigneeId?: string | null;
};
type AutomationFacts = {
amount: number | null;
hasPerson: boolean;
hasCompany: boolean;
ticketPriority: string | null;
};
@Injectable()
export class AutomationsService {
private readonly logger = new Logger(AutomationsService.name);
constructor(
private readonly prisma: PrismaService,
private readonly notifications: NotificationsService,
private readonly loyalty: LoyaltyService,
private readonly sms: SmsService,
) {}
async list(organizationId: string): Promise<AutomationRuleDto[]> {
@@ -44,14 +72,17 @@ export class AutomationsService {
organizationId: string,
dto: CreateAutomationRuleRequest,
): Promise<AutomationRuleDto> {
const steps = resolveSteps(dto.action, dto.config);
const action = firstAutomationAction(steps);
if (!action) throw new BadRequestException('حداقل یک عمل لازم است');
const row = await this.prisma.automationRule.create({
data: {
organizationId,
name: dto.name.trim(),
trigger: dto.trigger,
action: dto.action,
action,
isActive: dto.isActive ?? true,
config: (dto.config ?? {}) as Prisma.InputJsonValue,
config: packAutomationConfig(steps) as Prisma.InputJsonValue,
},
});
return this.toDto(row);
@@ -67,15 +98,30 @@ export class AutomationsService {
});
if (!existing) throw new NotFoundException('قانون پیدا نشد');
const shouldRewriteChain =
dto.action !== undefined || dto.config !== undefined;
const steps = shouldRewriteChain
? resolveSteps(
(dto.action ?? existing.action) as AutomationAction,
dto.config ?? asConfig(existing.config),
)
: null;
const nextAction = steps ? firstAutomationAction(steps) : null;
if (steps && !nextAction) {
throw new BadRequestException('حداقل یک عمل لازم است');
}
const row = await this.prisma.automationRule.update({
where: { id },
data: {
...(dto.name !== undefined ? { name: dto.name.trim() } : {}),
...(dto.trigger !== undefined ? { trigger: dto.trigger } : {}),
...(dto.action !== undefined ? { action: dto.action } : {}),
...(dto.isActive !== undefined ? { isActive: dto.isActive } : {}),
...(dto.config !== undefined
? { config: dto.config as Prisma.InputJsonValue }
...(steps && nextAction
? {
action: nextAction,
config: packAutomationConfig(steps) as Prisma.InputJsonValue,
}
: {}),
},
});
@@ -101,15 +147,103 @@ export class AutomationsService {
trigger,
},
});
const facts = await this.loadFacts(ctx);
for (const rule of rules) {
try {
await this.execute(rule.action as AutomationAction, asConfig(rule.config), ctx);
const config = asConfig(rule.config);
const steps = normalizeAutomationSteps(
rule.action as AutomationAction,
config,
);
for (const step of steps) {
if (isAutomationCondition(step)) {
if (!matchCondition(step, facts)) break;
continue;
}
if (!step.action) continue;
await this.execute(step.action, automationStepToConfig(step), ctx);
}
} catch {
// قوانین نباید شکست عملیات اصلی را ایجاد کنند
}
}
}
private async loadFacts(ctx: AutomationContext): Promise<AutomationFacts> {
if (ctx.entityType === 'deal') {
const deal = await this.prisma.deal.findFirst({
where: { id: ctx.entityId, organizationId: ctx.organizationId },
select: { amount: true, personId: true, companyId: true },
});
return {
amount: deal?.amount != null ? Number(deal.amount) : null,
hasPerson: Boolean(deal?.personId ?? ctx.personId),
hasCompany: Boolean(deal?.companyId ?? ctx.companyId),
ticketPriority: null,
};
}
if (ctx.entityType === 'ticket') {
const ticket = await this.prisma.ticket.findFirst({
where: { id: ctx.entityId, organizationId: ctx.organizationId },
select: { priority: true, personId: true, companyId: true },
});
return {
amount: null,
hasPerson: Boolean(ticket?.personId ?? ctx.personId),
hasCompany: Boolean(ticket?.companyId ?? ctx.companyId),
ticketPriority: ticket?.priority ?? null,
};
}
if (ctx.entityType === 'invoice') {
const invoice = await this.prisma.invoice.findFirst({
where: { id: ctx.entityId, organizationId: ctx.organizationId },
select: {
personId: true,
companyId: true,
discountAmount: true,
taxPercent: true,
lineItems: { select: { quantity: true, unitPrice: true } },
},
});
let amount: number | null = null;
if (invoice) {
const subtotal = invoice.lineItems.reduce(
(sum, item) => sum + Number(item.quantity) * Number(item.unitPrice),
0,
);
const discount = Number(invoice.discountAmount ?? 0);
const taxPercent = Number(invoice.taxPercent ?? 0);
amount = Math.abs(
subtotal - discount + Math.max(0, subtotal - discount) * (taxPercent / 100),
);
}
return {
amount,
hasPerson: Boolean(invoice?.personId ?? ctx.personId),
hasCompany: Boolean(invoice?.companyId ?? ctx.companyId),
ticketPriority: null,
};
}
if (ctx.entityType === 'activity') {
const activity = await this.prisma.activity.findFirst({
where: { id: ctx.entityId, organizationId: ctx.organizationId },
select: { personId: true, companyId: true, dealId: true },
});
return {
amount: null,
hasPerson: Boolean(activity?.personId ?? ctx.personId),
hasCompany: Boolean(activity?.companyId ?? ctx.companyId),
ticketPriority: null,
};
}
return {
amount: null,
hasPerson: Boolean(ctx.personId),
hasCompany: Boolean(ctx.companyId),
ticketPriority: null,
};
}
private async execute(
action: AutomationAction,
config: AutomationRuleConfig,
@@ -143,10 +277,7 @@ export class AutomationsService {
type: 'automation',
title: 'فعالیت خودکار',
body: title,
link:
ctx.entityType === 'deal'
? `/deals/${ctx.entityId}`
: `/tickets/${ctx.entityId}`,
link: entityLink(ctx),
entityType: ctx.entityType,
entityId: ctx.entityId,
});
@@ -155,25 +286,7 @@ export class AutomationsService {
}
if (action === 'create_notification') {
const userId =
config.notifyUserId?.trim() ||
ctx.assigneeId ||
ctx.ownerId ||
null;
if (!userId) return;
await this.notifications.create({
organizationId: ctx.organizationId,
userId,
type: 'automation',
title,
body: config.body?.trim() || ctx.title,
link:
ctx.entityType === 'deal'
? `/deals/${ctx.entityId}`
: `/tickets/${ctx.entityId}`,
entityType: ctx.entityType,
entityId: ctx.entityId,
});
await this.executeNotify(title, config, ctx);
return;
}
@@ -188,6 +301,80 @@ export class AutomationsService {
}
}
private async executeNotify(
title: string,
config: AutomationRuleConfig,
ctx: AutomationContext,
) {
const channel: AutomationNotifyChannel = config.notifyChannel ?? 'app';
const wantApp = channel === 'app' || channel === 'both';
const wantSms = channel === 'sms' || channel === 'both';
const smsText = (config.body?.trim() || title).slice(0, 160);
const link = entityLink(ctx);
if (config.notifyTarget === 'person') {
if (wantSms) {
const person = ctx.personId
? await this.prisma.person.findFirst({
where: {
id: ctx.personId,
organizationId: ctx.organizationId,
},
select: { mobile: true, phone: true },
})
: null;
await this.sendAutomationSms(person?.mobile || person?.phone, smsText);
}
return;
}
const userId =
config.notifyUserId?.trim() ||
ctx.assigneeId ||
ctx.ownerId ||
null;
if (!userId) return;
if (wantApp) {
await this.notifications.create({
organizationId: ctx.organizationId,
userId,
type: 'automation',
title,
body: config.body?.trim() || ctx.title,
link,
entityType: ctx.entityType,
entityId: ctx.entityId,
});
}
if (wantSms) {
const user = await this.prisma.user.findFirst({
where: { id: userId, organizationId: ctx.organizationId },
select: { mobile: true },
});
await this.sendAutomationSms(user?.mobile, smsText);
}
}
private async sendAutomationSms(
mobile: string | null | undefined,
text: string,
) {
if (!mobile) {
this.logger.warn('Automation SMS skipped: no mobile');
return;
}
if (!this.sms.isConfigured()) {
this.logger.warn('Automation SMS skipped: SMS not configured');
return;
}
const result = await this.sms.sendSmsDetailed(mobile, text);
if (!result.ok) {
this.logger.warn(`Automation SMS failed: ${result.reason ?? 'unknown'}`);
}
}
private toDto(row: {
id: string;
name: string;
@@ -216,8 +403,66 @@ function asConfig(raw: unknown): AutomationRuleConfig {
return raw as AutomationRuleConfig;
}
function resolveSteps(
action: AutomationAction,
config?: AutomationRuleConfig,
): AutomationStep[] {
const steps = normalizeAutomationSteps(action, config);
if (!firstAutomationAction(steps)) {
throw new BadRequestException('حداقل یک عمل لازم است');
}
if (steps.length > MAX_AUTOMATION_STEPS) {
throw new BadRequestException(
`حداکثر ${MAX_AUTOMATION_STEPS} عمل در یک قانون مجاز است`,
);
}
return steps;
}
function matchCondition(step: AutomationStep, facts: AutomationFacts): boolean {
const field: AutomationConditionField = step.conditionField ?? 'has_person';
const op: AutomationConditionOp = step.conditionOp ?? 'is_set';
if (field === 'deal_amount') {
const amount = facts.amount;
const value = Number(step.conditionValue);
if (amount == null || !Number.isFinite(value)) return false;
if (op === 'gte') return amount >= value;
if (op === 'lte') return amount <= value;
if (op === 'eq') return amount === value;
if (op === 'neq') return amount !== value;
return false;
}
if (field === 'has_person') {
return op === 'is_empty' ? !facts.hasPerson : facts.hasPerson;
}
if (field === 'has_company') {
return op === 'is_empty' ? !facts.hasCompany : facts.hasCompany;
}
if (field === 'ticket_priority') {
const current = facts.ticketPriority;
const value = String(step.conditionValue ?? '');
if (op === 'neq') return current !== value;
return current === value;
}
return false;
}
function defaultTitle(action: AutomationAction, entityTitle: string) {
if (action === 'create_activity') return `پیگیری خودکار: ${entityTitle}`;
if (action === 'create_notification') return `اتوماسیون: ${entityTitle}`;
return entityTitle;
}
function entityLink(ctx: AutomationContext) {
if (ctx.entityType === 'deal') return `/deals/${ctx.entityId}`;
if (ctx.entityType === 'ticket') return `/tickets/${ctx.entityId}`;
if (ctx.entityType === 'invoice') return `/invoices/${ctx.entityId}`;
if (ctx.entityType === 'person') return `/contacts/people/${ctx.entityId}`;
if (ctx.entityType === 'activity') return `/activities/${ctx.entityId}`;
return '/';
}
+13 -1
View File
@@ -12,7 +12,19 @@ import {
ValidateIf,
} from 'class-validator';
const TRIGGERS = ['deal_won', 'ticket_resolved'] as const;
const TRIGGERS = [
'person_created',
'lead_submitted',
'deal_created',
'deal_stage_changed',
'deal_won',
'deal_lost',
'ticket_created',
'ticket_resolved',
'invoice_issued',
'invoice_paid',
'activity_done',
] as const;
const ACTIONS = [
'create_activity',
'create_notification',
+2 -1
View File
@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common';
import { LoyaltyModule } from '../loyalty/loyalty.module';
import { AutomationsModule } from '../automations/automations.module';
import { CompaniesController } from './companies.controller';
import { CompaniesService } from './companies.service';
import { PeopleController } from './people.controller';
@@ -7,7 +8,7 @@ import { PeopleService } from './people.service';
import { ContactsExcelService } from './contacts-excel.service';
@Module({
imports: [LoyaltyModule],
imports: [LoyaltyModule, AutomationsModule],
controllers: [PeopleController, CompaniesController],
providers: [PeopleService, CompaniesService, ContactsExcelService],
exports: [PeopleService, CompaniesService],
+11
View File
@@ -25,6 +25,7 @@ import {
resolveOwnerId,
} from '../common/record-scope';
import { LoyaltyService } from '../loyalty/loyalty.service';
import { AutomationsService } from '../automations/automations.service';
const personInclude = {
company: { select: { id: true, name: true } },
@@ -64,6 +65,7 @@ export class PeopleService {
private readonly prisma: PrismaService,
private readonly companies: CompaniesService,
private readonly loyalty: LoyaltyService,
private readonly automations: AutomationsService,
) {}
async list(
@@ -149,6 +151,15 @@ export class PeopleService {
include: personInclude,
});
await this.loyalty.applyWelcomePoints(actor.organizationId, row.id);
await this.automations.runTrigger('person_created', {
organizationId: actor.organizationId,
entityType: 'person',
entityId: row.id,
title: `${row.firstName} ${row.lastName}`.trim(),
personId: row.id,
companyId: row.companyId,
ownerId: row.ownerId,
});
const fresh = await this.prisma.person.findFirst({
where: { id: row.id },
include: personInclude,
+120
View File
@@ -0,0 +1,120 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import type { ChequeDto, UpdateChequeRequest } from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { type Actor, ownerWhere } from '../common/record-scope';
const CHEQUE_STATUSES = ['pending', 'cleared', 'bounced'] as const;
@Injectable()
export class ChequesService {
constructor(private readonly prisma: PrismaService) {}
async list(
organizationId: string,
actor: Pick<Actor, 'userId' | 'role'>,
opts?: { status?: string; q?: string },
): Promise<ChequeDto[]> {
const rows = await this.prisma.cheque.findMany({
where: {
organizationId,
invoice: ownerWhere(actor),
...(opts?.status ? { status: opts.status } : {}),
...(opts?.q?.trim()
? {
OR: [
{ number: { contains: opts.q.trim(), mode: 'insensitive' } },
{ bank: { contains: opts.q.trim(), mode: 'insensitive' } },
{
invoice: {
number: { contains: opts.q.trim(), mode: 'insensitive' },
},
},
],
}
: {}),
},
include: this.include,
orderBy: [{ dueDate: 'asc' }, { createdAt: 'desc' }],
take: 300,
});
return rows.map((row) => this.toDto(row));
}
async update(
organizationId: string,
id: string,
actor: Pick<Actor, 'userId' | 'role'>,
dto: UpdateChequeRequest,
): Promise<ChequeDto> {
const existing = await this.prisma.cheque.findFirst({
where: { id, organizationId, invoice: ownerWhere(actor) },
select: { id: true },
});
if (!existing) throw new NotFoundException('چک پیدا نشد');
const data: Prisma.ChequeUncheckedUpdateInput = {};
if (dto.number !== undefined) data.number = dto.number.trim();
if (dto.bank !== undefined) data.bank = dto.bank.trim();
if (dto.dueDate !== undefined) data.dueDate = new Date(dto.dueDate);
if (dto.status !== undefined) {
if (!CHEQUE_STATUSES.includes(dto.status as (typeof CHEQUE_STATUSES)[number])) {
throw new BadRequestException('وضعیت چک معتبر نیست');
}
data.status = dto.status;
}
if ('notes' in dto) {
data.notes = dto.notes?.trim() ? dto.notes.trim() : null;
}
const row = await this.prisma.cheque.update({
where: { id },
data,
include: this.include,
});
return this.toDto(row);
}
private include = {
payment: { select: { id: true, amount: true, currency: true, paidAt: true } },
invoice: {
select: {
id: true,
number: true,
title: true,
person: { select: { firstName: true, lastName: true } },
company: { select: { name: true } },
},
},
} satisfies Prisma.ChequeInclude;
private toDto(
row: Prisma.ChequeGetPayload<{ include: ChequesService['include'] }>,
): ChequeDto {
const personName = row.invoice.person
? `${row.invoice.person.firstName} ${row.invoice.person.lastName}`.trim()
: row.invoice.company?.name ?? null;
return {
id: row.id,
paymentId: row.paymentId,
invoiceId: row.invoiceId,
invoiceNumber: row.invoice.number,
invoiceTitle: row.invoice.title,
personName,
amount: Number(row.payment.amount),
currency: row.payment.currency,
number: row.number,
bank: row.bank,
dueDate: row.dueDate.toISOString(),
status: row.status,
notes: row.notes,
paidAt: row.payment.paidAt.toISOString(),
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
}
+150
View File
@@ -0,0 +1,150 @@
import { Injectable } from '@nestjs/common';
import type { CommissionEntryDto } from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import type { Actor } from '../common/record-scope';
function roundMoney(value: number): number {
return Math.round((value + Number.EPSILON) * 100) / 100;
}
@Injectable()
export class CommissionsService {
constructor(private readonly prisma: PrismaService) {}
async list(
organizationId: string,
actor: Pick<Actor, 'userId' | 'role'>,
): Promise<CommissionEntryDto[]> {
const rows = await this.prisma.commissionEntry.findMany({
where: {
organizationId,
...this.userScope(actor),
},
include: {
user: { select: { id: true, fullName: true } },
invoice: { select: { id: true, number: true, title: true, ownerId: true } },
},
orderBy: { createdAt: 'desc' },
take: 200,
});
return rows
.filter((row) => this.canSeeInvoice(actor, row.invoice.ownerId))
.map((row) => this.toDto(row));
}
async syncInvoice(organizationId: string, invoiceId: string) {
const invoice = await this.prisma.invoice.findFirst({
where: { id: invoiceId, organizationId },
include: {
owner: { select: { id: true, commissionPercent: true } },
lineItems: true,
commissionEntry: true,
},
});
if (!invoice) return;
const shouldPost =
invoice.kind !== 'credit' &&
invoice.status !== 'draft' &&
invoice.status !== 'canceled' &&
Boolean(invoice.ownerId);
if (!shouldPost) {
if (invoice.commissionEntry) {
await this.prisma.commissionEntry.update({
where: { id: invoice.commissionEntry.id },
data: { status: 'void', amount: 0 },
});
}
return;
}
const subtotal = invoice.lineItems.reduce(
(sum, item) => sum + Number(item.quantity) * Number(item.unitPrice),
0,
);
const discountAmount = Number(invoice.discountAmount ?? 0);
const taxPercent = Number(invoice.taxPercent ?? 0);
const taxAmount = roundMoney(
Math.max(0, subtotal - discountAmount) * (taxPercent / 100),
);
const payable = Math.abs(
roundMoney(subtotal - discountAmount + taxAmount),
);
const fixed = invoice.commissionFixedAmount;
const overridePercent = invoice.commissionPercent;
const defaultPercent = Number(invoice.owner?.commissionPercent ?? 0);
const percent =
fixed != null
? payable > 0
? roundMoney((Number(fixed) / payable) * 100)
: 0
: Number(overridePercent ?? defaultPercent);
const amount =
fixed != null ? roundMoney(Number(fixed)) : roundMoney((payable * percent) / 100);
await this.prisma.commissionEntry.upsert({
where: { invoiceId: invoice.id },
create: {
organizationId,
userId: invoice.ownerId!,
invoiceId: invoice.id,
percent: new Prisma.Decimal(percent),
amount: new Prisma.Decimal(amount),
currency: invoice.currency,
status: 'posted',
},
update: {
userId: invoice.ownerId!,
percent: new Prisma.Decimal(percent),
amount: new Prisma.Decimal(amount),
currency: invoice.currency,
status: 'posted',
},
});
}
private userScope(
actor: Pick<Actor, 'userId' | 'role'>,
): Prisma.CommissionEntryWhereInput {
if (actor.role === 'owner' || actor.role === 'admin') return {};
return { userId: actor.userId };
}
private canSeeInvoice(
actor: Pick<Actor, 'userId' | 'role'>,
ownerId: string | null,
) {
if (actor.role === 'owner' || actor.role === 'admin') return true;
return ownerId === actor.userId;
}
private toDto(row: {
id: string;
userId: string;
invoiceId: string;
percent: Prisma.Decimal;
amount: Prisma.Decimal;
currency: string;
status: string;
createdAt: Date;
user: { fullName: string };
invoice: { number: string; title: string };
}): CommissionEntryDto {
return {
id: row.id,
userId: row.userId,
userName: row.user.fullName,
invoiceId: row.invoiceId,
invoiceNumber: row.invoice.number,
invoiceTitle: row.invoice.title,
percent: Number(row.percent),
amount: Number(row.amount),
currency: row.currency,
status: row.status,
createdAt: row.createdAt.toISOString(),
};
}
}
+28
View File
@@ -0,0 +1,28 @@
import { IsIn, IsOptional, IsString, MaxLength } from 'class-validator';
const CHEQUE_STATUSES = ['pending', 'cleared', 'bounced'] as const;
export class UpdateChequeDto {
@IsOptional()
@IsString()
@MaxLength(80)
number?: string;
@IsOptional()
@IsString()
@MaxLength(120)
bank?: string;
@IsOptional()
@IsString()
dueDate?: string;
@IsOptional()
@IsIn(CHEQUE_STATUSES)
status?: (typeof CHEQUE_STATUSES)[number];
@IsOptional()
@IsString()
@MaxLength(2000)
notes?: string | null;
}
@@ -0,0 +1,40 @@
import { Body, Controller, Get, Param, Patch, Query, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { UpdateChequeDto } from './dto';
import { ChequesService } from './cheques.service';
import { CommissionsService } from './commissions.service';
type AuthUser = { organizationId: string; userId: string; role: string };
@Controller()
@UseGuards(JwtAuthGuard)
export class FinanceController {
constructor(
private readonly cheques: ChequesService,
private readonly commissions: CommissionsService,
) {}
@Get('cheques')
listCheques(
@CurrentUser() user: AuthUser,
@Query('status') status?: string,
@Query('q') q?: string,
) {
return this.cheques.list(user.organizationId, user, { status, q });
}
@Patch('cheques/:id')
updateCheque(
@CurrentUser() user: AuthUser,
@Param('id') id: string,
@Body() dto: UpdateChequeDto,
) {
return this.cheques.update(user.organizationId, id, user, dto);
}
@Get('commissions')
listCommissions(@CurrentUser() user: AuthUser) {
return this.commissions.list(user.organizationId, user);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { ChequesService } from './cheques.service';
import { CommissionsService } from './commissions.service';
import { FinanceController } from './finance.controller';
@Module({
imports: [AuthModule],
controllers: [FinanceController],
providers: [ChequesService, CommissionsService],
exports: [ChequesService, CommissionsService],
})
export class FinanceModule {}
+38
View File
@@ -0,0 +1,38 @@
import { Type } from 'class-transformer';
import {
IsIn,
IsNumber,
IsOptional,
IsString,
MaxLength,
MinLength,
} from 'class-validator';
export class CreateStockMovementDto {
@IsString()
@MinLength(1)
productId!: string;
@IsIn(['purchase', 'adjustment'])
type!: 'purchase' | 'adjustment';
@Type(() => Number)
@IsNumber()
quantity!: number;
@IsOptional()
@IsString()
@MaxLength(400)
note?: string;
}
export class UpdatePartyOpeningDto {
@Type(() => Number)
@IsNumber()
amount!: number;
@IsOptional()
@IsString()
@MaxLength(400)
note?: string;
}
@@ -0,0 +1,69 @@
import {
Body,
Controller,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { CreateStockMovementDto, UpdatePartyOpeningDto } from './dto';
import { InventoryService } from './inventory.service';
type AuthUser = { organizationId: string };
@Controller('inventory')
@UseGuards(JwtAuthGuard, RolesGuard)
export class InventoryController {
constructor(private readonly inventory: InventoryService) {}
@Get()
summary(@CurrentUser() user: AuthUser) {
return this.inventory.getSummary(user.organizationId);
}
@Get('movements')
movements(
@CurrentUser() user: AuthUser,
@Query('productId') productId?: string,
) {
return this.inventory.listMovements(user.organizationId, productId);
}
@Post('movements')
@Roles('owner', 'admin')
addMovement(
@CurrentUser() user: AuthUser,
@Body() dto: CreateStockMovementDto,
) {
return this.inventory.addManualMovement(user.organizationId, dto);
}
@Get('party/:personId')
partyBalance(
@CurrentUser() user: AuthUser,
@Param('personId') personId: string,
) {
return this.inventory.getPartyBalance(user.organizationId, personId);
}
@Patch('party/:personId/opening')
@Roles('owner', 'admin')
setOpening(
@CurrentUser() user: AuthUser,
@Param('personId') personId: string,
@Body() dto: UpdatePartyOpeningDto,
) {
return this.inventory.setPartyOpening(
user.organizationId,
personId,
dto.amount,
dto.note,
);
}
}
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { InventoryController } from './inventory.controller';
import { InventoryService } from './inventory.service';
@Module({
imports: [AuthModule],
controllers: [InventoryController],
providers: [InventoryService],
exports: [InventoryService],
})
export class InventoryModule {}
+515
View File
@@ -0,0 +1,515 @@
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import type {
InventorySummaryDto,
PartyBalanceDto,
StockMovementDto,
StockMovementType,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
const MOVEMENT_TYPES = new Set([
'opening',
'purchase',
'sale',
'credit',
'adjustment',
]);
@Injectable()
export class InventoryService {
constructor(private readonly prisma: PrismaService) {}
async isInternalEnabled(organizationId: string): Promise<boolean> {
const n = await this.prisma.accountingConnection.count({
where: { organizationId, enabled: true },
});
return n === 0;
}
async getSummary(organizationId: string): Promise<InventorySummaryDto> {
const enabled = await this.isInternalEnabled(organizationId);
const org = await this.prisma.organization.findFirst({
where: { id: organizationId },
select: { baseCurrency: true },
});
const currency = org?.baseCurrency ?? 'IRR';
if (!enabled) {
return {
enabled: false,
warehouseName: null,
products: [],
cashTotal: 0,
receivablesTotal: 0,
currency,
};
}
const warehouse = await this.ensureReady(organizationId);
const products = await this.prisma.product.findMany({
where: { organizationId, kind: 'product' },
orderBy: [{ isActive: 'desc' }, { name: 'asc' }],
});
const stocks = await this.stockByProduct(
organizationId,
products.map((p) => p.id),
);
const [cashTotal, receivablesTotal] = await Promise.all([
this.cashTotal(organizationId),
this.receivablesTotal(organizationId),
]);
return {
enabled: true,
warehouseName: warehouse.name,
products: products.map((p) => ({
productId: p.id,
name: p.name,
sku: p.sku,
unit: p.unit,
kind: 'product',
stockQty: stocks.get(p.id) ?? 0,
currency: p.currency,
unitPrice: p.unitPrice == null ? null : Number(p.unitPrice),
})),
cashTotal,
receivablesTotal,
currency,
};
}
async listMovements(
organizationId: string,
productId?: string,
): Promise<StockMovementDto[]> {
if (!(await this.isInternalEnabled(organizationId))) return [];
await this.ensureReady(organizationId);
const rows = await this.prisma.stockMovement.findMany({
where: {
organizationId,
...(productId ? { productId } : {}),
},
include: { product: { select: { name: true } } },
orderBy: [{ occurredAt: 'desc' }, { createdAt: 'desc' }],
take: 200,
});
return rows.map((row) => ({
id: row.id,
productId: row.productId,
productName: row.product.name,
type: asMovementType(row.type),
quantity: Number(row.quantity),
note: row.note,
invoiceId: row.invoiceId,
occurredAt: row.occurredAt.toISOString(),
}));
}
async addManualMovement(
organizationId: string,
dto: { productId: string; type: 'purchase' | 'adjustment'; quantity: number; note?: string },
): Promise<StockMovementDto> {
if (!(await this.isInternalEnabled(organizationId))) {
throw new BadRequestException(
'با اتصال ته‌حساب، انبار داخلی غیرفعال است',
);
}
const warehouse = await this.ensureReady(organizationId);
const product = await this.prisma.product.findFirst({
where: { id: dto.productId, organizationId },
});
if (!product) throw new NotFoundException('محصول پیدا نشد');
if (product.kind === 'service') {
throw new BadRequestException('خدمات موجودی انبار ندارند');
}
let quantity = Number(dto.quantity);
if (!Number.isFinite(quantity) || quantity === 0) {
throw new BadRequestException('مقدار نامعتبر است');
}
if (dto.type === 'purchase' && quantity < 0) {
throw new BadRequestException('ورود خرید باید مثبت باشد');
}
const row = await this.prisma.stockMovement.create({
data: {
organizationId,
warehouseId: warehouse.id,
productId: product.id,
type: dto.type,
quantity: new Prisma.Decimal(quantity),
note: dto.note?.trim() || null,
},
include: { product: { select: { name: true } } },
});
await this.refreshProductStock(organizationId, product.id);
return {
id: row.id,
productId: row.productId,
productName: row.product.name,
type: asMovementType(row.type),
quantity: Number(row.quantity),
note: row.note,
invoiceId: row.invoiceId,
occurredAt: row.occurredAt.toISOString(),
};
}
async getPartyBalance(
organizationId: string,
personId: string,
): Promise<PartyBalanceDto> {
const enabled = await this.isInternalEnabled(organizationId);
const org = await this.prisma.organization.findFirst({
where: { id: organizationId },
select: { baseCurrency: true },
});
const currency = org?.baseCurrency ?? 'IRR';
if (!enabled) {
return {
enabled: false,
personId,
openingAmount: 0,
invoicedAmount: 0,
paidAmount: 0,
balance: 0,
currency,
};
}
const person = await this.prisma.person.findFirst({
where: { id: personId, organizationId },
select: { id: true },
});
if (!person) throw new NotFoundException('شخص پیدا نشد');
const { openingAmount, invoicedAmount, paidAmount } =
await this.personLedger(organizationId, personId);
return {
enabled: true,
personId,
openingAmount,
invoicedAmount,
paidAmount,
balance: roundMoney(openingAmount + invoicedAmount - paidAmount),
currency,
};
}
async setPartyOpening(
organizationId: string,
personId: string,
amount: number,
note?: string,
): Promise<PartyBalanceDto> {
if (!(await this.isInternalEnabled(organizationId))) {
throw new BadRequestException(
'با اتصال ته‌حساب، مانده داخلی غیرفعال است',
);
}
const person = await this.prisma.person.findFirst({
where: { id: personId, organizationId },
select: { id: true },
});
if (!person) throw new NotFoundException('شخص پیدا نشد');
if (!Number.isFinite(amount)) {
throw new BadRequestException('مبلغ نامعتبر است');
}
await this.prisma.partyOpeningBalance.upsert({
where: { organizationId_personId: { organizationId, personId } },
create: {
organizationId,
personId,
amount: new Prisma.Decimal(amount),
note: note?.trim() || null,
},
update: {
amount: new Prisma.Decimal(amount),
note: note?.trim() || null,
},
});
return this.getPartyBalance(organizationId, personId);
}
async syncInvoiceStock(organizationId: string, invoiceId: string) {
if (!(await this.isInternalEnabled(organizationId))) {
await this.prisma.stockMovement.deleteMany({ where: { invoiceId } });
return;
}
const warehouse = await this.ensureReady(organizationId);
const invoice = await this.prisma.invoice.findFirst({
where: { id: invoiceId, organizationId },
include: {
lineItems: { include: { product: { select: { id: true, kind: true } } } },
},
});
if (!invoice) return;
const productIds = [
...new Set(
invoice.lineItems
.map((l) => l.productId)
.filter((id): id is string => Boolean(id)),
),
];
await this.prisma.stockMovement.deleteMany({ where: { invoiceId } });
const active =
invoice.status !== 'draft' && invoice.status !== 'canceled';
if (active) {
const isCredit = invoice.kind === 'credit';
const sign = isCredit ? 1 : -1;
const type = isCredit ? 'credit' : 'sale';
const rows = invoice.lineItems
.filter((l) => l.productId && l.product?.kind !== 'service')
.map((l) => ({
organizationId,
warehouseId: warehouse.id,
productId: l.productId!,
type,
quantity: new Prisma.Decimal(sign * Number(l.quantity)),
note: invoice.number,
invoiceId,
occurredAt: invoice.issuedAt ?? new Date(),
}));
if (rows.length) {
await this.prisma.stockMovement.createMany({ data: rows });
}
}
await Promise.all(
productIds.map((id) => this.refreshProductStock(organizationId, id)),
);
}
async onProductCreated(
organizationId: string,
productId: string,
stockQty: number | null,
kind: string,
) {
if (kind === 'service') return;
if (!(await this.isInternalEnabled(organizationId))) return;
if (stockQty == null || stockQty === 0) return;
const warehouse = await this.ensureReady(organizationId);
const existing = await this.prisma.stockMovement.count({
where: { productId },
});
if (existing) return;
await this.prisma.stockMovement.create({
data: {
organizationId,
warehouseId: warehouse.id,
productId,
type: 'opening',
quantity: new Prisma.Decimal(stockQty),
note: 'موجودی اول دوره',
},
});
await this.refreshProductStock(organizationId, productId);
}
async onProductStockEdited(
organizationId: string,
productId: string,
nextQty: number | null,
kind: string,
) {
if (kind === 'service') return;
if (!(await this.isInternalEnabled(organizationId))) return;
const warehouse = await this.ensureReady(organizationId);
const current = await this.liveStock(organizationId, productId);
const target = nextQty ?? 0;
const delta = target - current;
if (Math.abs(delta) < 0.0001) {
await this.refreshProductStock(organizationId, productId);
return;
}
await this.prisma.stockMovement.create({
data: {
organizationId,
warehouseId: warehouse.id,
productId,
type: 'adjustment',
quantity: new Prisma.Decimal(delta),
note: 'اصلاح از فرم محصول',
},
});
await this.refreshProductStock(organizationId, productId);
}
private async ensureReady(organizationId: string) {
let warehouse = await this.prisma.warehouse.findFirst({
where: { organizationId, isDefault: true },
});
if (!warehouse) {
warehouse = await this.prisma.warehouse.create({
data: {
organizationId,
name: 'انبار اصلی',
isDefault: true,
},
});
}
const products = await this.prisma.product.findMany({
where: { organizationId, kind: 'product', stockQty: { not: null } },
select: { id: true, stockQty: true },
});
for (const product of products) {
const count = await this.prisma.stockMovement.count({
where: { productId: product.id },
});
if (count > 0 || product.stockQty == null || product.stockQty === 0) {
continue;
}
await this.prisma.stockMovement.create({
data: {
organizationId,
warehouseId: warehouse.id,
productId: product.id,
type: 'opening',
quantity: new Prisma.Decimal(product.stockQty),
note: 'موجودی اول دوره',
},
});
}
return warehouse;
}
private async stockByProduct(
organizationId: string,
productIds: string[],
): Promise<Map<string, number>> {
const map = new Map<string, number>();
if (!productIds.length) return map;
const groups = await this.prisma.stockMovement.groupBy({
by: ['productId'],
where: { organizationId, productId: { in: productIds } },
_sum: { quantity: true },
});
for (const g of groups) {
map.set(g.productId, Number(g._sum.quantity ?? 0));
}
return map;
}
private async liveStock(organizationId: string, productId: string) {
const agg = await this.prisma.stockMovement.aggregate({
where: { organizationId, productId },
_sum: { quantity: true },
});
return Number(agg._sum.quantity ?? 0);
}
private async refreshProductStock(organizationId: string, productId: string) {
const live = await this.liveStock(organizationId, productId);
await this.prisma.product.update({
where: { id: productId },
data: { stockQty: Math.round(live) },
});
}
private async cashTotal(organizationId: string): Promise<number> {
const payments = await this.prisma.payment.findMany({
where: {
invoice: {
organizationId,
status: { not: 'canceled' },
},
},
select: { amount: true },
});
return roundMoney(payments.reduce((s, p) => s + Number(p.amount), 0));
}
private async receivablesTotal(organizationId: string): Promise<number> {
const openings = await this.prisma.partyOpeningBalance.findMany({
where: { organizationId },
select: { amount: true },
});
const openingSum = openings.reduce((s, r) => s + Number(r.amount), 0);
const invoices = await this.prisma.invoice.findMany({
where: {
organizationId,
status: { in: ['issued', 'partially_paid', 'paid'] },
},
include: { lineItems: true, payments: true },
});
let remaining = 0;
for (const inv of invoices) {
remaining += invoiceRemaining(inv);
}
return roundMoney(openingSum + remaining);
}
private async personLedger(organizationId: string, personId: string) {
const opening = await this.prisma.partyOpeningBalance.findFirst({
where: { organizationId, personId },
});
const invoices = await this.prisma.invoice.findMany({
where: {
organizationId,
personId,
status: { in: ['issued', 'partially_paid', 'paid'] },
},
include: { lineItems: true, payments: true },
});
let invoicedAmount = 0;
let paidAmount = 0;
for (const inv of invoices) {
invoicedAmount += invoicePayable(inv);
paidAmount += inv.payments.reduce((s, p) => s + Number(p.amount), 0);
}
return {
openingAmount: Number(opening?.amount ?? 0),
invoicedAmount: roundMoney(invoicedAmount),
paidAmount: roundMoney(paidAmount),
};
}
}
function asMovementType(type: string): StockMovementType {
if (MOVEMENT_TYPES.has(type)) return type as StockMovementType;
return 'adjustment';
}
function invoicePayable(inv: {
kind: string;
discountAmount: Prisma.Decimal;
taxPercent: Prisma.Decimal;
lineItems: Array<{ quantity: Prisma.Decimal; unitPrice: Prisma.Decimal }>;
}): number {
const subtotal = inv.lineItems.reduce(
(s, i) => s + Number(i.quantity) * Number(i.unitPrice),
0,
);
const discount = Number(inv.discountAmount ?? 0);
const taxPercent = Number(inv.taxPercent ?? 0);
const tax = Math.max(0, subtotal - discount) * (taxPercent / 100);
const signed = roundMoney(subtotal - discount + tax);
return inv.kind === 'credit' ? -signed : signed;
}
function invoiceRemaining(inv: {
kind: string;
discountAmount: Prisma.Decimal;
taxPercent: Prisma.Decimal;
lineItems: Array<{ quantity: Prisma.Decimal; unitPrice: Prisma.Decimal }>;
payments: Array<{ amount: Prisma.Decimal }>;
}): number {
const payable = invoicePayable(inv);
const paid = inv.payments.reduce((s, p) => s + Number(p.amount), 0);
return payable - paid;
}
function roundMoney(n: number) {
return Math.round(n * 100) / 100;
}
+53
View File
@@ -151,6 +151,18 @@ export class CreateInvoiceDto {
@ValidateNested({ each: true })
@Type(() => InvoiceInstallmentInputDto)
installments?: InvoiceInstallmentInputDto[];
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
commissionPercent?: number | null;
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
commissionFixedAmount?: number | null;
}
export class UpdateInvoiceDto {
@@ -225,6 +237,42 @@ export class UpdateInvoiceDto {
@ValidateNested({ each: true })
@Type(() => InvoiceInstallmentInputDto)
installments?: InvoiceInstallmentInputDto[];
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
commissionPercent?: number | null;
@IsOptional()
@Type(() => Number)
@IsNumber()
@Min(0)
commissionFixedAmount?: number | null;
}
export class ChequeInputDto {
@IsString()
@MinLength(1)
@MaxLength(80)
number!: string;
@IsString()
@MinLength(1)
@MaxLength(120)
bank!: string;
@IsString()
dueDate!: string;
@IsOptional()
@IsIn(['pending', 'cleared', 'bounced'])
status?: 'pending' | 'cleared' | 'bounced';
@IsOptional()
@IsString()
@MaxLength(2000)
notes?: string;
}
export class CreatePaymentDto {
@@ -254,6 +302,11 @@ export class CreatePaymentDto {
@IsOptional()
@IsString()
installmentId?: string | null;
@IsOptional()
@ValidateNested()
@Type(() => ChequeInputDto)
cheque?: ChequeInputDto;
}
export class ListInvoicesQueryDto {
+4
View File
@@ -1,8 +1,12 @@
import { Module } from '@nestjs/common';
import { AutomationsModule } from '../automations/automations.module';
import { FinanceModule } from '../finance/finance.module';
import { InventoryModule } from '../inventory/inventory.module';
import { InvoicesController } from './invoices.controller';
import { InvoicesService } from './invoices.service';
@Module({
imports: [AutomationsModule, InventoryModule, FinanceModule],
controllers: [InvoicesController],
providers: [InvoicesService],
exports: [InvoicesService],
+151 -8
View File
@@ -16,6 +16,9 @@ import type {
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { type Actor, ownerWhere } from '../common/record-scope';
import { AutomationsService } from '../automations/automations.service';
import { InventoryService } from '../inventory/inventory.service';
import { CommissionsService } from '../finance/commissions.service';
type InvoiceActor = Pick<Actor, 'userId' | 'role'>;
@@ -26,7 +29,11 @@ const include = {
quote: { select: { id: true, number: true, title: true } },
owner: { select: { id: true, fullName: true } },
lineItems: { orderBy: { position: 'asc' as const } },
payments: { orderBy: { paidAt: 'desc' as const } },
payments: {
orderBy: { paidAt: 'desc' as const },
include: { cheque: true },
},
commissionEntry: true,
installments: {
orderBy: { position: 'asc' as const },
include: { payment: { select: { id: true } } },
@@ -37,7 +44,12 @@ type InvoiceRow = Prisma.InvoiceGetPayload<{ include: typeof include }>;
@Injectable()
export class InvoicesService {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly automations: AutomationsService,
private readonly inventory: InventoryService,
private readonly commissions: CommissionsService,
) {}
async list(
organizationId: string,
@@ -243,6 +255,14 @@ export class InvoicesService {
dealId,
quoteId,
ownerId: userId,
commissionPercent:
dto.commissionPercent != null
? new Prisma.Decimal(dto.commissionPercent)
: null,
commissionFixedAmount:
dto.commissionFixedAmount != null
? new Prisma.Decimal(dto.commissionFixedAmount)
: null,
...(lineItems.length
? {
lineItems: {
@@ -264,7 +284,17 @@ export class InvoicesService {
},
include,
});
return this.toDto(row);
await this.inventory.syncInvoiceStock(organizationId, row.id);
await this.commissions.syncInvoice(organizationId, row.id);
const fresh = await this.prisma.invoice.findFirst({
where: { id: row.id },
include,
});
const created = this.toDto(fresh ?? row);
if (created.status !== 'draft' && created.status !== 'canceled') {
await this.fireIssued(organizationId, created);
}
return created;
}
async update(
@@ -323,6 +353,18 @@ export class InvoicesService {
if ('companyId' in dto) data.companyId = emptyToNull(dto.companyId ?? null);
if ('dealId' in dto) data.dealId = emptyToNull(dto.dealId ?? null);
if ('quoteId' in dto) data.quoteId = emptyToNull(dto.quoteId ?? null);
if ('commissionPercent' in dto) {
data.commissionPercent =
dto.commissionPercent == null
? null
: new Prisma.Decimal(dto.commissionPercent);
}
if ('commissionFixedAmount' in dto) {
data.commissionFixedAmount =
dto.commissionFixedAmount == null
? null
: new Prisma.Decimal(dto.commissionFixedAmount);
}
if (
dto.status &&
@@ -374,7 +416,17 @@ export class InvoicesService {
await this.recomputeStatus(id);
}
return this.get(organizationId, id, actor);
const row = await this.get(organizationId, id, actor);
await this.inventory.syncInvoiceStock(organizationId, row.id);
await this.commissions.syncInvoice(organizationId, row.id);
const leftDraft =
existing.status === 'draft' &&
row.status !== 'draft' &&
row.status !== 'canceled';
if (leftDraft) {
await this.fireIssued(organizationId, row);
}
return row;
}
async remove(
@@ -394,13 +446,23 @@ export class InvoicesService {
): Promise<InvoiceDto> {
const invoice = await this.prisma.invoice.findFirst({
where: { id: invoiceId, organizationId, ...ownerWhere(actor) },
select: { id: true, status: true, currency: true },
select: { id: true, status: true, currency: true, organizationId: true },
});
if (!invoice) throw new NotFoundException('فاکتور پیدا نشد');
if (invoice.status === 'canceled') {
throw new BadRequestException('روی فاکتور لغوشده نمی‌توان پرداخت ثبت کرد');
}
const method = (dto.method as string) || 'transfer';
if (method === 'check') {
const cheque = dto.cheque;
if (!cheque?.number?.trim() || !cheque.bank?.trim() || !cheque.dueDate) {
throw new BadRequestException(
'برای پرداخت چکی شماره، بانک و تاریخ سررسید لازم است',
);
}
}
const installmentId = emptyToNull(dto.installmentId ?? null);
if (installmentId) {
const installment = await this.prisma.invoiceInstallment.findFirst({
@@ -414,17 +476,33 @@ export class InvoicesService {
}
await this.prisma.$transaction(async (tx) => {
await tx.payment.create({
const payment = await tx.payment.create({
data: {
invoiceId,
amount: new Prisma.Decimal(dto.amount),
currency: (dto.currency ?? invoice.currency).trim() || 'IRR',
method: (dto.method as never) || 'transfer',
method: method as never,
paidAt: dto.paidAt ? new Date(dto.paidAt) : new Date(),
notes: emptyToNull(dto.notes ?? null),
installmentId,
},
});
if (method === 'check' && dto.cheque) {
await tx.cheque.create({
data: {
organizationId: invoice.organizationId,
paymentId: payment.id,
invoiceId,
number: dto.cheque.number.trim(),
bank: dto.cheque.bank.trim(),
dueDate: new Date(dto.cheque.dueDate),
status: dto.cheque.status === 'cleared' || dto.cheque.status === 'bounced'
? dto.cheque.status
: 'pending',
notes: emptyToNull(dto.cheque.notes ?? null),
},
});
}
if (installmentId) {
await tx.invoiceInstallment.update({
where: { id: installmentId },
@@ -443,7 +521,23 @@ export class InvoicesService {
});
await this.recomputeStatus(invoiceId);
return this.get(organizationId, invoiceId, actor);
const row = await this.get(organizationId, invoiceId, actor);
await this.inventory.syncInvoiceStock(organizationId, row.id);
await this.commissions.syncInvoice(organizationId, row.id);
if (invoice.status === 'draft') {
await this.fireIssued(organizationId, row);
}
await this.automations.runTrigger('invoice_paid', {
organizationId,
entityType: 'invoice',
entityId: row.id,
title: row.title || row.number,
personId: row.person?.id ?? null,
companyId: row.company?.id ?? null,
dealId: row.deal?.id ?? null,
ownerId: row.owner?.id ?? null,
});
return row;
}
async removePayment(
@@ -469,6 +563,7 @@ export class InvoicesService {
});
await this.recomputeStatus(invoiceId);
await this.commissions.syncInvoice(organizationId, invoiceId);
return this.get(organizationId, invoiceId, actor);
}
@@ -549,6 +644,19 @@ export class InvoicesService {
return `FA-${String(count + 1).padStart(4, '0')}`;
}
private async fireIssued(organizationId: string, row: InvoiceDto) {
await this.automations.runTrigger('invoice_issued', {
organizationId,
entityType: 'invoice',
entityId: row.id,
title: row.title || row.number,
personId: row.person?.id ?? null,
companyId: row.company?.id ?? null,
dealId: row.deal?.id ?? null,
ownerId: row.owner?.id ?? null,
});
}
private async ensureExists(
organizationId: string,
id: string,
@@ -650,6 +758,28 @@ export class InvoicesService {
paidAt: p.paidAt.toISOString(),
notes: p.notes,
installmentId: p.installmentId,
cheque: p.cheque
? {
id: p.cheque.id,
paymentId: p.id,
invoiceId: row.id,
invoiceNumber: row.number,
invoiceTitle: row.title,
personName: row.person
? `${row.person.firstName} ${row.person.lastName}`.trim()
: row.company?.name ?? null,
amount: Number(p.amount),
currency: p.currency,
number: p.cheque.number,
bank: p.cheque.bank,
dueDate: p.cheque.dueDate.toISOString(),
status: p.cheque.status,
notes: p.cheque.notes,
paidAt: p.paidAt.toISOString(),
createdAt: p.cheque.createdAt.toISOString(),
updatedAt: p.cheque.updatedAt.toISOString(),
}
: null,
createdAt: p.createdAt.toISOString(),
}));
const paidAmount = payments.reduce((sum, p) => sum + p.amount, 0);
@@ -695,6 +825,19 @@ export class InvoicesService {
lineItems,
payments,
installments,
commissionPercent:
row.commissionPercent == null ? null : Number(row.commissionPercent),
commissionFixedAmount:
row.commissionFixedAmount == null
? null
: Number(row.commissionFixedAmount),
commission: row.commissionEntry
? {
percent: Number(row.commissionEntry.percent),
amount: Number(row.commissionEntry.amount),
status: row.commissionEntry.status,
}
: null,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
+2 -1
View File
@@ -1,11 +1,12 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { AutomationsModule } from '../automations/automations.module';
import { LeadFormsController } from './lead-forms.controller';
import { LeadFormsService } from './lead-forms.service';
import { PublicLeadFormsController } from './public-lead-forms.controller';
@Module({
imports: [AuthModule],
imports: [AuthModule, AutomationsModule],
controllers: [LeadFormsController, PublicLeadFormsController],
providers: [LeadFormsService],
exports: [LeadFormsService],
@@ -14,6 +14,7 @@ import type {
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { LocalFileStorage } from '../storage/local-file.storage';
import { AutomationsService } from '../automations/automations.service';
import {
emptyToNull,
normalizeEmail,
@@ -66,6 +67,7 @@ export class LeadFormsService {
constructor(
private readonly prisma: PrismaService,
private readonly files: LocalFileStorage,
private readonly automations: AutomationsService,
) {}
async list(organizationId: string): Promise<LeadFormDto[]> {
@@ -275,6 +277,19 @@ export class LeadFormsService {
});
}
const personName = [mapped.firstName, mapped.lastName]
.filter((p) => p?.trim())
.join(' ')
.trim();
await this.automations.runTrigger('lead_submitted', {
organizationId: form.organizationId,
entityType: 'person',
entityId: personId ?? form.id,
title: personName || form.name,
personId,
ownerId: ownerId ?? actorId,
});
return {
ok: true,
thankYouMessage: form.thankYouMessage,
+22 -4
View File
@@ -147,6 +147,17 @@ export class DealsService {
include: dealInclude,
});
await this.automations.runTrigger('deal_created', {
organizationId,
entityType: 'deal',
entityId: created.id,
title: created.title,
personId: created.personId,
companyId: created.companyId,
dealId: created.id,
ownerId: created.ownerId,
});
return this.pipelines.toDealDto(created);
}
@@ -290,17 +301,24 @@ export class DealsService {
});
}
if (status === 'won' && deal.status !== 'won') {
await this.automations.runTrigger('deal_won', {
if (deal.stageId !== stage.id) {
const ctx = {
organizationId,
entityType: 'deal',
entityType: 'deal' as const,
entityId: deal.id,
title: deal.title,
personId: deal.personId,
companyId: deal.companyId,
dealId: deal.id,
ownerId: deal.ownerId,
});
};
await this.automations.runTrigger('deal_stage_changed', ctx);
if (status === 'won' && deal.status !== 'won') {
await this.automations.runTrigger('deal_won', ctx);
}
if (status === 'lost' && deal.status !== 'lost') {
await this.automations.runTrigger('deal_lost', ctx);
}
}
return this.pipelines.toDealDto(row);
+21
View File
@@ -21,6 +21,27 @@ export class CreatePipelineDto {
name!: string;
}
export class CreatePipelineStageDto {
@IsString()
@MinLength(1)
@MaxLength(80)
name!: string;
}
export class UpdatePipelineStageDto {
@IsOptional()
@IsString()
@MinLength(1)
@MaxLength(80)
name?: string;
}
export class ReorderPipelineStagesDto {
@IsArray()
@IsString({ each: true })
stageIds!: string[];
}
export class DealLineItemInputDto {
@IsOptional()
@ValidateIf((_, v) => v !== '' && v != null)
+67 -1
View File
@@ -1,7 +1,10 @@
import {
Body,
Controller,
Delete,
Get,
Param,
Patch,
Post,
Query,
UseGuards,
@@ -10,7 +13,12 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { CreatePipelineDto } from './dto';
import {
CreatePipelineDto,
CreatePipelineStageDto,
ReorderPipelineStagesDto,
UpdatePipelineStageDto,
} from './dto';
import { PipelinesService } from './pipelines.service';
@Controller('pipelines')
@@ -42,4 +50,62 @@ export class PipelinesController {
) {
return this.pipelinesService.create(user.organizationId, dto.name);
}
@Post(':pipelineId/stages')
@Roles('owner', 'admin')
createStage(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
@Body() dto: CreatePipelineStageDto,
) {
return this.pipelinesService.createStage(
user.organizationId,
pipelineId,
dto.name,
);
}
@Patch(':pipelineId/stages/order')
@Roles('owner', 'admin')
reorderStages(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
@Body() dto: ReorderPipelineStagesDto,
) {
return this.pipelinesService.reorderStages(
user.organizationId,
pipelineId,
dto.stageIds,
);
}
@Patch(':pipelineId/stages/:stageId')
@Roles('owner', 'admin')
updateStage(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
@Param('stageId') stageId: string,
@Body() dto: UpdatePipelineStageDto,
) {
return this.pipelinesService.updateStage(
user.organizationId,
pipelineId,
stageId,
dto.name,
);
}
@Delete(':pipelineId/stages/:stageId')
@Roles('owner', 'admin')
deleteStage(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
@Param('stageId') stageId: string,
) {
return this.pipelinesService.deleteStage(
user.organizationId,
pipelineId,
stageId,
);
}
}
+137 -1
View File
@@ -1,4 +1,8 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import type {
DealDto,
PipelineBoardDto,
@@ -114,6 +118,121 @@ export class PipelinesService {
return this.toPipelineDto(created);
}
async createStage(
organizationId: string,
pipelineId: string,
name: string,
): Promise<PipelineDto> {
const pipeline = await this.getOwnedPipeline(organizationId, pipelineId);
const trimmed = name.trim();
if (!trimmed) throw new BadRequestException('نام ستون لازم است');
const firstClosed = pipeline.stages.findIndex((s) => s.isWon || s.isLost);
const insertAt = firstClosed === -1 ? pipeline.stages.length : firstClosed;
await this.prisma.$transaction(async (tx) => {
await tx.pipelineStage.updateMany({
where: { pipelineId: pipeline.id, position: { gte: insertAt } },
data: { position: { increment: 1 } },
});
await tx.pipelineStage.create({
data: {
pipelineId: pipeline.id,
name: trimmed,
position: insertAt,
isWon: false,
isLost: false,
},
});
});
return this.getOwnedPipelineDto(organizationId, pipeline.id);
}
async updateStage(
organizationId: string,
pipelineId: string,
stageId: string,
name?: string,
): Promise<PipelineDto> {
const pipeline = await this.getOwnedPipeline(organizationId, pipelineId);
const stage = pipeline.stages.find((s) => s.id === stageId);
if (!stage) throw new NotFoundException('ستون پیدا نشد');
const trimmed = name?.trim() ?? '';
if (!trimmed) throw new BadRequestException('نام ستون لازم است');
await this.prisma.pipelineStage.update({
where: { id: stage.id },
data: { name: trimmed },
});
return this.getOwnedPipelineDto(organizationId, pipeline.id);
}
async deleteStage(
organizationId: string,
pipelineId: string,
stageId: string,
): Promise<PipelineDto> {
const pipeline = await this.getOwnedPipeline(organizationId, pipelineId);
const stage = pipeline.stages.find((s) => s.id === stageId);
if (!stage) throw new NotFoundException('ستون پیدا نشد');
if (pipeline.stages.length <= 1) {
throw new BadRequestException('حداقل یک ستون باید باقی بماند');
}
const dealCount = await this.prisma.deal.count({
where: { organizationId, stageId: stage.id },
});
if (dealCount > 0) {
throw new BadRequestException(
'ابتدا معاملات این ستون را به ستون دیگری منتقل کنید',
);
}
const remaining = pipeline.stages.filter((s) => s.id !== stage.id);
await this.prisma.$transaction([
this.prisma.pipelineStage.delete({ where: { id: stage.id } }),
...remaining.map((s, index) =>
this.prisma.pipelineStage.update({
where: { id: s.id },
data: { position: index },
}),
),
]);
return this.getOwnedPipelineDto(organizationId, pipeline.id);
}
async reorderStages(
organizationId: string,
pipelineId: string,
stageIds: string[],
): Promise<PipelineDto> {
const pipeline = await this.getOwnedPipeline(organizationId, pipelineId);
const currentIds = pipeline.stages.map((s) => s.id);
const unique = new Set(stageIds);
if (
stageIds.length !== currentIds.length ||
unique.size !== currentIds.length ||
currentIds.some((id) => !unique.has(id))
) {
throw new BadRequestException('ترتیب ستون‌ها نامعتبر است');
}
await this.prisma.$transaction(
stageIds.map((id, index) =>
this.prisma.pipelineStage.update({
where: { id },
data: { position: index },
}),
),
);
return this.getOwnedPipelineDto(organizationId, pipeline.id);
}
async getBoard(
organizationId: string,
pipelineId?: string,
@@ -232,6 +351,23 @@ export class PipelinesService {
};
}
private async getOwnedPipeline(organizationId: string, pipelineId: string) {
const pipeline = await this.prisma.pipeline.findFirst({
where: { id: pipelineId, organizationId },
include: { stages: { orderBy: { position: 'asc' } } },
});
if (!pipeline) throw new NotFoundException('کاریز پیدا نشد');
return pipeline;
}
private async getOwnedPipelineDto(
organizationId: string,
pipelineId: string,
): Promise<PipelineDto> {
const pipeline = await this.getOwnedPipeline(organizationId, pipelineId);
return this.toPipelineDto(pipeline);
}
private toPipelineDto(row: {
id: string;
name: string;
+2 -1
View File
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { AuthModule } from '../auth/auth.module';
import { InventoryModule } from '../inventory/inventory.module';
import { ProductsController } from './products.controller';
import { ProductsService } from './products.service';
@Module({
imports: [AuthModule],
imports: [AuthModule, InventoryModule],
controllers: [ProductsController],
providers: [ProductsService],
exports: [ProductsService],
+19 -1
View File
@@ -10,6 +10,7 @@ import type {
} from '@mento/shared';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
import { InventoryService } from '../inventory/inventory.service';
type ProductRow = {
id: string;
@@ -33,7 +34,10 @@ type ProductRow = {
@Injectable()
export class ProductsService {
constructor(private readonly prisma: PrismaService) {}
constructor(
private readonly prisma: PrismaService,
private readonly inventory: InventoryService,
) {}
async list(
organizationId: string,
@@ -115,6 +119,12 @@ export class ProductsService {
isActive: dto.isActive ?? true,
},
});
await this.inventory.onProductCreated(
organizationId,
row.id,
row.stockQty,
row.kind,
);
return this.toDto(row);
}
@@ -154,6 +164,14 @@ export class ProductsService {
if (dto.isActive !== undefined) data.isActive = dto.isActive;
const row = await this.prisma.product.update({ where: { id }, data });
if ('stockQty' in dto) {
await this.inventory.onProductStockEdited(
organizationId,
row.id,
row.stockQty,
row.kind,
);
}
return this.toDto(row);
}
+12
View File
@@ -228,6 +228,18 @@ export class TicketsService {
});
}
await this.automations.runTrigger('ticket_created', {
organizationId: actor.organizationId,
entityType: 'ticket',
entityId: row.id,
title: row.subject,
personId: row.personId,
companyId: row.companyId,
dealId: row.dealId,
assigneeId: row.assigneeId,
ownerId: row.assigneeId,
});
return this.toDto(row);
}
+12
View File
@@ -1,8 +1,12 @@
import { Type } from 'class-transformer';
import {
IsEmail,
IsIn,
IsNumber,
IsString,
Max,
MaxLength,
Min,
MinLength,
} from 'class-validator';
@@ -31,3 +35,11 @@ export class UpdateUserRoleDto {
@IsIn(ALL_ROLES)
role!: (typeof ALL_ROLES)[number];
}
export class UpdateUserCommissionDto {
@Type(() => Number)
@IsNumber()
@Min(0)
@Max(100)
commissionPercent!: number;
}
+16 -1
View File
@@ -12,7 +12,7 @@ import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { InviteUserDto, UpdateUserRoleDto } from './dto';
import { InviteUserDto, UpdateUserCommissionDto, UpdateUserRoleDto } from './dto';
import { UsersService } from './users.service';
@Controller('users')
@@ -34,6 +34,21 @@ export class UsersController {
return this.usersService.invite(user.organizationId, user.role, dto);
}
@Patch(':id/commission')
@Roles('owner', 'admin')
updateCommission(
@CurrentUser() user: { organizationId: string; role: UserRole },
@Param('id') id: string,
@Body() dto: UpdateUserCommissionDto,
) {
return this.usersService.updateCommission(
user.organizationId,
user.role,
id,
dto.commissionPercent,
);
}
@Patch(':id/role')
@Roles('owner', 'admin')
updateRole(
+26
View File
@@ -7,6 +7,7 @@ import {
} from '@nestjs/common';
import type { InviteUserRequest, OrgUserDto, UserRole } from '@mento/shared';
import * as bcrypt from 'bcryptjs';
import { Prisma } from '@prisma/client';
import { PrismaService } from '../prisma/prisma.service';
@Injectable()
@@ -56,6 +57,29 @@ export class UsersService {
return this.toDto(row);
}
async updateCommission(
organizationId: string,
actorRole: UserRole,
targetId: string,
percent: number,
): Promise<OrgUserDto> {
if (actorRole !== 'owner' && actorRole !== 'admin') {
throw new ForbiddenException('فقط مالک یا مدیر می‌تواند پورسانت را تعیین کند');
}
if (percent < 0 || percent > 100) {
throw new BadRequestException('درصد پورسانت باید بین ۰ تا ۱۰۰ باشد');
}
const target = await this.prisma.user.findFirst({
where: { id: targetId, organizationId },
});
if (!target) throw new NotFoundException('کاربر پیدا نشد');
const row = await this.prisma.user.update({
where: { id: target.id },
data: { commissionPercent: new Prisma.Decimal(percent) },
});
return this.toDto(row);
}
async updateRole(
organizationId: string,
actor: { userId: string; role: UserRole },
@@ -100,6 +124,7 @@ export class UsersService {
email: string;
fullName: string;
role: UserRole;
commissionPercent?: { toString(): string } | number;
createdAt: Date;
}): OrgUserDto {
return {
@@ -107,6 +132,7 @@ export class UsersService {
email: row.email,
fullName: row.fullName,
role: row.role,
commissionPercent: Number(row.commissionPercent ?? 0),
createdAt: row.createdAt.toISOString(),
};
}
+2
View File
@@ -12,8 +12,10 @@
"dependencies": {
"@mento/shared": "*",
"axios": "^1.8.4",
"echarts": "^6.1.0",
"pinia": "^3.0.1",
"vue": "^3.5.13",
"vue-echarts": "^8.3.0",
"vue-router": "^4.5.0"
},
"devDependencies": {
+3 -3
View File
@@ -90,7 +90,7 @@ form {
gap: 0.45rem;
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 14px;
border-radius: var(--radius);
padding: 0.35rem 0.4rem 0.35rem 0.7rem;
}
@@ -110,7 +110,7 @@ input {
button {
border: 0;
border-radius: 10px;
border-radius: var(--radius);
background: #14b8a6;
color: #fff;
font: inherit;
@@ -126,7 +126,7 @@ button:disabled {
.answer {
background: #f0fdfa;
border-radius: 12px;
border-radius: var(--radius);
padding: 0.7rem 0.85rem;
}
+47 -58
View File
@@ -2,6 +2,7 @@
import { onMounted, ref, watch } from 'vue';
import { api } from '@/lib/api';
import JalaliDateInput from '@/components/JalaliDateInput.vue';
import { UiField, UiInput, UiSelect } from '@/components/ui';
import type {
CustomFieldDefinitionDto,
CustomFieldEntity,
@@ -58,27 +59,28 @@ onMounted(load);
<template>
<div v-if="loading" class="muted">بارگذاری فیلدهای سفارشی…</div>
<div v-else-if="fields.length" class="custom-block">
<h3>فیلدهای سفارشی</h3>
<div class="grid">
<div v-for="field in fields" :key="field.id" class="field">
<label :for="`cf-${field.key}`">
{{ field.label }}
<span v-if="field.required" class="req">*</span>
</label>
<select
<h3 class="custom-title">فیلدهای سفارشی</h3>
<div class="crm-form-grid-2">
<UiField
v-for="field in fields"
:key="field.id"
:label="field.label"
:required="field.required"
:for-id="`cf-${field.key}`"
>
<UiSelect
v-if="field.fieldType === 'select'"
:id="`cf-${field.key}`"
:value="String(displayValue(field.key))"
@change="setValue(field.key, ($event.target as HTMLSelectElement).value)"
:model-value="String(displayValue(field.key))"
@update:model-value="setValue(field.key, $event)"
>
<option value="">انتخاب کنید</option>
<option v-for="opt in field.options" :key="opt" :value="opt">
{{ opt }}
</option>
</select>
</UiSelect>
<label v-else-if="field.fieldType === 'boolean'" class="check">
<label v-else-if="field.fieldType === 'boolean'" class="cf-check">
<input
:id="`cf-${field.key}`"
type="checkbox"
@@ -87,20 +89,18 @@ onMounted(load);
setValue(field.key, ($event.target as HTMLInputElement).checked)
"
/>
فعال
<span>فعال</span>
</label>
<input
<UiInput
v-else-if="field.fieldType === 'number'"
:id="`cf-${field.key}`"
type="number"
:value="String(displayValue(field.key))"
@input="
:model-value="props.modelValue[field.key] != null ? Number(props.modelValue[field.key]) : ''"
@update:model-value="
setValue(
field.key,
($event.target as HTMLInputElement).value === ''
? null
: Number(($event.target as HTMLInputElement).value),
$event === '' || $event == null ? null : Number($event),
)
"
/>
@@ -112,66 +112,55 @@ onMounted(load);
@update:model-value="setValue(field.key, $event || null)"
/>
<input
<UiInput
v-else
:id="`cf-${field.key}`"
type="text"
:value="String(displayValue(field.key))"
@input="setValue(field.key, ($event.target as HTMLInputElement).value)"
:model-value="String(displayValue(field.key))"
@update:model-value="setValue(field.key, $event)"
/>
</div>
</UiField>
</div>
</div>
</template>
<style scoped>
.custom-block {
display: grid;
gap: 0.75rem;
padding-top: 0.4rem;
display: flex;
flex-direction: column;
gap: var(--sp-3);
padding-top: var(--sp-4);
border-top: 1px dashed var(--line);
width: 100%;
}
h3 {
.custom-title {
margin: 0;
font-size: 1rem;
}
.grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.9rem;
font-size: var(--fs-sm);
font-weight: var(--fw-semibold);
color: var(--ink-secondary);
}
.muted {
color: var(--muted);
font-size: var(--fs-xs);
}
.req {
color: #b42318;
}
.check {
display: flex;
.cf-check {
display: inline-flex;
align-items: center;
gap: 0.5rem;
font-weight: 500;
gap: var(--sp-2);
min-height: var(--control-h-md);
font-size: var(--fs-base);
font-weight: var(--fw-medium);
color: var(--ink);
cursor: pointer;
}
select,
input[type='text'],
input[type='number'] {
border: 1px solid var(--line);
border-radius: 12px;
padding: 0.8rem 0.95rem;
background: #fff;
font: inherit;
width: 100%;
}
@media (max-width: 700px) {
.grid {
grid-template-columns: 1fr;
}
.cf-check input[type='checkbox'] {
width: 18px;
height: 18px;
accent-color: var(--accent);
cursor: pointer;
}
</style>
+2 -2
View File
@@ -289,7 +289,7 @@ onMounted(load);
.composer input {
width: 100%;
border: 1px solid var(--line);
border-radius: 12px;
border-radius: var(--radius);
padding: 0.7rem 0.85rem;
background: #fff;
}
@@ -316,7 +316,7 @@ onMounted(load);
gap: 0.75rem;
align-items: flex-start;
border: 1px solid var(--line);
border-radius: 12px;
border-radius: var(--radius);
padding: 0.75rem 0.85rem;
background: #fbfcfb;
}
+22 -18
View File
@@ -655,14 +655,15 @@ onBeforeUnmount(() => {
.trigger {
width: 100%;
min-height: 44px;
min-height: var(--control-h);
height: var(--control-h);
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
gap: 0.45rem;
border: 1px solid var(--line, #e2e8f0);
border-radius: 12px;
padding: 0.7rem 0.85rem;
border-radius: var(--radius);
padding: 0 0.75rem;
background: #fff;
color: #0f172a;
font: inherit;
@@ -674,7 +675,7 @@ onBeforeUnmount(() => {
justify-content: flex-start;
gap: 0.8rem;
min-height: 52px;
border-radius: 16px;
border-radius: var(--radius);
padding: 0.45rem 0.85rem 0.45rem 0.45rem;
background: linear-gradient(180deg, #ffffff 0%, #f8fffd 100%);
}
@@ -697,7 +698,7 @@ onBeforeUnmount(() => {
left: 50%;
bottom: 50%;
transform-origin: center bottom;
border-radius: 99px;
border-radius: var(--radius);
background: #0f766e;
}
@@ -725,7 +726,7 @@ onBeforeUnmount(() => {
}
.clock-text {
font-weight: 800;
font-weight: 600;
font-variant-numeric: tabular-nums;
letter-spacing: 0.02em;
font-size: 1.05rem;
@@ -739,6 +740,9 @@ onBeforeUnmount(() => {
.trigger span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.trigger .empty {
@@ -764,7 +768,7 @@ onBeforeUnmount(() => {
max-height: calc(100vh - 16px);
overflow: auto;
background: #fff;
border-radius: 16px;
border-radius: var(--radius);
box-shadow: 0 18px 48px rgba(15, 23, 42, 0.18);
padding: 0.75rem 0.8rem 0.7rem;
font-family: IRANSans, Tahoma, sans-serif;
@@ -793,7 +797,7 @@ onBeforeUnmount(() => {
width: 32px;
height: 32px;
border: 0;
border-radius: 8px;
border-radius: var(--radius);
background: #f1f5f9;
color: #0f766e;
display: grid;
@@ -822,7 +826,7 @@ onBeforeUnmount(() => {
.day {
height: 34px;
border: 0;
border-radius: 9px;
border-radius: var(--radius);
background: none;
color: #0f172a;
font: inherit;
@@ -877,12 +881,12 @@ onBeforeUnmount(() => {
min-width: 5.1rem;
height: 4.1rem;
border: 0;
border-radius: 14px;
border-radius: var(--radius);
background: #f1f5f9;
color: #0f172a;
font: inherit;
font-size: 2.35rem;
font-weight: 800;
font-weight: 600;
font-variant-numeric: tabular-nums;
letter-spacing: 0.02em;
cursor: pointer;
@@ -896,7 +900,7 @@ onBeforeUnmount(() => {
.md-colon {
font-size: 2.2rem;
font-weight: 800;
font-weight: 600;
color: #0f172a;
line-height: 1;
padding-bottom: 0.15rem;
@@ -1001,7 +1005,7 @@ onBeforeUnmount(() => {
margin: 0;
text-align: center;
font-size: 1.2rem;
font-weight: 800;
font-weight: 600;
color: #0f766e;
letter-spacing: 0.04em;
}
@@ -1029,7 +1033,7 @@ onBeforeUnmount(() => {
height: 220px;
overflow: auto;
border: 1px solid #e2e8f0;
border-radius: 12px;
border-radius: var(--radius);
background: #f8fafc;
padding: 0.25rem;
scrollbar-width: thin;
@@ -1040,7 +1044,7 @@ onBeforeUnmount(() => {
width: 100%;
height: 36px;
border: 0;
border-radius: 8px;
border-radius: var(--radius);
background: transparent;
color: #334155;
font: inherit;
@@ -1083,9 +1087,9 @@ onBeforeUnmount(() => {
margin-inline-start: auto;
background: #14b8a6;
color: #fff;
border-radius: 10px;
border-radius: var(--radius);
padding: 0.4rem 0.8rem;
font-weight: 800;
font-weight: 600;
font-size: 0.8rem;
}
+2 -2
View File
@@ -203,7 +203,7 @@ h2 {
textarea {
border: 1px solid var(--line);
border-radius: 12px;
border-radius: var(--radius);
padding: 0.75rem 0.9rem;
background: #fff;
font: inherit;
@@ -221,7 +221,7 @@ textarea {
.items li {
border: 1px solid var(--line);
border-radius: 12px;
border-radius: var(--radius);
padding: 0.75rem 0.85rem;
background: #fff;
}
@@ -231,7 +231,7 @@ function formatPayloadSummary(value: NoteAiPayloadDto | null) {
margin-top: 0.75rem;
padding: 0.75rem 0.85rem;
border: 1px dashed var(--accent);
border-radius: 12px;
border-radius: var(--radius);
background: rgba(255, 255, 255, 0.65);
display: grid;
gap: 0.6rem;
@@ -281,7 +281,7 @@ header {
input[type='text'],
textarea {
border: 1px solid var(--line);
border-radius: 10px;
border-radius: var(--radius);
padding: 0.55rem 0.7rem;
font: inherit;
width: 100%;
+107 -71
View File
@@ -4,9 +4,10 @@ import { useRoute, useRouter } from 'vue-router';
import type { RouteLocationRaw } from 'vue-router';
import UiIcon from '@/components/UiIcon.vue';
const FAB_SIZE = 56;
const FAB_MARGIN = 20;
const POS_KEY = 'mento.quickCreateFab';
const FAB_SIZE = 36;
const FAB_MARGIN_BOTTOM = 24;
const FAB_MARGIN_LEFT = 24;
const POS_KEY = 'mento.quickCreateFab_v2';
type FabPos = { left: number; top: number };
@@ -67,7 +68,10 @@ const router = useRouter();
const hidden = computed(() => route.name === 'person-detail');
const isQuickCreateOpen = ref(false);
const ready = ref(false);
const fabPos = ref<FabPos>({ left: FAB_MARGIN, top: FAB_MARGIN });
const fabPos = ref<FabPos>({
left: FAB_MARGIN_LEFT,
top: typeof window !== 'undefined' ? window.innerHeight - FAB_MARGIN_BOTTOM - FAB_SIZE : 600,
});
const viewport = ref({ w: 1280, h: 800 });
const dragging = ref(false);
let dragMoved = false;
@@ -76,8 +80,8 @@ let dragOffsetY = 0;
function defaultPos(): FabPos {
return {
left: FAB_MARGIN,
top: Math.max(FAB_MARGIN, viewport.value.h - FAB_MARGIN - FAB_SIZE),
left: FAB_MARGIN_LEFT,
top: Math.max(8, viewport.value.h - FAB_MARGIN_BOTTOM - FAB_SIZE),
};
}
@@ -164,13 +168,18 @@ const fabStyle = computed(() => ({
}));
const panelStyle = computed(() => {
const gap = 18;
const width = Math.min(390, viewport.value.w - 32);
const gap = 12;
const edge = 16;
const width = Math.min(300, viewport.value.w - 32);
let left = fabPos.value.left;
left = Math.min(left, viewport.value.w - width - 16);
left = Math.max(16, left);
const spaceAbove = fabPos.value.top;
const placeAbove = spaceAbove > 360;
left = Math.min(left, viewport.value.w - width - edge);
left = Math.max(edge, left);
const spaceAbove = fabPos.value.top - edge;
const spaceBelow = viewport.value.h - (fabPos.value.top + FAB_SIZE) - edge;
const placeAbove = spaceAbove >= spaceBelow;
const maxHeight = Math.max(0, (placeAbove ? spaceAbove : spaceBelow) - gap);
if (placeAbove) {
return {
left: `${left}px`,
@@ -178,6 +187,7 @@ const panelStyle = computed(() => {
bottom: `${viewport.value.h - fabPos.value.top + gap}px`,
top: 'auto',
width: `${width}px`,
maxHeight: `${maxHeight}px`,
};
}
return {
@@ -186,6 +196,7 @@ const panelStyle = computed(() => {
top: `${fabPos.value.top + FAB_SIZE + gap}px`,
bottom: 'auto',
width: `${width}px`,
maxHeight: `${maxHeight}px`,
};
});
@@ -257,21 +268,23 @@ onBeforeUnmount(() => {
:style="panelStyle"
>
<h2 id="qc-title">ایجاد سریع</h2>
<button
v-for="item in items"
:key="item.key"
class="item"
type="button"
@click="go(item.to)"
>
<span class="ico" :class="item.tone">
<UiIcon :name="item.icon" :size="26" />
</span>
<span class="copy">
<strong>{{ item.title }}</strong>
<small>{{ item.desc }}</small>
</span>
</button>
<div class="items">
<button
v-for="item in items"
:key="item.key"
class="item"
type="button"
@click="go(item.to)"
>
<span class="item-ico" :class="item.tone">
<UiIcon :name="item.icon" :size="18" />
</span>
<span class="copy">
<strong>{{ item.title }}</strong>
<small>{{ item.desc }}</small>
</span>
</button>
</div>
</section>
<button
@@ -289,7 +302,7 @@ onBeforeUnmount(() => {
@pointercancel="onFabPointerUp"
>
<span class="fab-face" aria-hidden="true">
<UiIcon :name="isQuickCreateOpen ? 'x' : 'apps-plus'" :size="22" />
<UiIcon :name="isQuickCreateOpen ? 'x' : 'apps-plus'" :size="20" />
</span>
</button>
</div>
@@ -314,101 +327,121 @@ onBeforeUnmount(() => {
.panel {
position: fixed;
z-index: 92;
width: 390px;
width: 300px;
max-height: min(480px, calc(100dvh - 80px));
box-sizing: border-box;
display: flex;
flex-direction: column;
background: #fff;
border-radius: 28px;
padding: 20px;
box-shadow: 0 18px 48px rgba(15, 23, 42, 0.18);
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 12px 12px 10px;
box-shadow: var(--shadow-lg);
overflow: hidden;
}
.panel h2 {
margin: 0 0 16px;
flex-shrink: 0;
margin: 0 0 10px;
text-align: right;
font-size: 22px;
font-weight: 800;
color: #111827;
font-size: var(--fs-md);
font-weight: 700;
color: var(--ink);
}
.items {
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 6px;
padding-left: 2px;
overscroll-behavior: contain;
}
.item {
width: 100%;
height: 82px;
margin-bottom: 10px;
min-height: 46px;
display: flex;
align-items: center;
gap: 14px;
padding: 0 14px;
border: 1px solid #eef1f2;
border-radius: 16px;
gap: 10px;
padding: 6px 10px;
border: 1px solid var(--line-light);
border-radius: var(--radius);
background: #fff;
box-shadow: 0 4px 14px rgba(15, 23, 42, 0.04);
box-shadow: var(--shadow-xs);
font: inherit;
text-align: right;
cursor: pointer;
transition: background var(--transition-fast), border-color var(--transition-fast);
}
.item:last-child {
margin-bottom: 0;
.item:hover {
background: var(--surface-hover);
border-color: var(--line-strong);
}
.ico {
width: 52px;
height: 52px;
border-radius: 14px;
.item-ico {
width: 34px;
height: 34px;
border-radius: var(--radius);
display: grid;
place-items: center;
color: #fff;
flex-shrink: 0;
}
.ico.person {
.item-ico.person {
background: #0d9488;
}
.ico.company {
background: #22d3ee;
.item-ico.company {
background: #0891b2;
}
.ico.deal {
.item-ico.deal {
background: #7c3aed;
}
.ico.activity {
background: #f97316;
.item-ico.activity {
background: #ea580c;
}
.ico.note {
.item-ico.note {
background: #2563eb;
}
.copy {
display: grid;
gap: 4px;
gap: 2px;
min-width: 0;
text-align: right;
}
.copy strong {
font-size: 16px;
font-size: var(--fs-sm);
font-weight: 600;
color: #111827;
color: var(--ink);
line-height: 1.2;
}
.copy small {
font-size: 13px;
color: #94a3b8;
line-height: 1.5;
font-size: var(--fs-xs);
color: var(--muted);
line-height: 1.3;
}
.fab {
position: fixed;
z-index: 93;
width: 54px;
height: 54px;
box-sizing: border-box;
width: var(--control-h);
height: var(--control-h);
padding: 0;
margin: 0;
border: 0;
border-radius: 16px;
border-radius: var(--radius);
overflow: hidden;
background: linear-gradient(145deg, #0f766e 0%, #14b8a6 100%);
color: #fff;
display: grid;
@@ -416,7 +449,7 @@ onBeforeUnmount(() => {
line-height: 0;
direction: ltr;
box-shadow:
0 8px 22px rgba(13, 148, 136, 0.4),
0 4px 14px rgba(13, 148, 136, 0.35),
inset 0 1px 0 rgba(255, 255, 255, 0.22);
cursor: grab;
touch-action: none;
@@ -437,25 +470,28 @@ onBeforeUnmount(() => {
.fab :deep(.ico) {
display: block;
stroke-width: 1.55;
filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.15));
width: 20px;
height: 20px;
max-width: 20px;
max-height: 20px;
stroke-width: 1.7;
}
.fab:hover {
filter: brightness(1.06);
box-shadow:
0 10px 26px rgba(13, 148, 136, 0.48),
0 6px 18px rgba(13, 148, 136, 0.42),
inset 0 1px 0 rgba(255, 255, 255, 0.25);
}
.fab.open {
background: linear-gradient(145deg, #115e59 0%, #0d9488 100%);
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.28);
box-shadow: 0 6px 20px rgba(15, 23, 42, 0.25);
}
.fab.dragging {
cursor: grabbing;
transform: scale(1.05);
box-shadow: 0 12px 28px rgba(13, 148, 136, 0.5);
box-shadow: 0 8px 24px rgba(13, 148, 136, 0.45);
}
</style>
+29 -2
View File
@@ -57,7 +57,14 @@ defineProps<{
| 'apps-plus'
| 'crown'
| 'gift'
| 'medal';
| 'medal'
| 'logout'
| 'arrow-right'
| 'arrow-left'
| 'chevron-right'
| 'chevron-left'
| 'chevrons-right'
| 'chevrons-left';
size?: number;
}>();
</script>
@@ -211,9 +218,24 @@ defineProps<{
<template v-else-if="name === 'plus'">
<path d="M12 6v12M6 12h12" />
</template>
<template v-else-if="name === 'chevron'">
<template v-else-if="name === 'chevron' || name === 'chevron-right'">
<path d="m9 6 6 6-6 6" />
</template>
<template v-else-if="name === 'chevron-left'">
<path d="m15 18-6-6 6-6" />
</template>
<template v-else-if="name === 'chevrons-right'">
<path d="m6 17 5-5-5-5M13 17l5-5-5-5" />
</template>
<template v-else-if="name === 'chevrons-left'">
<path d="m11 17-5-5 5-5M18 17l-5-5 5-5" />
</template>
<template v-else-if="name === 'arrow-right'">
<path d="M5 12h14M12 5l7 7-7 7" />
</template>
<template v-else-if="name === 'arrow-left'">
<path d="M19 12H5M12 19l-7-7 7-7" />
</template>
<template v-else-if="name === 'star'">
<path d="m12 3.4 2.4 4.9 5.4.8-3.9 3.8.9 5.4L12 15.8 7.2 18.3l.9-5.4-3.9-3.8 5.4-.8L12 3.4Z" />
</template>
@@ -340,6 +362,11 @@ defineProps<{
<circle cx="12" cy="9" r="2.3" />
<path d="m9.1 13.6-1.4 6.2 4.3-2.3 4.3 2.3-1.4-6.2" />
</template>
<template v-else-if="name === 'logout'">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
<path d="M16 17l5-5-5-5" />
<path d="M21 12H9" />
</template>
</svg>
</template>
+1 -1
View File
@@ -52,7 +52,7 @@ img {
em {
font-style: normal;
color: #fff;
font-weight: 800;
font-weight: 600;
font-size: 0.62rem;
line-height: 1;
}
+10 -8
View File
@@ -318,8 +318,9 @@ onBeforeUnmount(() => {
border: 1px solid #d7e3dc;
background: #f4faf7;
color: #0f766e;
border-radius: 999px;
min-height: 36px;
border-radius: var(--radius);
min-height: var(--control-h);
height: var(--control-h);
padding: 0 0.75rem;
font: inherit;
font-size: 0.8rem;
@@ -335,13 +336,13 @@ onBeforeUnmount(() => {
border-color: #5eead4;
background: #042f2e;
color: #ecfdf5;
min-height: 44px;
min-height: var(--control-h);
padding-inline: 0.7rem 0.85rem;
box-shadow: 0 10px 24px rgba(15, 118, 110, 0.22);
}
.vtt.busy {
min-height: 44px;
min-height: var(--control-h);
border-color: #99f6e4;
background: #ecfdf5;
color: #0f766e;
@@ -372,7 +373,7 @@ onBeforeUnmount(() => {
.meter i {
display: block;
width: 3px;
border-radius: 99px;
border-radius: var(--radius);
background: #5eead4;
box-shadow: 0 0 8px rgba(94, 234, 212, 0.45);
transition: height 70ms linear;
@@ -401,7 +402,7 @@ onBeforeUnmount(() => {
height: 38px;
min-height: 38px;
padding: 0;
border-radius: 12px;
border-radius: var(--radius);
border-color: transparent;
background: #f8fafc;
justify-content: center;
@@ -411,9 +412,10 @@ onBeforeUnmount(() => {
.toolbar.wait .vtt {
width: auto;
height: auto;
min-height: 40px;
min-height: var(--control-h);
height: var(--control-h);
padding: 0 0.7rem;
border-radius: 999px;
border-radius: var(--radius);
}
.toolbar .vtt.on {
@@ -296,8 +296,8 @@ onBeforeUnmount(() => {
.head h2 {
margin: 0;
text-align: center;
font-size: 1.05rem;
font-weight: 800;
font-size: 16px;
font-weight: 500;
color: #0f172a;
}
@@ -332,7 +332,7 @@ onBeforeUnmount(() => {
align-items: flex-start;
padding: 0.9rem 0.95rem;
border: 1px solid #e2e8f0;
border-radius: 18px;
border-radius: var(--radius);
background: #fff;
}
@@ -370,7 +370,7 @@ onBeforeUnmount(() => {
.ctx-copy h3 {
margin: 0.1rem 0 0;
font-size: 0.98rem;
font-weight: 800;
font-weight: 600;
line-height: 1.55;
}
@@ -404,7 +404,7 @@ onBeforeUnmount(() => {
.editor {
border: 1px solid #e2e8f0;
border-radius: 16px;
border-radius: var(--radius);
background: #fff;
min-height: 11.5rem;
display: flex;
@@ -448,13 +448,13 @@ onBeforeUnmount(() => {
width: 36px;
height: 36px;
border: 1px solid #e2e8f0;
border-radius: 10px;
border-radius: var(--radius);
background: #fff;
color: #0f766e;
display: grid;
place-items: center;
font: inherit;
font-weight: 800;
font-weight: 600;
cursor: pointer;
}
@@ -473,7 +473,7 @@ onBeforeUnmount(() => {
font-size: 0.74rem;
font-weight: 700;
padding: 0.42rem 0.65rem;
border-radius: 10px;
border-radius: var(--radius);
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.18);
}
@@ -497,7 +497,7 @@ onBeforeUnmount(() => {
max-height: 12rem;
overflow: auto;
background: #fff;
border-radius: 12px;
border-radius: var(--radius);
box-shadow: 0 14px 36px rgba(15, 23, 42, 0.16);
z-index: 2;
}
@@ -510,7 +510,7 @@ onBeforeUnmount(() => {
text-align: start;
font: inherit;
padding: 0.55rem 0.65rem;
border-radius: 8px;
border-radius: var(--radius);
color: #0f172a;
cursor: pointer;
}
@@ -536,7 +536,7 @@ onBeforeUnmount(() => {
align-items: flex-start;
gap: 0.5rem;
padding: 0.72rem 0.8rem;
border-radius: 12px;
border-radius: var(--radius);
background: #ecfdf5;
color: #0f766e;
font-size: 0.8rem;
@@ -555,10 +555,11 @@ onBeforeUnmount(() => {
}
.act {
min-height: 48px;
border-radius: 14px;
min-height: var(--control-h);
height: var(--control-h);
border-radius: var(--radius);
font: inherit;
font-weight: 800;
font-weight: 600;
cursor: pointer;
}
@@ -599,7 +600,7 @@ onBeforeUnmount(() => {
position: relative;
max-width: 480px;
height: min(92dvh, 860px);
border-radius: 22px;
border-radius: var(--radius, 10px);
box-shadow: 0 28px 70px rgba(15, 23, 42, 0.22);
}
}
@@ -274,8 +274,8 @@ onBeforeUnmount(() => {
}
.titles h2 {
font-size: 1.02rem;
font-weight: 800;
font-size: 16px;
font-weight: 500;
color: #0f172a;
}
@@ -319,7 +319,7 @@ onBeforeUnmount(() => {
min-height: 72px;
padding: 0.7rem 0.9rem;
border: 1px solid #e8eef3;
border-radius: 16px;
border-radius: var(--radius);
background: #fff;
font: inherit;
text-align: start;
@@ -340,7 +340,7 @@ onBeforeUnmount(() => {
.label,
.copy strong {
font-size: 0.95rem;
font-weight: 800;
font-weight: 600;
color: #0f172a;
}
@@ -365,7 +365,7 @@ onBeforeUnmount(() => {
.ico-box {
width: 40px;
height: 40px;
border-radius: 10px;
border-radius: var(--radius);
background: #e6f7f4;
color: #0d9488;
display: grid;
@@ -375,13 +375,13 @@ onBeforeUnmount(() => {
.when {
color: #0d9488;
font-size: 0.74rem;
font-weight: 800;
font-weight: 600;
white-space: nowrap;
}
.custom-box {
border: 1px solid #e8eef3;
border-radius: 16px;
border-radius: var(--radius);
padding: 0.85rem 0.9rem;
display: grid;
gap: 0.55rem;
@@ -396,9 +396,10 @@ onBeforeUnmount(() => {
.picker input {
width: 100%;
min-height: 44px;
min-height: var(--control-h);
height: var(--control-h);
border: 1px solid #e2e8f0;
border-radius: 12px;
border-radius: var(--radius);
padding: 0.45rem 0.7rem;
font: inherit;
color: #0f172a;
@@ -418,7 +419,7 @@ onBeforeUnmount(() => {
align-items: flex-start;
gap: 0.55rem;
padding: 0.85rem 0.9rem;
border-radius: 14px;
border-radius: var(--radius);
background: #f8fafc;
color: #475569;
font-size: 0.8rem;
@@ -451,7 +452,7 @@ onBeforeUnmount(() => {
position: relative;
max-width: 480px;
height: min(92dvh, 860px);
border-radius: 22px;
border-radius: var(--radius, 10px);
box-shadow: 0 28px 70px rgba(15, 23, 42, 0.22);
}
}
@@ -79,7 +79,7 @@ withDefaults(
.brand-copy strong {
font-size: 1.2rem;
color: #0f172a;
font-weight: 800;
font-weight: 600;
}
.brand-copy span {
@@ -117,7 +117,7 @@ withDefaults(
aspect-ratio: 1.35;
background: rgba(255, 255, 255, 0.88);
border: 1px solid rgba(148, 163, 184, 0.35);
border-radius: 18px;
border-radius: var(--radius);
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.1);
padding: 1rem;
backdrop-filter: blur(6px);
@@ -150,7 +150,7 @@ withDefaults(
.chart-line {
height: 54px;
border-radius: 12px;
border-radius: var(--radius);
background:
linear-gradient(180deg, transparent 55%, rgba(13, 148, 136, 0.12) 55%),
radial-gradient(circle at 20% 60%, #14b8a6 3px, transparent 4px),
@@ -184,7 +184,7 @@ withDefaults(
position: absolute;
width: 42px;
height: 42px;
border-radius: 14px;
border-radius: var(--radius);
background: #fff;
box-shadow: 0 10px 24px rgba(15, 23, 42, 0.1);
}
@@ -0,0 +1,553 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import UiIcon from '@/components/UiIcon.vue';
import {
AUTOMATION_ACTION_LABELS,
AUTOMATION_ACTIONS,
AUTOMATION_CONDITION_FIELD_LABELS,
AUTOMATION_CONDITION_OP_LABELS,
AUTOMATION_NOTIFY_CHANNEL_LABELS,
AUTOMATION_TRIGGER_LABELS,
MAX_AUTOMATION_STEPS,
isAutomationCondition,
type AutomationAction,
type AutomationStep,
type AutomationTrigger,
} from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
export type AutomationAddPayload =
| { kind: 'action'; action: AutomationAction }
| { kind: 'condition' };
const props = defineProps<{
trigger: AutomationTrigger;
steps: AutomationStep[];
selected: 'trigger' | string;
}>();
const emit = defineEmits<{
select: [id: 'trigger' | string];
add: [payload: AutomationAddPayload, index: number];
remove: [id: string];
}>();
const addAt = ref<number | null>(null);
const canAdd = computed(() => props.steps.length < MAX_AUTOMATION_STEPS);
const actionCount = computed(
() => props.steps.filter((s) => !isAutomationCondition(s)).length,
);
type NodeIcon = 'sparkle' | 'flag' | 'bell' | 'gift' | 'filter';
function actionIcon(action: AutomationAction): NodeIcon {
if (action === 'create_notification') return 'bell';
if (action === 'add_loyalty_points') return 'gift';
return 'flag';
}
function canRemove(step: AutomationStep) {
if (props.steps.length <= 1) return false;
if (isAutomationCondition(step)) return true;
return actionCount.value > 1;
}
function stepTitle(step: AutomationStep) {
if (isAutomationCondition(step)) {
const field = step.conditionField ?? 'has_person';
return AUTOMATION_CONDITION_FIELD_LABELS[field];
}
return AUTOMATION_ACTION_LABELS[step.action ?? 'create_activity'];
}
function stepHint(step: AutomationStep) {
if (isAutomationCondition(step)) {
const op = step.conditionOp ?? 'is_set';
const opLabel = AUTOMATION_CONDITION_OP_LABELS[op];
if (step.conditionField === 'deal_amount' && step.conditionValue != null) {
return `${opLabel} ${toFaDigits(Number(step.conditionValue))}`;
}
if (step.conditionField === 'ticket_priority' && step.conditionValue) {
const pri: Record<string, string> = {
low: 'کم',
normal: 'عادی',
high: 'بالا',
urgent: 'فوری',
};
return `${opLabel} ${pri[String(step.conditionValue)] ?? step.conditionValue}`;
}
return opLabel;
}
if (step.action === 'add_loyalty_points') {
return `${toFaDigits(step.points ?? 100)} امتیاز`;
}
if (step.action === 'create_notification') {
return AUTOMATION_NOTIFY_CHANNEL_LABELS[step.notifyChannel ?? 'app'];
}
const types: Record<string, string> = {
call: 'تماس',
meeting: 'جلسه',
task: 'وظیفه',
note: 'یادداشت',
};
return types[step.activityType ?? 'task'] ?? 'وظیفه';
}
function openAdd(index: number) {
if (!canAdd.value) return;
addAt.value = addAt.value === index ? null : index;
}
function pickAction(action: AutomationAction) {
if (addAt.value == null) return;
emit('add', { kind: 'action', action }, addAt.value);
addAt.value = null;
}
function pickCondition() {
if (addAt.value == null) return;
emit('add', { kind: 'condition' }, addAt.value);
addAt.value = null;
}
function nodeClass(step: AutomationStep) {
if (isAutomationCondition(step)) return 'condition';
return step.action ?? 'create_activity';
}
</script>
<template>
<div class="canvas" @click.self="addAt = null">
<div class="flow">
<button
class="node trigger"
type="button"
:class="{ on: selected === 'trigger' }"
@click="emit('select', 'trigger')"
>
<span class="icon">
<UiIcon name="sparkle" :size="18" />
</span>
<span class="copy">
<span class="kind">اگر</span>
<strong>{{ AUTOMATION_TRIGGER_LABELS[trigger] }}</strong>
</span>
</button>
<template v-for="(step, i) in steps" :key="step.id">
<div class="wire" :class="{ open: addAt === i }">
<button
v-if="canAdd"
class="plus"
type="button"
title="افزودن گره"
@click.stop="openAdd(i)"
>
<UiIcon name="plus" :size="14" />
</button>
</div>
<div class="node-wrap">
<button
class="node action"
type="button"
:class="[nodeClass(step), { on: selected === step.id }]"
@click="emit('select', step.id)"
>
<span class="icon">
<UiIcon
:name="isAutomationCondition(step) ? 'filter' : actionIcon(step.action ?? 'create_activity')"
:size="18"
/>
</span>
<span class="copy">
<span class="kind">{{ isAutomationCondition(step) ? 'شرط' : 'آنگاه' }}</span>
<strong>{{ stepTitle(step) }}</strong>
<em>{{ stepHint(step) }}</em>
</span>
</button>
<button
v-if="canRemove(step)"
class="trash"
type="button"
title="حذف"
@click.stop="emit('remove', step.id)"
>
<UiIcon name="trash" :size="14" />
</button>
</div>
</template>
<div class="wire end" :class="{ open: addAt === steps.length }">
<button
v-if="canAdd"
class="plus big"
type="button"
title="افزودن گره بعدی"
@click.stop="openAdd(steps.length)"
>
<UiIcon name="plus" :size="16" />
</button>
</div>
</div>
<div v-if="addAt !== null" class="picker" @click.stop>
<p>گره بعدی را انتخاب کنید</p>
<div class="picks">
<button type="button" class="condition" @click="pickCondition">
<UiIcon name="filter" :size="16" />
شرط
</button>
<button
v-for="action in AUTOMATION_ACTIONS"
:key="action"
type="button"
:class="action"
@click="pickAction(action)"
>
<UiIcon :name="actionIcon(action)" :size="16" />
{{ AUTOMATION_ACTION_LABELS[action] }}
</button>
</div>
<button class="cancel" type="button" @click="addAt = null">انصراف</button>
</div>
<p v-if="!canAdd" class="cap">
حداکثر {{ toFaDigits(MAX_AUTOMATION_STEPS) }} گره در یک قانون
</p>
</div>
</template>
<style scoped>
.canvas {
position: relative;
width: 100%;
min-width: 0;
min-height: 22rem;
border-radius: var(--radius);
overflow: auto;
background-color: #f3f6f5;
background-image: radial-gradient(#c9d4cf 1.1px, transparent 1.2px);
background-size: 16px 16px;
padding: 1.6rem 1.1rem 1.25rem;
}
.flow {
display: flex;
flex-direction: row;
align-items: center;
gap: 0;
min-width: max-content;
min-height: 16rem;
}
.node-wrap {
position: relative;
display: flex;
align-items: center;
}
.node {
width: 13.6rem;
display: flex;
align-items: center;
gap: 0.7rem;
text-align: start;
padding: 0.72rem 0.8rem;
border-radius: var(--radius);
border: 1px solid #d5ddd8;
background: #fff;
box-shadow: 0 10px 24px rgba(23, 33, 28, 0.06);
cursor: pointer;
color: inherit;
font: inherit;
}
.node.trigger {
width: 14.2rem;
min-height: 4.35rem;
border-radius: 999px;
padding-inline: 1rem;
background: #fff7ed;
border-color: #fdba74;
}
.node.action:not(.condition) {
border-radius: var(--radius);
border-inline-start-width: 5px;
}
.node.create_activity {
border-inline-start-color: #14b8a6;
}
.node.create_notification {
border-inline-start-color: #2563eb;
}
.node.add_loyalty_points {
border-inline-start-color: #7c3aed;
}
.node.condition {
width: 15.1rem;
min-height: 4.6rem;
padding-inline: 1.15rem;
border: 0;
border-radius: 0;
background: #fffbeb;
box-shadow: none;
clip-path: polygon(12% 0%, 88% 0%, 100% 50%, 88% 100%, 12% 100%, 0% 50%);
filter: drop-shadow(0 8px 14px rgba(180, 83, 9, 0.14));
}
.node.on {
border-color: #14b8a6;
box-shadow:
0 0 0 3px rgba(20, 184, 166, 0.18),
0 12px 24px rgba(15, 23, 42, 0.08);
}
.node.trigger.on {
border-color: #ea580c;
box-shadow:
0 0 0 3px rgba(234, 88, 12, 0.2),
0 12px 24px rgba(15, 23, 42, 0.08);
}
.node.condition.on {
box-shadow: none;
filter:
drop-shadow(0 0 0 3px rgba(217, 119, 6, 0.35))
drop-shadow(0 8px 14px rgba(180, 83, 9, 0.14));
}
.icon {
width: 2.35rem;
height: 2.35rem;
border-radius: var(--radius);
display: grid;
place-items: center;
flex-shrink: 0;
color: #0f766e;
background: #ecfdf8;
}
.node.trigger .icon {
border-radius: 999px;
color: #c2410c;
background: #ffedd5;
}
.node.create_notification .icon {
color: #1d4ed8;
background: #eff6ff;
}
.node.add_loyalty_points .icon {
color: #7c3aed;
background: #f5f3ff;
}
.node.condition .icon {
border-radius: var(--radius);
color: #b45309;
background: #ffedd5;
}
.copy {
display: grid;
gap: 0.08rem;
min-width: 0;
}
.kind {
font-size: 0.7rem;
font-weight: 700;
color: #94a3b8;
}
strong {
font-size: 0.88rem;
font-weight: 600;
color: #0f172a;
}
em {
font-style: normal;
font-size: 0.72rem;
color: #64748b;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.trash {
position: absolute;
top: -0.45rem;
inset-inline-end: -0.45rem;
width: 1.55rem;
height: 1.55rem;
border-radius: 999px;
border: 1px solid #fecaca;
background: #fff;
color: #b91c1c;
display: grid;
place-items: center;
cursor: pointer;
opacity: 0;
pointer-events: none;
}
.node-wrap:hover .trash,
.node-wrap:focus-within .trash,
.node.on ~ .trash {
opacity: 1;
pointer-events: auto;
}
.wire {
position: relative;
width: 3.4rem;
height: 2px;
background: #cbd5e1;
flex-shrink: 0;
}
.wire::after {
content: '';
position: absolute;
inset-inline-end: -1px;
top: 50%;
transform: translateY(-50%);
border-block: 5px solid transparent;
border-inline-start: 7px solid #cbd5e1;
border-inline-end: 0;
}
.plus {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 1.45rem;
height: 1.45rem;
border-radius: 999px;
border: 1px solid #99f6e4;
background: #fff;
color: #0f766e;
display: grid;
place-items: center;
cursor: pointer;
z-index: 1;
box-shadow: 0 4px 10px rgba(15, 23, 42, 0.08);
}
.plus.big {
width: 2rem;
height: 2rem;
}
.wire.open .plus,
.plus:hover {
background: #14b8a6;
color: #fff;
border-color: #14b8a6;
}
.wire.end {
width: 3.8rem;
background: repeating-linear-gradient(
90deg,
#cbd5e1 0 6px,
transparent 6px 10px
);
}
.wire.end::after {
display: none;
}
.picker {
margin-top: 1rem;
background: #fff;
border: 1px solid #d5ddd8;
border-radius: var(--radius);
padding: 0.85rem;
display: grid;
gap: 0.65rem;
max-width: 40rem;
box-shadow: 0 16px 32px rgba(15, 23, 42, 0.08);
}
.picker p {
margin: 0;
font-size: 0.82rem;
font-weight: 700;
color: #334155;
}
.picks {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.picks button {
display: inline-flex;
align-items: center;
gap: 0.4rem;
border: 1px solid #e2e8f0;
background: #fff;
border-radius: 999px;
padding: 0.45rem 0.75rem;
font: inherit;
font-weight: 700;
font-size: 0.8rem;
cursor: pointer;
color: #0f172a;
}
.picks .create_activity {
color: #0f766e;
}
.picks .create_notification {
color: #1d4ed8;
}
.picks .add_loyalty_points {
color: #7c3aed;
}
.picks .condition {
color: #b45309;
}
.cancel {
justify-self: start;
border: 0;
background: none;
color: #64748b;
cursor: pointer;
font: inherit;
font-size: 0.8rem;
}
.cap {
margin: 0.85rem 0 0;
color: #94a3b8;
font-size: 0.78rem;
}
@media (max-width: 700px) {
.node {
width: 12.4rem;
}
.node.trigger {
width: 13rem;
}
.node.condition {
width: 14rem;
}
}
</style>
@@ -0,0 +1,344 @@
<script setup lang="ts">
import { computed, watch } from 'vue';
import type {
ActivityType,
AutomationAction,
AutomationConditionField,
AutomationConditionOp,
AutomationStep,
AutomationTrigger,
OrgUserDto,
TicketPriority,
} from '@mento/shared';
import {
AUTOMATION_ACTION_LABELS,
AUTOMATION_ACTIONS,
AUTOMATION_CONDITION_FIELD_LABELS,
AUTOMATION_CONDITION_OP_LABELS,
AUTOMATION_NOTIFY_CHANNEL_LABELS,
AUTOMATION_NOTIFY_CHANNELS,
AUTOMATION_TRIGGER_GROUPS,
AUTOMATION_TRIGGER_LABELS,
conditionFieldsForTrigger,
isAutomationCondition,
} from '@mento/shared';
const props = defineProps<{
selected: 'trigger' | string;
users: OrgUserDto[];
}>();
const trigger = defineModel<AutomationTrigger>('trigger', { required: true });
const steps = defineModel<AutomationStep[]>('steps', { required: true });
const selectedStep = computed(() => {
if (props.selected === 'trigger') return null;
return steps.value.find((s) => s.id === props.selected) ?? null;
});
const isCondition = computed(
() => !!selectedStep.value && isAutomationCondition(selectedStep.value),
);
const conditionFields = computed(() => conditionFieldsForTrigger(trigger.value));
const conditionOps = computed((): AutomationConditionOp[] => {
const field = selectedStep.value?.conditionField;
if (field === 'deal_amount') return ['gte', 'lte', 'eq', 'neq'];
if (field === 'ticket_priority') return ['eq', 'neq'];
return ['is_set', 'is_empty'];
});
const activityTypes: Array<{ value: ActivityType; label: string }> = [
{ value: 'task', label: 'وظیفه' },
{ value: 'call', label: 'تماس' },
{ value: 'meeting', label: 'جلسه' },
{ value: 'note', label: 'یادداشت' },
];
const ticketPriorities: Array<{ value: TicketPriority; label: string }> = [
{ value: 'low', label: 'کم' },
{ value: 'normal', label: 'عادی' },
{ value: 'high', label: 'بالا' },
{ value: 'urgent', label: 'فوری' },
];
function setAction(step: AutomationStep, action: AutomationAction) {
step.kind = 'action';
step.action = action;
if (action === 'add_loyalty_points' && !step.points) step.points = 100;
if (action === 'create_activity' && !step.activityType) step.activityType = 'task';
if (action === 'create_notification' && !step.notifyChannel) step.notifyChannel = 'app';
}
function setConditionField(step: AutomationStep, field: AutomationConditionField) {
step.conditionField = field;
if (field === 'deal_amount') {
step.conditionOp = 'gte';
step.conditionValue = typeof step.conditionValue === 'number' ? step.conditionValue : 0;
} else if (field === 'ticket_priority') {
step.conditionOp = 'eq';
step.conditionValue = 'normal';
} else {
step.conditionOp = 'is_set';
step.conditionValue = undefined;
}
}
watch(
selectedStep,
(step) => {
if (!step || isAutomationCondition(step) || step.action !== 'create_notification') return;
if (!step.notifyChannel) step.notifyChannel = 'app';
if (!step.notifyTarget) step.notifyTarget = 'staff';
},
{ immediate: true },
);
</script>
<template>
<aside class="inspector">
<template v-if="selected === 'trigger'">
<h2>گره محرک</h2>
<p class="hint">وقتی این اتفاق بیفتد، زنجیره از راست به چپ اجرا می‌شود.</p>
<label>
اگر
<select v-model="trigger">
<optgroup
v-for="group in AUTOMATION_TRIGGER_GROUPS"
:key="group.label"
:label="group.label"
>
<option v-for="t in group.items" :key="t" :value="t">
{{ AUTOMATION_TRIGGER_LABELS[t] }}
</option>
</optgroup>
</select>
</label>
</template>
<template v-else-if="selectedStep && isCondition">
<h2>گره شرط</h2>
<p class="hint">
اگر شرط برقرار نباشد، عمل‌های بعد از این گره اجرا نمی‌شوند.
</p>
<label>
فیلد
<select
:value="selectedStep.conditionField"
@change="
setConditionField(
selectedStep,
($event.target as HTMLSelectElement).value as AutomationConditionField,
)
"
>
<option v-for="f in conditionFields" :key="f" :value="f">
{{ AUTOMATION_CONDITION_FIELD_LABELS[f] }}
</option>
</select>
</label>
<label>
مقایسه
<select v-model="selectedStep.conditionOp">
<option v-for="op in conditionOps" :key="op" :value="op">
{{ AUTOMATION_CONDITION_OP_LABELS[op] }}
</option>
</select>
</label>
<label v-if="selectedStep.conditionField === 'deal_amount'">
مبلغ
<input v-model.number="selectedStep.conditionValue" type="number" min="0" />
</label>
<label v-if="selectedStep.conditionField === 'ticket_priority'">
اولویت
<select v-model="selectedStep.conditionValue">
<option v-for="p in ticketPriorities" :key="p.value" :value="p.value">
{{ p.label }}
</option>
</select>
</label>
</template>
<template v-else-if="selectedStep">
<h2>گره عمل</h2>
<p class="hint">بعد از محرک (و شرط‌ها)، این کار به ترتیب انجام می‌شود.</p>
<label>
آنگاه
<select
:value="selectedStep.action"
@change="
setAction(
selectedStep,
($event.target as HTMLSelectElement).value as AutomationAction,
)
"
>
<option v-for="a in AUTOMATION_ACTIONS" :key="a" :value="a">
{{ AUTOMATION_ACTION_LABELS[a] }}
</option>
</select>
</label>
<label>
عنوان
<input
v-model="selectedStep.title"
type="text"
maxlength="200"
placeholder="اختیاری"
/>
</label>
<label>
توضیح / متن پیام
<textarea
v-model="selectedStep.body"
rows="3"
maxlength="1000"
placeholder="اختیاری"
/>
</label>
<label v-if="selectedStep.action === 'create_activity'">
نوع فعالیت
<select v-model="selectedStep.activityType">
<option v-for="t in activityTypes" :key="t.value" :value="t.value">
{{ t.label }}
</option>
</select>
</label>
<label v-if="selectedStep.action === 'create_activity'">
مسئول فعالیت
<select v-model="selectedStep.assigneeId">
<option :value="null">مسئول معامله / تیکت</option>
<option v-for="u in users" :key="u.id" :value="u.id">
{{ u.fullName }}
</option>
</select>
</label>
<template v-if="selectedStep.action === 'create_notification'">
<p class="field-label">نحوه ارسال</p>
<div class="channels">
<label
v-for="ch in AUTOMATION_NOTIFY_CHANNELS"
:key="ch"
class="ch"
>
<input
v-model="selectedStep.notifyChannel"
type="radio"
:value="ch"
/>
{{ AUTOMATION_NOTIFY_CHANNEL_LABELS[ch] }}
</label>
</div>
<label>
گیرنده
<select v-model="selectedStep.notifyTarget">
<option value="staff">کاربر تیم</option>
<option value="person">مخاطب معامله / تیکت</option>
</select>
</label>
<label v-if="selectedStep.notifyTarget !== 'person'">
کاربر
<select v-model="selectedStep.notifyUserId">
<option :value="null">مسئول معامله / تیکت</option>
<option v-for="u in users" :key="u.id" :value="u.id">
{{ u.fullName }}
</option>
</select>
</label>
<p v-if="selectedStep.notifyTarget === 'person'" class="hint">
پیامک به موبایل مخاطب ارسال می‌شود. ناتیفیکیشن داخلی برای مخاطب نیست.
</p>
<p
v-else-if="selectedStep.notifyChannel === 'sms' || selectedStep.notifyChannel === 'both'"
class="hint"
>
پیامک به موبایل همان کاربر ارسال می‌شود.
</p>
</template>
<label v-if="selectedStep.action === 'add_loyalty_points'">
امتیاز
<input v-model.number="selectedStep.points" type="number" min="1" />
</label>
</template>
<p v-else class="hint">یک گره را از بوم انتخاب کنید.</p>
</aside>
</template>
<style scoped>
.inspector {
display: grid;
align-content: start;
gap: 0.75rem;
padding: 1rem;
background: #fff;
border: 1px solid #e2e8f0;
border-radius: var(--radius);
min-width: 0;
}
h2 {
margin: 0;
font-size: 0.98rem;
font-weight: 600;
}
.hint {
margin: 0;
color: #64748b;
font-size: 0.82rem;
line-height: 1.6;
}
label,
.field-label {
display: grid;
gap: 0.35rem;
font-size: 0.84rem;
color: #64748b;
}
.field-label {
margin: 0;
font-weight: 700;
}
input,
select,
textarea {
border: 1px solid #e2e8f0;
border-radius: var(--radius);
padding: 0.55rem 0.7rem;
font: inherit;
color: #0f172a;
background: #fff;
}
.channels {
display: flex;
flex-wrap: wrap;
gap: 0.55rem 0.85rem;
}
.ch {
display: inline-flex !important;
flex-direction: row;
align-items: center;
gap: 0.32rem;
color: #334155;
cursor: pointer;
white-space: nowrap;
}
.ch input {
accent-color: #14b8a6;
width: 14px;
height: 14px;
margin: 0;
}
</style>
@@ -64,7 +64,7 @@ withDefaults(
width: max-content;
max-width: 118px;
padding: 0.48rem 0.65rem 0.55rem;
border-radius: 14px;
border-radius: var(--radius);
background: #fff;
color: #0f172a;
font-size: 0.68rem;
+1 -1
View File
@@ -56,7 +56,7 @@ withDefaults(
letter-spacing: -0.02em;
color: #0f172a;
line-height: 1.1;
font-weight: 800;
font-weight: 600;
}
.text small {
@@ -93,7 +93,7 @@ function pick(label: string) {
<style scoped>
.panel {
background: #fff;
border-radius: 20px;
border-radius: var(--radius);
padding: 1rem 1rem 0.95rem;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
border: 1px solid #eef2f7;
@@ -144,7 +144,7 @@ h2 {
align-items: center;
gap: 0.55rem;
padding: 0.58rem 0.7rem;
border-radius: 12px;
border-radius: var(--radius);
background: #fff;
border: 1px solid #eef2f7;
color: #334155;
@@ -168,7 +168,7 @@ h2 {
.chip-ico {
width: 26px;
height: 26px;
border-radius: 8px;
border-radius: var(--radius);
background: #ecfdf8;
color: #14b8a6;
display: grid;
@@ -185,7 +185,7 @@ h2 {
.ai-input input {
flex: 1;
border: 1px solid #e2e8f0;
border-radius: 12px;
border-radius: var(--radius);
padding: 0.58rem 0.75rem;
background: #f8fafc;
font-size: 0.8rem;
@@ -194,7 +194,7 @@ h2 {
.ai-input button {
width: 40px;
border: 0;
border-radius: 12px;
border-radius: var(--radius);
background: #14b8a6;
color: #fff;
cursor: pointer;
@@ -208,7 +208,7 @@ h2 {
.ai-answer {
background: #f0fdfa;
border-radius: 12px;
border-radius: var(--radius);
padding: 0.7rem 0.8rem;
margin-bottom: 0.75rem;
}
@@ -137,7 +137,7 @@ function alertIcon(tone: string) {
align-items: start;
min-height: 0;
padding: 0.8rem 1.5rem 0.9rem;
border-radius: 28px;
border-radius: var(--radius);
overflow: visible;
color: #fff;
background: transparent;
@@ -148,7 +148,7 @@ function alertIcon(tone: string) {
position: absolute;
inset: 0;
z-index: 0;
border-radius: 28px;
border-radius: var(--radius);
overflow: hidden;
background-color: #134e4a;
background-image:
@@ -248,7 +248,7 @@ function alertIcon(tone: string) {
.greet-text h1 {
margin: 0;
font-size: clamp(1.35rem, 2vw, 1.75rem);
font-weight: 800;
font-weight: 600;
letter-spacing: -0.01em;
color: #fff;
}
@@ -273,7 +273,7 @@ function alertIcon(tone: string) {
gap: 0.4rem;
min-width: 0;
padding: 0.4rem 0.5rem;
border-radius: 12px;
border-radius: var(--radius);
background: #fff;
color: #0f172a;
text-decoration: none;
@@ -308,7 +308,7 @@ function alertIcon(tone: string) {
.chip-ico {
width: 22px;
height: 22px;
border-radius: 8px;
border-radius: var(--radius);
display: grid;
place-items: center;
flex-shrink: 0;
@@ -366,7 +366,7 @@ function alertIcon(tone: string) {
color: #94a3b8;
background: #f1f5f9;
border: 1px solid #e2e8f0;
border-radius: 7px;
border-radius: var(--radius);
padding: 0.14rem 0.38rem;
flex-shrink: 0;
}
@@ -58,7 +58,7 @@ const iconTones: Record<string, string> = {
gap: 0.85rem;
align-items: flex-start;
background: #fff;
border-radius: 22px;
border-radius: var(--radius);
padding: 1.1rem 1.15rem;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
border: 1px solid #eef2f7;
@@ -67,7 +67,7 @@ const iconTones: Record<string, string> = {
.kpi-icon {
width: 48px;
height: 48px;
border-radius: 16px;
border-radius: var(--radius);
background: #f8fafc;
display: grid;
place-items: center;
@@ -101,7 +101,7 @@ const cols = computed<Col[]>(() => {
<style scoped>
.panel {
background: #fff;
border-radius: 20px;
border-radius: var(--radius);
padding: 1rem 1.05rem;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
border: 1px solid #eef2f7;
@@ -151,7 +151,7 @@ a {
align-items: center;
gap: 0.5rem;
padding: 0.55rem 0.6rem;
border-radius: 12px;
border-radius: var(--radius);
background: #f8fafc;
border: 1px solid #eef2f7;
color: inherit;
@@ -185,12 +185,12 @@ a {
.deal-mark {
width: 28px;
height: 28px;
border-radius: 8px;
border-radius: var(--radius);
background: #ecfdf8;
color: #0f766e;
display: grid;
place-items: center;
font-weight: 800;
font-weight: 600;
flex-shrink: 0;
}
@@ -108,7 +108,7 @@ const rows = computed<Row[]>(() => {
<style scoped>
.panel {
background: #fff;
border-radius: 20px;
border-radius: var(--radius);
padding: 1rem 1.05rem;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
border: 1px solid #eef2f7;
@@ -151,7 +151,7 @@ a {
.act-icon {
width: 38px;
height: 38px;
border-radius: 12px;
border-radius: var(--radius);
background: #ecfdf8;
color: #14b8a6;
display: grid;
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue';
import type { HomeDashboardTrendPointDto } from '@mento/shared';
import UiChart, { type UiChartOption } from '@/components/ui/UiChart.vue';
const props = defineProps<{
trend: HomeDashboardTrendPointDto[];
@@ -20,33 +21,61 @@ const demoTrend: HomeDashboardTrendPointDto[] = [
const trend = computed(() => (props.trend.length ? props.trend : demoTrend));
const change = computed(() => props.changePercent ?? 14);
const points = computed(() => {
const rows = trend.value;
const max = Math.max(...rows.map((p) => p.amount), 1);
const w = 360;
const h = 150;
const padX = 16;
const padY = 36;
return rows.map((p, i) => ({
...p,
x: padX + (i / Math.max(rows.length - 1, 1)) * (w - padX * 2),
y: h - padY - (p.amount / max) * (h - padY * 2),
}));
});
const line = computed(() => points.value.map((p) => `${p.x},${p.y}`).join(' '));
const area = computed(() => {
if (!points.value.length) return '';
const first = points.value[0]!;
const last = points.value[points.value.length - 1]!;
return `${line.value} ${last.x},160 ${first.x},160`;
});
const highlight = computed(() => {
if (!points.value.length) return null;
return points.value.reduce((best, cur) => (cur.amount >= best.amount ? cur : best));
});
const option = computed<UiChartOption>(() => ({
animationDuration: 400,
grid: { top: 28, right: 8, bottom: 28, left: 8, containLabel: true },
tooltip: {
trigger: 'axis',
textStyle: { fontFamily: 'IRANSans, Tahoma, sans-serif' },
formatter: (params) => {
const row = Array.isArray(params) ? params[0] : params;
const point = trend.value[row.dataIndex ?? 0];
if (!point) return '';
return `${point.monthLabel}<br/>${props.formatAmount(point.amount)}`;
},
},
xAxis: {
type: 'category',
data: trend.value.map((p) => p.monthLabel),
boundaryGap: false,
axisLine: { show: false },
axisTick: { show: false },
axisLabel: {
color: '#94a3b8',
fontFamily: 'IRANSans, Tahoma, sans-serif',
fontSize: 11,
},
},
yAxis: {
type: 'value',
splitLine: { lineStyle: { color: '#eef2f7' } },
axisLabel: { show: false },
},
series: [
{
type: 'line',
data: trend.value.map((p) => p.amount),
smooth: 0.35,
symbol: 'circle',
symbolSize: 8,
itemStyle: { color: '#14b8a6', borderColor: '#fff', borderWidth: 2 },
lineStyle: { color: '#14b8a6', width: 3 },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(20, 184, 166, 0.28)' },
{ offset: 1, color: 'rgba(20, 184, 166, 0)' },
],
},
},
},
],
}));
</script>
<template>
@@ -57,73 +86,17 @@ const highlight = computed(() => {
{{ formatChange(change) }} نسبت به ماه قبل
</span>
</header>
<div class="chart-wrap">
<svg viewBox="0 0 360 170" class="line-chart" aria-hidden="true">
<defs>
<linearGradient id="homeTrendFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stop-color="#14b8a6" stop-opacity="0.28" />
<stop offset="100%" stop-color="#14b8a6" stop-opacity="0" />
</linearGradient>
</defs>
<line
v-for="y in [40, 75, 110, 145]"
:key="y"
x1="12"
:y1="y"
x2="348"
:y2="y"
stroke="#eef2f7"
stroke-width="1"
/>
<polygon v-if="area" :points="area" fill="url(#homeTrendFill)" />
<polyline
v-if="line"
:points="line"
fill="none"
stroke="#14b8a6"
stroke-width="3.2"
stroke-linecap="round"
stroke-linejoin="round"
/>
<g v-for="(p, i) in points" :key="i">
<circle :cx="p.x" :cy="p.y" r="4.5" fill="#fff" stroke="#14b8a6" stroke-width="2.4" />
</g>
<g v-if="highlight">
<rect
:x="Math.min(Math.max(highlight.x - 52, 4), 256)"
:y="highlight.y - 32"
width="104"
height="24"
rx="8"
fill="#0f766e"
/>
<text
:x="Math.min(Math.max(highlight.x, 56), 308)"
:y="highlight.y - 16"
text-anchor="middle"
fill="#fff"
font-size="9.5"
font-family="IRANSans, Tahoma, sans-serif"
>
{{ formatAmount(highlight.amount) }}
</text>
</g>
</svg>
<div class="chart-labels">
<span v-for="p in trend" :key="p.monthKey">{{ p.monthLabel }}</span>
</div>
</div>
<UiChart :option="option" height="210px" />
</article>
</template>
<style scoped>
.panel {
background: #fff;
border-radius: 20px;
padding: 1rem 1.1rem 0.9rem;
border-radius: var(--radius);
padding: var(--pad-modal);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
border: 1px solid #eef2f7;
border: 1px solid var(--line);
min-width: 0;
height: 100%;
display: flex;
@@ -135,7 +108,7 @@ const highlight = computed(() => {
align-items: center;
justify-content: space-between;
gap: 0.75rem;
margin-bottom: 0;
margin-bottom: 0.35rem;
}
h2 {
@@ -149,7 +122,7 @@ h2 {
font-weight: 700;
color: #16a34a;
background: #dcfce7;
border-radius: 999px;
border-radius: var(--radius);
padding: 0.18rem 0.5rem;
white-space: nowrap;
}
@@ -158,24 +131,4 @@ h2 {
color: #dc2626;
background: #fee2e2;
}
.chart-wrap {
display: grid;
gap: 0.15rem;
margin-top: auto;
padding-top: 2.25rem;
}
.line-chart {
width: 100%;
height: auto;
}
.chart-labels {
display: flex;
justify-content: space-between;
color: #94a3b8;
font-size: 0.72rem;
padding: 0 0.35rem;
}
</style>
@@ -2,6 +2,7 @@
import { computed } from 'vue';
import { toFaDigits } from '@/lib/jalali';
import type { HomeDashboardSourceDto } from '@mento/shared';
import UiChart, { type UiChartOption } from '@/components/ui/UiChart.vue';
const props = defineProps<{
sources: HomeDashboardSourceDto[];
@@ -18,17 +19,31 @@ const demoSources: HomeDashboardSourceDto[] = [
const colors = ['#2563eb', '#14b8a6', '#22c55e', '#fb923c', '#94a3b8'];
const rows = computed(() => (props.sources.length ? props.sources : demoSources));
const segments = computed(() => {
let offset = 0;
return rows.value.map((s, i) => {
const seg = { ...s, color: colors[i % colors.length], offset };
offset += s.percent;
return seg;
});
});
const total = computed(() => rows.value.reduce((a, s) => a + s.count, 0));
const option = computed<UiChartOption>(() => ({
animationDuration: 400,
color: colors,
tooltip: {
trigger: 'item',
textStyle: { fontFamily: 'IRANSans, Tahoma, sans-serif' },
formatter: (p) => {
const item = Array.isArray(p) ? p[0] : p;
return `${item.name}<br/>${toFaDigits(Number(item.value ?? 0))} — ${toFaDigits(item.percent ?? 0)}٪`;
},
},
series: [
{
type: 'pie',
radius: ['58%', '82%'],
center: ['50%', '50%'],
avoidLabelOverlap: true,
label: { show: false },
labelLine: { show: false },
data: rows.value.map((s) => ({ name: s.label, value: s.count })),
},
],
}));
</script>
<template>
@@ -39,23 +54,7 @@ const total = computed(() => rows.value.reduce((a, s) => a + s.count, 0));
<div class="donut-wrap">
<div class="donut-chart-box">
<svg viewBox="0 0 140 140" class="donut-chart" aria-hidden="true">
<circle cx="70" cy="70" r="48" fill="none" stroke="#eef2f7" stroke-width="16" />
<circle
v-for="seg in segments"
:key="seg.label"
cx="70"
cy="70"
r="48"
fill="none"
:stroke="seg.color"
stroke-width="16"
stroke-linecap="butt"
:stroke-dasharray="`${seg.percent * 3.016} 301.6`"
:stroke-dashoffset="`${-seg.offset * 3.016}`"
transform="rotate(-90 70 70)"
/>
</svg>
<UiChart :option="option" height="132px" />
<div class="donut-center">
<strong>{{ toFaDigits(total) }}</strong>
<span>مشتری</span>
@@ -63,10 +62,10 @@ const total = computed(() => rows.value.reduce((a, s) => a + s.count, 0));
</div>
<ul class="donut-legend">
<li v-for="seg in segments" :key="seg.label">
<span class="dot" :style="{ background: seg.color }" />
<span class="lbl">{{ seg.label }}</span>
<em>{{ toFaDigits(seg.percent) }}٪</em>
<li v-for="(row, i) in rows" :key="row.label">
<span class="dot" :style="{ background: colors[i % colors.length] }" />
<span class="lbl">{{ row.label }}</span>
<em>{{ toFaDigits(row.percent) }}٪</em>
</li>
</ul>
</div>
@@ -76,10 +75,10 @@ const total = computed(() => rows.value.reduce((a, s) => a + s.count, 0));
<style scoped>
.panel {
background: #fff;
border-radius: 20px;
padding: 1rem 1.1rem;
border-radius: var(--radius);
padding: var(--pad-modal);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
border: 1px solid #eef2f7;
border: 1px solid var(--line);
min-width: 0;
}
@@ -106,11 +105,6 @@ h2 {
height: 132px;
}
.donut-chart {
width: 132px;
height: 132px;
}
.donut-center {
position: absolute;
inset: 0;
@@ -47,7 +47,7 @@ function trophy(rank: number) {
<style scoped>
.panel {
background: #fff;
border-radius: 20px;
border-radius: var(--radius);
padding: 1rem 1.05rem;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
border: 1px solid #eef2f7;
@@ -89,12 +89,12 @@ a {
.cust-avatar {
width: 38px;
height: 38px;
border-radius: 12px;
border-radius: var(--radius);
background: linear-gradient(145deg, #ccfbf1, #99f6e4);
color: #0f766e;
display: grid;
place-items: center;
font-weight: 800;
font-weight: 600;
flex-shrink: 0;
}
@@ -0,0 +1,173 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import { formatMoney } from '@/lib/money';
import { useAuthStore } from '@/stores/auth';
import { canManageSettings } from '@/lib/roles';
import UiButton from '@/components/ui/UiButton.vue';
import UiInput from '@/components/ui/UiInput.vue';
import type { PartyBalanceDto } from '@mento/shared';
const props = defineProps<{
personId: string;
}>();
const auth = useAuthStore();
const canWrite = computed(() => canManageSettings(auth.user?.role));
const loading = ref(false);
const error = ref('');
const data = ref<PartyBalanceDto | null>(null);
const opening = ref('');
const saving = ref(false);
async function load() {
loading.value = true;
error.value = '';
try {
const { data: row } = await api.get<PartyBalanceDto>(
`/inventory/party/${props.personId}`,
);
data.value = row;
opening.value = String(row.openingAmount);
} catch {
error.value = 'بارگذاری مانده ناموفق بود.';
} finally {
loading.value = false;
}
}
async function saveOpening() {
if (!canWrite.value || saving.value) return;
const amount = Number(opening.value);
if (!Number.isFinite(amount)) return;
saving.value = true;
error.value = '';
try {
const { data: row } = await api.patch<PartyBalanceDto>(
`/inventory/party/${props.personId}/opening`,
{ amount },
);
data.value = row;
} catch (e) {
const msg = axios.isAxiosError(e)
? (e.response?.data as { message?: string })?.message
: null;
error.value = typeof msg === 'string' ? msg : 'ذخیره مانده اول دوره ناموفق بود.';
} finally {
saving.value = false;
}
}
watch(
() => props.personId,
() => {
void load();
},
);
onMounted(load);
</script>
<template>
<article v-if="data?.enabled" class="box">
<header>
<h3>مانده حساب داخلی</h3>
<p>از فاکتور و پرداخت‌های منتکت — وقتی ته‌حساب وصل نیست</p>
</header>
<p v-if="error" class="error">{{ error }}</p>
<p v-else-if="loading" class="muted">در حال بارگذاری…</p>
<template v-else>
<dl>
<div>
<dt>اول دوره</dt>
<dd>{{ formatMoney(data.openingAmount, data.currency) }}</dd>
</div>
<div>
<dt>فاکتورها</dt>
<dd>{{ formatMoney(data.invoicedAmount, data.currency) }}</dd>
</div>
<div>
<dt>پرداخت‌ها</dt>
<dd>{{ formatMoney(data.paidAmount, data.currency) }}</dd>
</div>
<div class="total">
<dt>مانده</dt>
<dd>{{ formatMoney(data.balance, data.currency) }}</dd>
</div>
</dl>
<form v-if="canWrite" class="open-form" @submit.prevent="saveOpening">
<label>
مانده اول دوره
<UiInput v-model="opening" type="number" />
</label>
<UiButton type="submit" :disabled="saving">
{{ saving ? 'ذخیره…' : 'ثبت' }}
</UiButton>
</form>
</template>
</article>
</template>
<style scoped>
.box {
background: #fff;
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 1rem 1.1rem;
margin-bottom: 0.85rem;
}
h3 {
margin: 0;
font-size: 0.95rem;
}
header p,
.muted {
margin: 0.25rem 0 0;
color: var(--muted);
font-size: 0.8rem;
}
.error {
color: var(--danger, #dc2626);
font-weight: 600;
}
dl {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.65rem;
margin: 0.85rem 0 0;
}
dt {
color: var(--muted);
font-size: 0.78rem;
}
dd {
margin: 0.15rem 0 0;
font-weight: 700;
}
.total dd {
color: var(--accent-deep, #0f766e);
}
.open-form {
display: flex;
align-items: end;
gap: 0.5rem;
margin-top: 0.85rem;
}
.open-form label {
display: grid;
gap: 0.3rem;
font-size: 0.8rem;
color: var(--muted);
flex: 1;
}
</style>
@@ -775,7 +775,7 @@ onMounted(async () => {
gap: 0.28rem;
min-width: 0;
padding: 0.8rem 0.9rem;
border-radius: 12px;
border-radius: var(--radius);
border: 1px solid #e2e8f0;
background: #f8fafc;
}
@@ -789,7 +789,7 @@ onMounted(async () => {
align-items: baseline;
gap: 0.3rem;
font-size: 1.15rem;
font-weight: 800;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.balance-box em {
@@ -843,7 +843,7 @@ onMounted(async () => {
border: 1px solid var(--line);
background: var(--bg);
color: var(--text);
border-radius: 10px;
border-radius: var(--radius);
padding: 0.45rem 0.75rem;
cursor: pointer;
}
@@ -918,7 +918,7 @@ onMounted(async () => {
justify-content: space-between;
gap: 0.5rem;
padding: 0.3rem 0.4rem;
border-radius: 8px;
border-radius: var(--radius);
margin-top: 0.25rem;
font-size: 0.9rem;
}
@@ -942,21 +942,21 @@ onMounted(async () => {
color: #92400e;
background: #fffbeb;
border: 1px solid #fde68a;
border-radius: 8px;
border-radius: var(--radius);
padding: 0.55rem 0.7rem;
font-size: 0.88rem;
}
input,
select {
border: 1px solid var(--line);
border-radius: 10px;
border-radius: var(--radius);
padding: 0.45rem 0.6rem;
background: var(--bg);
color: var(--text);
}
.btn {
border: 0;
border-radius: 10px;
border-radius: var(--radius);
padding: 0.45rem 0.8rem;
background: var(--accent);
color: #fff;
@@ -119,7 +119,7 @@ withDefaults(
h3 {
margin: 0;
font-size: 1.08rem;
font-weight: 800;
font-weight: 600;
color: #1e2937;
}
@@ -143,8 +143,9 @@ p {
align-items: center;
justify-content: center;
gap: 0.4rem;
min-height: 48px;
border-radius: 16px;
min-height: var(--control-h);
height: var(--control-h);
border-radius: var(--radius);
font-weight: 700;
font-size: 0.9rem;
}
@@ -188,9 +189,10 @@ p {
.btn-primary,
.btn-secondary {
min-height: 46px;
min-height: var(--control-h);
height: var(--control-h);
font-size: 0.86rem;
border-radius: 14px;
border-radius: var(--radius);
}
}
</style>
@@ -139,7 +139,7 @@ function onSelect(key: string) {
height: 38px;
border: 0;
background: #fff;
border-radius: 12px;
border-radius: var(--radius);
display: grid;
place-items: center;
color: #334155;
@@ -169,7 +169,7 @@ function onSelect(key: string) {
list-style: none;
width: 220px;
background: #fff;
border-radius: 14px;
border-radius: var(--radius);
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.16);
display: flex;
flex-direction: column;
@@ -187,7 +187,7 @@ function onSelect(key: string) {
box-sizing: border-box;
margin: 0;
border: 0;
border-radius: 10px;
border-radius: var(--radius);
background: transparent;
color: #0f172a;
font: inherit;
@@ -1,4 +1,5 @@
<script setup lang="ts">
import UiButton from '@/components/ui/UiButton.vue';
import UiIcon from '@/components/UiIcon.vue';
import type { PipelineAccent } from '@/lib/pipeline-board';
import { PIPELINE_ACCENT } from '@/lib/pipeline-board';
@@ -13,47 +14,15 @@ const emit = defineEmits<{
</script>
<template>
<button
type="button"
<UiButton
variant="dashed"
block
class="add-deal"
:style="{
'--add-color': PIPELINE_ACCENT[accent].text,
'--add-border': PIPELINE_ACCENT[accent].border,
'--add-soft': PIPELINE_ACCENT[accent].soft,
}"
:style="{ color: PIPELINE_ACCENT[accent].text }"
aria-label="افزودن معامله"
@click="emit('add')"
>
<UiIcon name="plus" :size="16" />
افزودن معامله
</button>
</UiButton>
</template>
<style scoped>
.add-deal {
display: flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
width: 100%;
margin-top: 0.35rem;
padding: 0.85rem 1rem;
border: 1.5px dashed var(--add-border);
border-radius: 16px;
background: color-mix(in srgb, var(--add-soft) 55%, white);
color: var(--add-color);
font-weight: 700;
font-size: 0.9rem;
cursor: pointer;
transition: background 0.15s ease, border-color 0.15s ease, transform 0.15s ease;
}
.add-deal:hover {
background: var(--add-soft);
}
.add-deal:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
</style>
+106 -103
View File
@@ -38,51 +38,52 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
@dragend="emit('dragEnd')"
@dblclick="emit('open', deal.id)"
>
<div class="top">
<div class="identity">
<span class="badge" aria-hidden="true">{{ deal.initials }}</span>
<div class="titles">
<h3 @click.stop="emit('open', deal.id)">{{ deal.title }}</h3>
<p class="desc">{{ deal.description }}</p>
</div>
</div>
<button
type="button"
class="menu"
aria-label="گزینه‌های معامله"
@click.stop="emit('menu', deal.id)"
>
<UiIcon name="dots-v" :size="18" />
</button>
<span class="badge" aria-hidden="true">{{ deal.initials }}</span>
<div class="titles">
<h3 @click.stop="emit('open', deal.id)">{{ deal.title }}</h3>
<p v-if="deal.description" class="desc">{{ deal.description }}</p>
</div>
<div class="amount" dir="ltr">
<button
type="button"
class="menu"
aria-label="گزینه‌های معامله"
@click.stop="emit('menu', deal.id)"
>
<UiIcon name="dots-v" :size="16" />
</button>
<img
class="avatar"
src="/brand/user-avatar.png"
alt=""
width="32"
height="32"
/>
<span class="date">
{{ deal.date }}
<UiIcon name="calendar" :size="13" />
</span>
<div class="amount">
<strong>{{ money.number }}</strong>
<span>{{ money.unit }}</span>
</div>
<div class="foot">
<img
class="avatar"
src="/brand/user-avatar.png"
alt=""
width="28"
height="28"
/>
<span class="date">
<UiIcon name="calendar" :size="14" />
{{ deal.date }}
</span>
</div>
</article>
</template>
<style scoped>
.deal-card {
--face: 32px;
display: grid;
grid-template-columns: var(--face) minmax(0, 1fr) auto;
grid-template-rows: auto auto;
column-gap: 0.5rem;
row-gap: 0.65rem;
align-items: center;
background: #fff;
border: 1px solid color-mix(in srgb, var(--line) 70%, transparent);
border-radius: 16px;
padding: 1rem;
border-radius: var(--radius);
padding: 0.85rem 0.7rem 0.85rem 0.55rem;
min-width: 0;
overflow: hidden;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.04);
cursor: grab;
transition:
@@ -115,113 +116,115 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
outline-offset: 2px;
}
.top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.5rem;
}
.identity {
display: flex;
align-items: flex-start;
gap: 0.65rem;
min-width: 0;
flex: 1;
.badge,
.avatar {
width: var(--face);
height: var(--face);
max-width: var(--face);
border-radius: 999px;
justify-self: center;
}
.badge {
flex: 0 0 auto;
width: 2.35rem;
height: 2.35rem;
border-radius: 999px;
display: grid;
place-items: center;
background: var(--badge-bg);
color: var(--badge-fg);
font-size: 0.72rem;
font-weight: 800;
font-size: 0.65rem;
font-weight: 600;
line-height: 1;
}
.avatar {
object-fit: cover;
border: 1px solid var(--line);
}
.titles {
min-width: 0;
text-align: right;
}
.titles h3 {
margin: 0;
font-size: 0.95rem;
font-weight: 800;
line-height: 1.45;
font-size: 0.82rem;
font-weight: 600;
line-height: 1.4;
color: var(--ink);
cursor: pointer;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow-wrap: anywhere;
}
.desc {
margin: 0.15rem 0 0;
margin: 0.1rem 0 0;
color: var(--muted);
font-size: 0.8rem;
line-height: 1.4;
font-size: 0.7rem;
line-height: 1.35;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.menu {
align-self: start;
justify-self: end;
border: 0;
background: transparent;
background: none;
color: var(--muted);
padding: 0.15rem;
border-radius: 8px;
width: auto;
height: auto;
padding: 0;
margin: 0;
line-height: 0;
cursor: pointer;
flex: 0 0 auto;
}
.menu:hover,
.menu:focus-visible {
color: var(--ink);
background: #f1f5f9;
}
.amount {
margin-top: 0.85rem;
text-align: left;
display: grid;
justify-items: start;
gap: 0.05rem;
}
.amount strong {
font-size: 1.05rem;
font-weight: 800;
color: var(--ink);
letter-spacing: -0.01em;
}
.amount span {
font-size: 0.72rem;
color: var(--muted);
font-weight: 600;
}
.foot {
margin-top: 0.85rem;
display: flex;
align-items: center;
gap: 0.55rem;
}
.avatar {
width: 28px;
height: 28px;
border-radius: 999px;
object-fit: cover;
border: 1px solid var(--line);
background: none;
outline: none;
}
.date {
display: inline-flex;
display: flex;
align-items: center;
gap: 0.3rem;
justify-content: flex-start;
gap: 0.25rem;
min-width: 0;
width: 100%;
color: var(--muted);
font-size: 0.68rem;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.amount {
text-align: left;
display: grid;
justify-items: end;
gap: 0.02rem;
min-width: 0;
}
.amount strong {
font-size: 0.88rem;
font-weight: 600;
color: var(--ink);
letter-spacing: -0.01em;
max-width: 100%;
overflow-wrap: anywhere;
}
.amount span {
font-size: 0.65rem;
color: var(--muted);
font-size: 0.78rem;
font-weight: 600;
}
</style>
@@ -1,4 +1,6 @@
<script setup lang="ts">
import { nextTick, ref } from 'vue';
import UiIcon from '@/components/UiIcon.vue';
import PipelineColumn from './PipelineColumn.vue';
import type { PipelineDeal, PipelineStage } from '@/lib/pipeline-board';
@@ -6,6 +8,7 @@ defineProps<{
stages: PipelineStage[];
draggingId: string | null;
dropStageId: string | null;
canManage?: boolean;
}>();
const emit = defineEmits<{
@@ -16,17 +19,51 @@ const emit = defineEmits<{
addDeal: [stageId: string];
openDeal: [dealId: string];
menuDeal: [dealId: string];
renameStage: [stageId: string, title: string];
deleteStage: [stageId: string];
moveStage: [stageId: string, dir: -1 | 1];
columnDragStart: [stageId: string, event: DragEvent];
columnDragEnd: [];
addStage: [name: string];
}>();
const adding = ref(false);
const newName = ref('');
const addInput = ref<HTMLInputElement | null>(null);
async function startAdd() {
adding.value = true;
newName.value = '';
await nextTick();
addInput.value?.focus();
}
function cancelAdd() {
adding.value = false;
newName.value = '';
}
function submitAdd() {
const name = newName.value.trim();
if (!name) return;
emit('addStage', name);
adding.value = false;
newName.value = '';
}
</script>
<template>
<div class="board" dir="rtl">
<div class="board-shell" dir="rtl">
<div class="board">
<PipelineColumn
v-for="stage in stages"
v-for="(stage, index) in stages"
:key="stage.id"
:stage="stage"
:dragging-id="draggingId"
:drop-active="dropStageId === stage.id"
:can-manage="canManage"
:is-first="index === 0"
:is-last="index === stages.length - 1"
@drag-start="(d, e) => emit('dragStart', d, e)"
@drag-end="emit('dragEnd')"
@drag-over="(id, e) => emit('dragOver', id, e)"
@@ -34,31 +71,169 @@ const emit = defineEmits<{
@add-deal="emit('addDeal', $event)"
@open-deal="emit('openDeal', $event)"
@menu-deal="emit('menuDeal', $event)"
@rename="(id, title) => emit('renameStage', id, title)"
@delete="emit('deleteStage', $event)"
@move="(id, dir) => emit('moveStage', id, dir)"
@column-drag-start="(id, e) => emit('columnDragStart', id, e)"
@column-drag-end="emit('columnDragEnd')"
/>
<section v-if="canManage" class="add-col">
<form v-if="adding" class="add-form" @submit.prevent="submitAdd">
<input
ref="addInput"
v-model="newName"
maxlength="80"
placeholder="نام ستون جدید…"
aria-label="نام ستون جدید"
@keydown.esc.prevent="cancelAdd"
/>
<div class="add-actions">
<button class="ok" type="submit" :disabled="newName.trim().length < 1">
افزودن
</button>
<button class="cancel" type="button" @click="cancelAdd">انصراف</button>
</div>
</form>
<button v-else type="button" class="add-btn" @click="startAdd">
<UiIcon name="plus" :size="18" />
افزودن ستون
</button>
</section>
</div>
</div>
</template>
<style scoped>
.board-shell {
background: #fff;
border: 1px solid var(--line);
border-radius: var(--radius);
padding: var(--pad-modal);
min-width: 0;
}
.board {
display: flex;
flex-direction: row;
gap: 16px;
width: 100%;
min-width: 0;
max-width: 100%;
align-items: stretch;
overflow-x: auto;
overflow-y: hidden;
padding: 0.1rem 0.05rem 0.5rem;
touch-action: pan-x pan-y;
overscroll-behavior-x: contain;
-webkit-overflow-scrolling: touch;
scrollbar-width: thin;
scrollbar-color: color-mix(in srgb, var(--muted) 45%, transparent) transparent;
}
@media (max-width: 1024px) {
.board::-webkit-scrollbar {
height: 8px;
}
.board::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--muted) 38%, transparent);
border-radius: 999px;
}
.add-col {
flex: 0 0 17.5rem;
min-width: 17.5rem;
min-height: 420px;
display: flex;
align-items: flex-start;
padding-top: 0.15rem;
}
.add-btn {
width: 100%;
min-height: 3.2rem;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
border: 1.5px dashed var(--line);
border-radius: var(--radius);
background: #f8fafc;
color: var(--muted);
font: inherit;
font-weight: 700;
cursor: pointer;
}
.add-btn:hover {
border-color: var(--accent);
color: var(--accent-deep, #0f766e);
background: color-mix(in srgb, var(--accent) 6%, #fff);
}
.add-form {
width: 100%;
display: grid;
gap: 0.55rem;
padding: 0.75rem;
border: 1px solid var(--line);
border-radius: var(--radius);
background: #fff;
}
.add-form input {
width: 100%;
min-height: var(--control-h);
padding: 0 0.75rem;
border: 1px solid var(--line);
border-radius: var(--radius);
font: inherit;
}
.add-actions {
display: flex;
gap: 0.4rem;
}
.add-actions .ok,
.add-actions .cancel {
min-height: var(--control-h);
padding: 0 0.85rem;
border-radius: var(--radius);
font: inherit;
font-weight: 700;
cursor: pointer;
}
.add-actions .ok {
border: 0;
background: var(--accent);
color: #fff;
}
.add-actions .ok:disabled {
opacity: 0.5;
cursor: default;
}
.add-actions .cancel {
border: 1px solid var(--line);
background: #fff;
color: var(--ink);
}
@container pipeline (max-width: 720px) {
.board {
overflow-x: auto;
padding-bottom: 0.75rem;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
scroll-padding-inline: 0.25rem;
}
.board::-webkit-scrollbar {
display: none;
.add-col {
flex: 0 0 min(20rem, 86cqi);
width: min(20rem, 86cqi);
min-width: min(20rem, 86cqi);
min-height: 360px;
scroll-snap-align: start;
}
}
</style>
@@ -1,14 +1,18 @@
<script setup lang="ts">
import { nextTick, onBeforeUnmount, ref, watch } from 'vue';
import UiIcon from '@/components/UiIcon.vue';
import AddDealButton from './AddDealButton.vue';
import DealCard from './DealCard.vue';
import type { PipelineDeal, PipelineStage } from '@/lib/pipeline-board';
import { PIPELINE_ACCENT, toFaDealCount } from '@/lib/pipeline-board';
defineProps<{
const props = defineProps<{
stage: PipelineStage;
draggingId: string | null;
dropActive: boolean;
canManage?: boolean;
isFirst?: boolean;
isLast?: boolean;
}>();
const emit = defineEmits<{
@@ -19,8 +23,19 @@ const emit = defineEmits<{
addDeal: [stageId: string];
openDeal: [dealId: string];
menuDeal: [dealId: string];
rename: [stageId: string, title: string];
delete: [stageId: string];
move: [stageId: string, dir: -1 | 1];
columnDragStart: [stageId: string, event: DragEvent];
columnDragEnd: [];
}>();
const renaming = ref(false);
const draft = ref('');
const titleInput = ref<HTMLInputElement | null>(null);
const menuOpen = ref(false);
const menuRoot = ref<HTMLElement | null>(null);
function onCardDragOver(stageId: string, event: DragEvent) {
event.preventDefault();
event.stopPropagation();
@@ -32,6 +47,60 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
event.stopPropagation();
emit('drop', stageId, event, index);
}
function startRename() {
if (!props.canManage) return;
draft.value = props.stage.title;
renaming.value = true;
menuOpen.value = false;
void nextTick(() => titleInput.value?.select());
}
function commitRename() {
if (!renaming.value) return;
const title = draft.value.trim();
renaming.value = false;
if (!title || title === props.stage.title) return;
emit('rename', props.stage.id, title);
}
function cancelRename() {
renaming.value = false;
draft.value = props.stage.title;
}
function toggleMenu() {
menuOpen.value = !menuOpen.value;
}
function onColumnDragStart(event: DragEvent) {
event.dataTransfer?.setData('text/plain', `stage:${props.stage.id}`);
event.dataTransfer!.effectAllowed = 'move';
emit('columnDragStart', props.stage.id, event);
}
function onDocPointerDown(event: PointerEvent) {
const target = event.target as Node | null;
const root = menuRoot.value;
if (root && target && !root.contains(target)) menuOpen.value = false;
}
function onMenuOpened() {
document.addEventListener('pointerdown', onDocPointerDown);
}
function onMenuClosed() {
document.removeEventListener('pointerdown', onDocPointerDown);
}
watch(menuOpen, (open) => {
if (open) onMenuOpened();
else onMenuClosed();
});
onBeforeUnmount(() => {
document.removeEventListener('pointerdown', onDocPointerDown);
});
</script>
<template>
@@ -48,21 +117,88 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
@drop.prevent="emit('drop', stage.id, $event)"
>
<header class="column-head">
<span
v-if="canManage"
class="grip"
draggable="true"
title="کشیدن برای جابه‌جایی"
aria-label="جابه‌جایی ستون"
@dragstart="onColumnDragStart"
@dragend="emit('columnDragEnd')"
>
<UiIcon name="grip" :size="14" />
</span>
<div class="title-wrap">
<span class="dot" aria-hidden="true" />
<h2>{{ stage.title }}</h2>
<input
v-if="renaming"
ref="titleInput"
v-model="draft"
class="title-input"
maxlength="80"
aria-label="نام ستون"
@keydown.enter.prevent="commitRename"
@keydown.esc.prevent="cancelRename"
@blur="commitRename"
/>
<h2
v-else
:class="{ editable: canManage }"
:title="canManage ? 'برای تغییر نام کلیک کنید' : undefined"
@click="startRename"
>
{{ stage.title }}
</h2>
</div>
<div class="head-actions">
<span class="count">{{ toFaDealCount(stage.deals.length) }}</span>
<span class="count">{{ toFaDealCount(stage.deals.length) }}</span>
<div v-if="canManage" ref="menuRoot" class="more-wrap">
<button
type="button"
class="plus"
aria-label="افزودن معامله به این مرحله"
@click="emit('addDeal', stage.id)"
class="icon-btn"
aria-label="گزینه‌های ستون"
:aria-expanded="menuOpen"
@click.stop="toggleMenu"
>
<UiIcon name="plus" :size="16" />
<UiIcon name="dots-v" :size="16" />
</button>
<div v-if="menuOpen" class="col-menu" role="menu">
<button type="button" role="menuitem" @click="startRename">
تغییر نام
</button>
<button
type="button"
role="menuitem"
:disabled="isFirst"
@click="emit('move', stage.id, -1); menuOpen = false"
>
انتقال به راست
</button>
<button
type="button"
role="menuitem"
:disabled="isLast"
@click="emit('move', stage.id, 1); menuOpen = false"
>
انتقال به چپ
</button>
<button
type="button"
role="menuitem"
class="danger"
@click="emit('delete', stage.id); menuOpen = false"
>
حذف ستون
</button>
</div>
</div>
<button
type="button"
class="plus"
aria-label="افزودن معامله به این مرحله"
@click="emit('addDeal', stage.id)"
>
<UiIcon name="plus" :size="16" />
</button>
</header>
<div class="cards" role="list" :aria-label="stage.title">
@@ -95,13 +231,13 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
display: flex;
flex-direction: column;
gap: 0.75rem;
min-width: 0;
flex: 1 1 0;
flex: 1 1 17.5rem;
min-width: 17.5rem;
min-height: 420px;
padding: 0.35rem 0.15rem 0.5rem;
border-radius: 18px;
border: 1px solid transparent;
background: transparent;
padding: 0.75rem;
border-radius: var(--radius);
border: 1px solid var(--line);
background: #fff;
transition: background 0.15s ease, border-color 0.15s ease;
}
@@ -113,16 +249,31 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
.column-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.15rem 0.25rem;
gap: 0.4rem;
padding: 0.1rem 0.1rem 0.15rem;
}
.grip {
display: grid;
place-items: center;
width: 1.25rem;
color: var(--muted);
cursor: grab;
flex: 0 0 auto;
touch-action: none;
}
.grip:active {
cursor: grabbing;
}
.title-wrap {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 0.45rem;
min-width: 0;
flex: 1;
}
.dot {
@@ -133,17 +284,34 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
flex: 0 0 auto;
}
.column-head h2 {
.column-head h2,
.title-input {
margin: 0;
min-width: 0;
width: 100%;
font-size: 0.98rem;
font-weight: 800;
font-weight: 600;
color: var(--ink);
font: inherit;
font-weight: 600;
}
.head-actions {
display: flex;
align-items: center;
gap: 0.45rem;
.column-head h2 {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.column-head h2.editable {
cursor: text;
}
.title-input {
height: 1.7rem;
padding: 0 0.4rem;
border: 1px solid var(--line);
border-radius: var(--radius);
background: #fff;
}
.count {
@@ -153,29 +321,91 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
white-space: nowrap;
}
.more-wrap {
position: relative;
flex: 0 0 auto;
}
.icon-btn,
.plus {
width: 1.7rem;
height: 1.7rem;
border-radius: 999px;
border: 0;
width: var(--control-h);
height: var(--control-h);
border-radius: var(--radius);
display: grid;
place-items: center;
background: color-mix(in srgb, var(--accent) 14%, white);
color: var(--accent);
background: #fff;
cursor: pointer;
}
.icon-btn {
border: 1px solid transparent;
color: var(--muted);
}
.icon-btn:hover,
.icon-btn:focus-visible {
background: var(--stage-soft);
color: var(--stage-solid);
outline: none;
}
.plus {
border: 1.5px solid var(--stage-solid);
color: var(--stage-solid);
}
.plus:hover,
.plus:focus-visible {
background: var(--accent-soft);
background: var(--stage-soft);
outline: none;
}
.col-menu {
position: absolute;
top: calc(100% + 4px);
inset-inline-end: 0;
z-index: 8;
min-width: 10.5rem;
padding: 0.3rem;
display: grid;
gap: 0.1rem;
background: #fff;
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow);
}
.col-menu button {
border: 0;
background: transparent;
padding: 0.45rem 0.7rem;
font: inherit;
font-size: 0.86rem;
color: var(--ink);
text-align: right;
cursor: pointer;
border-radius: var(--radius);
}
.col-menu button:hover:not(:disabled) {
background: #f8fafc;
}
.col-menu button:disabled {
opacity: 0.4;
cursor: default;
}
.col-menu .danger {
color: var(--danger, #dc2626);
}
.cards {
display: flex;
flex-direction: column;
gap: 0.7rem;
flex: 1;
min-width: 0;
min-height: 4rem;
}
@@ -190,20 +420,14 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
font-size: 0.85rem;
}
@media (max-width: 1024px) {
@container pipeline (max-width: 720px) {
.column {
flex: 0 0 auto;
width: min(320px, 86vw);
min-width: min(320px, 86vw);
flex: 0 0 min(20rem, 86cqi);
width: min(20rem, 86cqi);
min-width: min(20rem, 86cqi);
max-width: none;
min-height: 360px;
scroll-snap-align: start;
}
}
@media (max-width: 700px) {
.column {
width: 88vw;
min-width: 88vw;
min-height: 360px;
}
}
</style>
@@ -0,0 +1,351 @@
<script setup lang="ts">
import { computed } from 'vue';
import UiIcon from '@/components/UiIcon.vue';
import type { PipelineDeal, PipelineStage } from '@/lib/pipeline-board';
import {
formatCurrencyParts,
PIPELINE_ACCENT,
} from '@/lib/pipeline-board';
const props = defineProps<{
stages: PipelineStage[];
}>();
const emit = defineEmits<{
openDeal: [dealId: string];
menuDeal: [dealId: string];
}>();
const rows = computed(() =>
props.stages.flatMap((stage) =>
stage.deals.map((deal) => ({
deal,
stageTitle: stage.title,
accent: stage.color,
})),
),
);
function money(deal: PipelineDeal) {
return formatCurrencyParts(deal.amount, deal.currencyUnit ?? 'تومان');
}
</script>
<template>
<div class="list" dir="rtl">
<p v-if="!rows.length" class="empty">معامله‌ای نیست</p>
<div v-else class="table-wrap">
<table class="data-table">
<thead>
<tr>
<th>معامله</th>
<th>مرحله</th>
<th>مبلغ</th>
<th>تاریخ</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.deal.id">
<td>
<button
type="button"
class="identity"
@click="emit('openDeal', row.deal.id)"
>
<span
class="badge"
:style="{
background: PIPELINE_ACCENT[row.accent].soft,
color: PIPELINE_ACCENT[row.accent].text,
}"
>{{ row.deal.initials }}</span>
<span class="titles">
<strong>{{ row.deal.title }}</strong>
<em v-if="row.deal.description">{{ row.deal.description }}</em>
</span>
</button>
</td>
<td>
<span
class="stage"
:style="{
background: PIPELINE_ACCENT[row.accent].soft,
color: PIPELINE_ACCENT[row.accent].text,
}"
>
<i :style="{ background: PIPELINE_ACCENT[row.accent].solid }" />
{{ row.stageTitle }}
</span>
</td>
<td>
<span class="amount" dir="ltr">
<strong>{{ money(row.deal).number }}</strong>
<small>{{ money(row.deal).unit }}</small>
</span>
</td>
<td>
<span class="date">
<UiIcon name="calendar" :size="14" />
{{ row.deal.date }}
</span>
</td>
<td class="menu-cell">
<button
type="button"
class="menu"
aria-label="گزینه‌های معامله"
@click="emit('menuDeal', row.deal.id)"
>
<UiIcon name="dots-v" :size="18" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="rows.length" class="cards">
<article
v-for="row in rows"
:key="row.deal.id"
class="card"
@dblclick="emit('openDeal', row.deal.id)"
>
<button
type="button"
class="identity"
@click="emit('openDeal', row.deal.id)"
>
<span
class="badge"
:style="{
background: PIPELINE_ACCENT[row.accent].soft,
color: PIPELINE_ACCENT[row.accent].text,
}"
>{{ row.deal.initials }}</span>
<span class="titles">
<strong>{{ row.deal.title }}</strong>
<em v-if="row.deal.description">{{ row.deal.description }}</em>
</span>
</button>
<span
class="stage"
:style="{
background: PIPELINE_ACCENT[row.accent].soft,
color: PIPELINE_ACCENT[row.accent].text,
}"
>
<i :style="{ background: PIPELINE_ACCENT[row.accent].solid }" />
{{ row.stageTitle }}
</span>
<div class="card-foot">
<span class="date">
<UiIcon name="calendar" :size="14" />
{{ row.deal.date }}
</span>
<span class="amount" dir="ltr">
<strong>{{ money(row.deal).number }}</strong>
<small>{{ money(row.deal).unit }}</small>
</span>
</div>
</article>
</div>
</div>
</template>
<style scoped>
.list {
min-width: 0;
}
.empty {
margin: 2rem 0;
text-align: center;
color: var(--muted);
font-weight: 700;
}
.table-wrap {
background: #fff;
border: 1px solid color-mix(in srgb, var(--line) 80%, transparent);
border-radius: var(--radius);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
overflow: auto;
}
.data-table {
width: 100%;
border-collapse: collapse;
min-width: 640px;
}
.data-table th,
.data-table td {
padding: 0.85rem 1rem;
text-align: start;
border-bottom: 1px solid #f1f5f9;
vertical-align: middle;
}
.data-table th {
font-size: 0.78rem;
color: #94a3b8;
font-weight: 700;
background: #f8fafc;
}
.data-table tbody tr:last-child td {
border-bottom: 0;
}
.data-table tbody tr:hover td {
background: #f8fafc;
}
.identity {
display: flex;
align-items: center;
gap: 0.7rem;
min-width: 0;
border: 0;
background: transparent;
padding: 0;
cursor: pointer;
text-align: right;
font: inherit;
color: inherit;
}
.badge {
flex: 0 0 auto;
width: 2.2rem;
height: 2.2rem;
border-radius: 999px;
display: grid;
place-items: center;
font-size: 0.7rem;
font-weight: 600;
}
.titles {
display: grid;
gap: 0.1rem;
min-width: 0;
}
.titles strong {
font-size: 0.92rem;
font-weight: 600;
color: var(--ink);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.titles em {
font-style: normal;
color: var(--muted);
font-size: 0.78rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.stage {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.28rem 0.65rem;
border-radius: 999px;
font-size: 0.78rem;
font-weight: 700;
white-space: nowrap;
}
.stage i {
width: 0.45rem;
height: 0.45rem;
border-radius: 999px;
display: block;
}
.amount {
display: grid;
justify-items: start;
gap: 0.05rem;
}
.amount strong {
font-weight: 600;
color: var(--ink);
}
.amount small {
color: var(--muted);
font-size: 0.72rem;
font-weight: 600;
}
.date {
display: inline-flex;
align-items: center;
gap: 0.3rem;
color: var(--muted);
font-size: 0.82rem;
font-weight: 600;
white-space: nowrap;
}
.menu-cell {
width: 2.5rem;
}
.menu {
border: 0;
background: transparent;
color: var(--muted);
padding: 0.2rem;
border-radius: var(--radius);
cursor: pointer;
}
.menu:hover,
.menu:focus-visible {
color: var(--ink);
background: #f1f5f9;
}
.cards {
display: none;
gap: 0.7rem;
}
.card {
background: #fff;
border: 1px solid color-mix(in srgb, var(--line) 70%, transparent);
border-radius: var(--radius);
padding: 0.95rem 1rem;
display: grid;
gap: 0.7rem;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.04);
}
.card-foot {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 0.5rem;
}
@container pipeline (max-width: 720px) {
.table-wrap {
display: none;
}
.cards {
display: grid;
}
}
</style>
@@ -1,22 +1,42 @@
<script setup lang="ts">
import UiFilterBar from '@/components/ui/UiFilterBar.vue';
import UiIcon from '@/components/UiIcon.vue';
import UiSegmented from '@/components/ui/UiSegmented.vue';
import UiSelect from '@/components/ui/UiSelect.vue';
export type PipelineViewMode = 'kanban' | 'list';
defineProps<{
pipelineName: string;
pipelineOptions: Array<{ id: string; name: string }>;
selectedPipelineId: string;
viewMode: PipelineViewMode;
search: string;
}>();
withDefaults(
defineProps<{
pipelineName: string;
pipelineOptions: Array<{ id: string; name: string }>;
canCreate?: boolean;
}>(),
{ canCreate: false },
);
const emit = defineEmits<{
'update:viewMode': [PipelineViewMode];
'update:search': [string];
'update:selectedPipelineId': [string];
filter: [];
create: [];
}>();
const viewMode = defineModel<PipelineViewMode>('viewMode', { required: true });
const search = defineModel<string>('search', { default: '' });
const selectedPipelineId = defineModel<string>('selectedPipelineId', { required: true });
const amountMin = defineModel<string>('amountMin', { default: '' });
const amountMax = defineModel<string>('amountMax', { default: '' });
const viewOptions = [
{ value: 'kanban' as const, label: 'نمای کاریز', icon: 'grid' as const },
{ value: 'list' as const, label: 'نمای لیست', icon: 'list' as const },
];
function onPick(value: string) {
if (value === '__create__') {
emit('create');
return;
}
selectedPipelineId.value = value;
}
</script>
<template>
@@ -25,237 +45,116 @@ const emit = defineEmits<{
<span class="brand-ico" aria-hidden="true">
<UiIcon name="briefcase" :size="18" />
</span>
<h1>کاریز فروش</h1>
<h1>{{ pipelineName }}</h1>
</div>
<div class="view-toggle" role="group" aria-label="نوع نمایش">
<button
type="button"
class="seg"
:class="{ on: viewMode === 'kanban' }"
:aria-pressed="viewMode === 'kanban'"
@click="emit('update:viewMode', 'kanban')"
>
<UiIcon name="grid" :size="16" />
نمای کاریز
</button>
<button
type="button"
class="seg"
:class="{ on: viewMode === 'list' }"
:aria-pressed="viewMode === 'list'"
@click="emit('update:viewMode', 'list')"
>
<UiIcon name="list" :size="16" />
نمای لیست
</button>
</div>
<UiSegmented v-model="viewMode" :options="viewOptions">
<template #icon="{ option }">
<UiIcon :name="option.icon ?? 'grid'" :size="16" />
</template>
</UiSegmented>
<label class="pipeline-pick">
<span class="sr">انتخاب کاریز</span>
<select
:value="selectedPipelineId"
@change="
emit(
'update:selectedPipelineId',
($event.target as HTMLSelectElement).value,
)
"
<UiSelect
class="pipeline-pick"
:model-value="selectedPipelineId"
@update:model-value="onPick"
>
<option
v-for="opt in pipelineOptions"
:key="opt.id"
:value="opt.id"
>
<option
v-for="opt in pipelineOptions"
:key="opt.id"
:value="opt.id"
>
{{ opt.name }}
</option>
</select>
<UiIcon class="chev" name="chevron" :size="16" />
</label>
{{ opt.name }}
</option>
<option v-if="canCreate" value="__create__">کاریز جدید…</option>
</UiSelect>
<label class="search">
<UiIcon name="search" :size="16" />
<span class="sr">جستجو</span>
<input
:value="search"
type="search"
placeholder="جستجو..."
@input="emit('update:search', ($event.target as HTMLInputElement).value)"
/>
</label>
<button type="button" class="filter-btn" aria-label="فیلترها" @click="emit('filter')">
<UiIcon name="filter" :size="16" />
فیلترها
</button>
<UiFilterBar v-model:search="search" class="filters">
<label class="field">
<span>حداقل مبلغ</span>
<input v-model="amountMin" type="number" min="0" placeholder="۰" />
</label>
<label class="field">
<span>حداکثر مبلغ</span>
<input v-model="amountMax" type="number" min="0" placeholder="—" />
</label>
</UiFilterBar>
</header>
</template>
<style scoped>
.toolbar {
display: flex;
flex-wrap: wrap;
flex-wrap: nowrap;
align-items: center;
gap: 0.65rem;
margin-bottom: 1rem;
gap: 0.55rem;
margin-bottom: 0.85rem;
min-width: 0;
width: 100%;
}
.title-block {
display: flex;
align-items: center;
gap: 0.55rem;
margin-inline-end: 0.25rem;
flex: 0 0 auto;
min-width: 0;
}
.brand-ico {
width: 2.15rem;
height: 2.15rem;
border-radius: 10px;
width: var(--control-h);
height: var(--control-h);
border-radius: var(--radius);
display: grid;
place-items: center;
background: #0f766e;
background: var(--accent-deep);
color: #fff;
flex: 0 0 auto;
}
h1 {
margin: 0;
font-size: 1.25rem;
font-weight: 800;
color: var(--ink);
}
.view-toggle {
display: inline-flex;
background: #eef2f4;
border-radius: 12px;
padding: 0.2rem;
gap: 0.15rem;
}
.seg {
display: inline-flex;
align-items: center;
gap: 0.35rem;
border: 0;
background: transparent;
color: var(--muted);
font-weight: 700;
font-size: 0.82rem;
padding: 0.45rem 0.75rem;
border-radius: 10px;
cursor: pointer;
}
.seg.on {
background: #fff;
color: var(--accent);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);
}
.seg:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
.pipeline-pick {
position: relative;
display: inline-flex;
align-items: center;
min-width: 140px;
}
.pipeline-pick select {
appearance: none;
border: 1px solid var(--line);
background: #fff;
border-radius: 12px;
padding: 0.55rem 2rem 0.55rem 0.85rem;
font: inherit;
font-size: 1.15rem;
font-weight: 600;
color: var(--ink);
min-width: 150px;
cursor: pointer;
}
.pipeline-pick .chev {
position: absolute;
left: 0.65rem;
pointer-events: none;
color: var(--muted);
transform: rotate(-90deg);
}
.search {
flex: 1 1 180px;
min-width: 160px;
display: flex;
align-items: center;
gap: 0.45rem;
background: #fff;
border: 1px solid var(--line);
border-radius: 12px;
padding: 0.45rem 0.75rem;
color: var(--muted);
}
.search input {
border: 0;
outline: none;
background: transparent;
width: 100%;
color: var(--ink);
font: inherit;
}
.filter-btn {
display: inline-flex;
align-items: center;
gap: 0.35rem;
border: 0;
border-radius: 12px;
padding: 0.55rem 0.95rem;
background: var(--accent);
color: #fff;
font-weight: 700;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.filter-btn:focus-visible,
.pipeline-pick select:focus-visible,
.search:focus-within {
outline: 2px solid var(--accent-soft);
outline-offset: 1px;
.pipeline-pick {
flex: 0 1 13rem;
min-width: 8.5rem;
}
.sr {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
.filters {
flex: 1 1 12rem;
min-width: 0;
}
@media (max-width: 900px) {
.field {
display: grid;
gap: 0.3rem;
}
.field span {
font-size: 0.8rem;
color: var(--muted);
font-weight: 700;
}
@container pipeline (max-width: 720px) {
.toolbar {
align-items: stretch;
flex-wrap: wrap;
}
.title-block {
width: 100%;
}
.view-toggle,
.pipeline-pick,
.search,
.filter-btn {
flex: 1 1 auto;
}
.pipeline-pick select,
.filter-btn {
width: 100%;
justify-content: center;
.filters {
flex: 1 1 100%;
}
}
</style>
+88
View File
@@ -0,0 +1,88 @@
<script setup lang="ts">
withDefaults(
defineProps<{
variant?: 'neutral' | 'accent' | 'primary' | 'success' | 'warning' | 'danger' | 'info';
size?: 'sm' | 'md';
dot?: boolean;
}>(),
{
variant: 'neutral',
size: 'md',
dot: false,
},
);
</script>
<template>
<span class="ui-badge" :class="[variant, size]">
<span v-if="dot" class="badge-dot" aria-hidden="true" />
<slot />
</span>
</template>
<style scoped>
.ui-badge {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
padding: 0.2rem 0.6rem;
border-radius: var(--radius-full);
font-size: var(--fs-xs);
font-weight: var(--fw-semibold);
line-height: 1.2;
white-space: nowrap;
border: 1px solid transparent;
user-select: none;
}
.ui-badge.sm {
padding: 0.1rem 0.45rem;
font-size: 0.7rem;
}
.badge-dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
/* Variants */
.ui-badge.neutral {
background: var(--surface-subtle);
color: var(--ink-secondary);
border-color: var(--line);
}
.ui-badge.accent,
.ui-badge.primary {
background: var(--accent-soft);
color: var(--accent-deep);
border-color: color-mix(in srgb, var(--accent) 30%, transparent);
}
.ui-badge.success {
background: var(--success-soft);
color: var(--success-deep);
border-color: color-mix(in srgb, var(--success) 30%, transparent);
}
.ui-badge.warning {
background: var(--warning-soft);
color: var(--warning-deep);
border-color: color-mix(in srgb, var(--warning) 30%, transparent);
}
.ui-badge.danger {
background: var(--danger-soft);
color: var(--danger);
border-color: color-mix(in srgb, var(--danger) 30%, transparent);
}
.ui-badge.info {
background: var(--info-soft);
color: var(--info-deep);
border-color: color-mix(in srgb, var(--info) 30%, transparent);
}
</style>
+219
View File
@@ -0,0 +1,219 @@
<script setup lang="ts">
withDefaults(
defineProps<{
variant?: 'primary' | 'ghost' | 'dashed' | 'icon' | 'danger' | 'outline' | 'link' | 'secondary' | 'success';
size?: 'sm' | 'md' | 'lg';
type?: 'button' | 'submit' | 'reset';
disabled?: boolean;
loading?: boolean;
block?: boolean;
}>(),
{
variant: 'primary',
size: 'md',
type: 'button',
disabled: false,
loading: false,
block: false,
},
);
</script>
<template>
<button
:type="type"
class="ui-btn"
:class="[variant, size, { block, loading }]"
:disabled="disabled || loading"
:aria-busy="loading"
>
<span v-if="loading" class="spinner" aria-hidden="true"></span>
<slot name="icon" />
<slot />
</button>
</template>
<style scoped>
.ui-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--sp-2);
min-height: var(--control-h-md);
height: var(--control-h-md);
padding: 0 0.85rem;
border: 1px solid transparent;
border-radius: var(--radius);
background: var(--accent);
color: var(--accent-contrast);
font: inherit;
font-weight: var(--fw-semibold);
font-size: var(--fs-sm);
white-space: nowrap;
cursor: pointer;
box-sizing: border-box;
transition: background var(--transition-fast), border-color var(--transition-fast),
box-shadow var(--transition-fast), opacity var(--transition-fast);
user-select: none;
}
/* Sizes */
.ui-btn.sm {
min-height: var(--control-h-sm);
height: var(--control-h-sm);
padding: 0 0.65rem;
font-size: var(--fs-xs);
border-radius: var(--radius-sm);
}
.ui-btn.md {
min-height: var(--control-h-md);
height: var(--control-h-md);
padding: 0 0.85rem;
font-size: var(--fs-sm);
border-radius: var(--radius);
}
.ui-btn.lg {
min-height: var(--control-h-lg);
height: var(--control-h-lg);
padding: 0 1.15rem;
font-size: var(--fs-base);
border-radius: var(--radius-md);
}
.ui-btn:hover:not(:disabled) {
background: var(--accent-hover);
}
.ui-btn:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.ui-btn.block {
width: 100%;
}
/* Variants */
.ui-btn.ghost {
background: transparent;
color: var(--ink);
border-color: var(--line);
}
.ui-btn.ghost:hover:not(:disabled) {
background: var(--surface-subtle);
border-color: var(--line-strong);
}
.ui-btn.outline {
background: transparent;
color: var(--accent);
border-color: var(--accent);
}
.ui-btn.outline:hover:not(:disabled) {
background: var(--accent-subtle);
}
.ui-btn.secondary {
background: var(--surface-subtle);
color: var(--ink-secondary);
border-color: var(--line);
}
.ui-btn.secondary:hover:not(:disabled) {
background: var(--line);
color: var(--ink);
}
.ui-btn.danger {
background: var(--danger);
color: #fff;
border-color: var(--danger);
}
.ui-btn.danger:hover:not(:disabled) {
background: var(--danger-hover);
}
.ui-btn.success {
background: var(--success);
color: #fff;
border-color: var(--success);
}
.ui-btn.success:hover:not(:disabled) {
background: var(--success-deep);
}
.ui-btn.dashed {
background: #fff;
color: var(--muted);
border: 1.5px dashed var(--line-strong);
}
.ui-btn.dashed:hover:not(:disabled) {
color: var(--accent);
border-color: var(--accent);
background: var(--accent-subtle);
}
.ui-btn.link {
background: transparent;
border-color: transparent;
color: var(--accent);
padding: 0 var(--sp-1);
min-height: auto;
font-weight: var(--fw-semibold);
}
.ui-btn.link:hover:not(:disabled) {
background: transparent;
text-decoration: underline;
}
.ui-btn.icon {
width: var(--control-h-md);
padding: 0;
background: #fff;
color: var(--accent-deep);
border-color: var(--accent);
}
.ui-btn.icon.sm {
width: var(--control-h-sm);
min-height: var(--control-h-sm);
}
.ui-btn.icon.lg {
width: var(--control-h-lg);
min-height: var(--control-h-lg);
}
.ui-btn.icon:hover:not(:disabled) {
background: var(--accent-subtle);
}
.ui-btn:focus-visible {
outline: 2px solid var(--accent-soft);
outline-offset: 1px;
}
/* Spinner */
.spinner {
width: 14px;
height: 14px;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: ui-spin 0.6s linear infinite;
}
@keyframes ui-spin {
to {
transform: rotate(360deg);
}
}
</style>
+119
View File
@@ -0,0 +1,119 @@
<script setup lang="ts">
withDefaults(
defineProps<{
padding?: 'none' | 'sm' | 'md' | 'lg';
shadow?: 'none' | 'xs' | 'sm' | 'md';
interactive?: boolean;
title?: string;
}>(),
{
padding: 'md',
shadow: 'xs',
interactive: false,
},
);
</script>
<template>
<div
class="ui-card"
:class="[
`pad-${padding}`,
`shadow-${shadow}`,
{ interactive }
]"
>
<header v-if="title || $slots.header" class="card-head">
<slot name="header">
<h3 v-if="title" class="card-title">{{ title }}</h3>
</slot>
<div v-if="$slots.actions" class="card-actions">
<slot name="actions" />
</div>
</header>
<div class="card-body">
<slot />
</div>
<footer v-if="$slots.footer" class="card-foot">
<slot name="footer" />
</footer>
</div>
</template>
<style scoped>
.ui-card {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-sizing: border-box;
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}
/* Padding variants */
.ui-card.pad-none {
padding: 0;
}
.ui-card.pad-sm {
padding: var(--sp-3);
}
.ui-card.pad-md {
padding: var(--sp-5);
}
.ui-card.pad-lg {
padding: var(--sp-6);
}
/* Shadow variants */
.ui-card.shadow-none {
box-shadow: none;
}
.ui-card.shadow-xs {
box-shadow: var(--shadow-xs);
}
.ui-card.shadow-sm {
box-shadow: var(--shadow-sm);
}
.ui-card.shadow-md {
box-shadow: var(--shadow-md);
}
.ui-card.interactive:hover {
border-color: var(--line-strong);
box-shadow: var(--shadow-sm);
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-3);
padding-bottom: var(--sp-3);
margin-bottom: var(--sp-4);
border-bottom: 1px solid var(--line-light);
}
.card-title {
margin: 0;
font-size: var(--fs-md);
font-weight: var(--fw-bold);
color: var(--ink);
}
.card-actions {
display: flex;
align-items: center;
gap: var(--sp-2);
}
.card-foot {
padding-top: var(--sp-3);
margin-top: var(--sp-4);
border-top: 1px solid var(--line-light);
}
</style>
+114
View File
@@ -0,0 +1,114 @@
<script lang="ts">
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, PieChart, BarChart } from 'echarts/charts';
import {
GridComponent,
LegendComponent,
TooltipComponent,
TitleComponent,
} from 'echarts/components';
import type { ComposeOption } from 'echarts/core';
import type { LineSeriesOption, PieSeriesOption, BarSeriesOption } from 'echarts/charts';
import type {
GridComponentOption,
LegendComponentOption,
TooltipComponentOption,
TitleComponentOption,
} from 'echarts/components';
use([
CanvasRenderer,
LineChart,
PieChart,
BarChart,
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent,
]);
export type UiChartOption = ComposeOption<
| LineSeriesOption
| PieSeriesOption
| BarSeriesOption
| GridComponentOption
| TooltipComponentOption
| LegendComponentOption
| TitleComponentOption
>;
/**
* Shared palette matching Montact CRM design tokens
*/
export const CHART_PALETTE = [
'#14b8a6', // Teal (Accent)
'#3b82f6', // Blue
'#f59e0b', // Amber
'#10b981', // Emerald
'#8b5cf6', // Violet
'#f43f5e', // Rose
'#06b6d4', // Cyan
'#eab308', // Yellow
];
</script>
<script setup lang="ts">
import VChart from 'vue-echarts';
withDefaults(
defineProps<{
option: UiChartOption;
height?: string;
loading?: boolean;
}>(),
{ height: '260px', loading: false },
);
</script>
<template>
<div class="ui-chart-container" :style="{ height }">
<div v-if="loading" class="chart-loading">
<div class="chart-spinner"></div>
</div>
<VChart v-else class="ui-chart" :option="option" autoresize />
</div>
</template>
<style scoped>
.ui-chart-container {
width: 100%;
min-width: 0;
position: relative;
}
.ui-chart {
width: 100%;
height: 100%;
min-width: 0;
}
.chart-loading {
position: absolute;
inset: 0;
display: grid;
place-items: center;
background: rgba(255, 255, 255, 0.7);
z-index: 2;
}
.chart-spinner {
width: 28px;
height: 28px;
border: 3px solid var(--line);
border-top-color: var(--accent);
border-radius: 50%;
animation: chart-spin 0.8s linear infinite;
}
@keyframes chart-spin {
to {
transform: rotate(360deg);
}
}
</style>
@@ -0,0 +1,81 @@
<script setup lang="ts">
import UiIcon from '@/components/UiIcon.vue';
type IconName = InstanceType<typeof UiIcon>['$props']['name'];
withDefaults(
defineProps<{
title?: string;
description?: string;
icon?: IconName;
}>(),
{
title: 'موردی یافت نشد',
icon: 'search',
},
);
</script>
<template>
<div class="ui-empty-state">
<div class="icon-wrap">
<slot name="icon">
<UiIcon :name="icon" :size="32" />
</slot>
</div>
<h3 class="title">{{ title }}</h3>
<p v-if="description" class="description">{{ description }}</p>
<slot />
<div v-if="$slots.action" class="action-wrap">
<slot name="action" />
</div>
</div>
</template>
<style scoped>
.ui-empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: var(--sp-10) var(--sp-6);
gap: var(--sp-3);
color: var(--muted);
background: var(--surface);
border: 1px dashed var(--line-strong);
border-radius: var(--radius);
width: 100%;
box-sizing: border-box;
}
.icon-wrap {
display: grid;
place-items: center;
width: 56px;
height: 56px;
border-radius: 50%;
background: var(--surface-subtle);
color: var(--muted);
margin-bottom: var(--sp-1);
}
.title {
margin: 0;
font-size: var(--fs-md);
font-weight: var(--fw-bold);
color: var(--ink);
}
.description {
margin: 0;
font-size: var(--fs-sm);
max-width: 360px;
line-height: var(--lh-relaxed);
color: var(--muted);
}
.action-wrap {
margin-top: var(--sp-2);
}
</style>
+104
View File
@@ -0,0 +1,104 @@
<script setup lang="ts">
withDefaults(
defineProps<{
label?: string;
forId?: string;
required?: boolean;
hint?: string;
error?: string | boolean;
horizontal?: boolean;
}>(),
{
required: false,
horizontal: false,
},
);
</script>
<template>
<div class="ui-field" :class="{ horizontal, hasError: !!error }">
<div v-if="label || $slots.label" class="label-row">
<label v-if="label" :for="forId" class="field-label">
{{ label }}
<span v-if="required" class="required-mark" aria-hidden="true">*</span>
</label>
<slot v-else name="label" />
<slot name="label-extra" />
</div>
<div class="control-wrap">
<slot />
<p v-if="typeof error === 'string' && error" class="field-error" role="alert">
{{ error }}
</p>
<p v-else-if="hint || $slots.hint" class="field-hint">
<slot name="hint">{{ hint }}</slot>
</p>
</div>
</div>
</template>
<style scoped>
.ui-field {
display: flex;
flex-direction: column;
gap: var(--sp-1);
min-width: 0;
width: 100%;
}
.ui-field.horizontal {
flex-direction: row;
align-items: center;
gap: var(--sp-3);
}
.ui-field.horizontal .label-row {
flex: 0 0 140px;
}
.ui-field.horizontal .control-wrap {
flex: 1;
}
.label-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
}
.field-label {
font-size: var(--fs-sm);
font-weight: var(--fw-semibold);
color: var(--ink-secondary);
line-height: var(--lh-tight);
}
.required-mark {
color: var(--danger);
margin-right: 2px;
}
.control-wrap {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
width: 100%;
}
.field-error {
margin: 2px 0 0;
font-size: var(--fs-xs);
color: var(--danger);
font-weight: var(--fw-medium);
}
.field-hint {
margin: 2px 0 0;
font-size: var(--fs-xs);
color: var(--muted);
line-height: var(--lh-normal);
}
</style>
@@ -0,0 +1,62 @@
<script setup lang="ts">
import { ref } from 'vue';
import UiButton from './UiButton.vue';
import UiSearch from './UiSearch.vue';
import UiIcon from '@/components/UiIcon.vue';
withDefaults(
defineProps<{
placeholder?: string;
}>(),
{ placeholder: 'جستجو...' },
);
const search = defineModel<string>('search', { default: '' });
const open = ref(false);
</script>
<template>
<div class="filter-bar">
<div class="row">
<slot name="before" />
<UiSearch v-model="search" :placeholder="placeholder" class="search" />
<UiButton variant="secondary" type="button" @click="open = !open">
<UiIcon name="filter" :size="16" />
فیلترها
</UiButton>
</div>
<div v-if="open" class="panel">
<slot />
</div>
</div>
</template>
<style scoped>
.filter-bar {
display: grid;
gap: 0.65rem;
min-width: 0;
}
.row {
display: flex;
align-items: center;
gap: 0.55rem;
min-width: 0;
}
.search {
flex: 1 1 10rem;
}
.panel {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr));
gap: 0.65rem;
padding: var(--sp-4);
background: #fff;
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow-sm);
}
</style>
+125
View File
@@ -0,0 +1,125 @@
<script setup lang="ts">
withDefaults(
defineProps<{
type?: string;
placeholder?: string;
disabled?: boolean;
readonly?: boolean;
required?: boolean;
error?: boolean | string;
size?: 'sm' | 'md' | 'lg';
maxlength?: number | string;
minlength?: number | string;
id?: string;
autocomplete?: string;
}>(),
{
type: 'text',
size: 'md',
disabled: false,
readonly: false,
required: false,
},
);
const model = defineModel<string | number>({ default: '' });
</script>
<template>
<div class="ui-input-wrapper" :class="[size, { disabled, hasError: !!error }]">
<slot name="prefix" />
<input
:id="id"
v-model="model"
class="ui-input"
:type="type"
:placeholder="placeholder"
:disabled="disabled"
:readonly="readonly"
:required="required"
:maxlength="maxlength"
:minlength="minlength"
:autocomplete="autocomplete"
:aria-invalid="!!error"
/>
<slot name="suffix" />
</div>
</template>
<style scoped>
.ui-input-wrapper {
display: inline-flex;
align-items: center;
width: 100%;
min-width: 0;
min-height: var(--control-h-md);
padding: 0 var(--sp-3);
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
color: var(--ink);
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
box-sizing: border-box;
}
.ui-input-wrapper.sm {
min-height: var(--control-h-sm);
padding: 0 var(--sp-2);
border-radius: var(--radius-sm);
font-size: var(--fs-xs);
}
.ui-input-wrapper.md {
min-height: var(--control-h-md);
padding: 0 var(--sp-3);
border-radius: var(--radius);
font-size: var(--fs-base);
}
.ui-input-wrapper.lg {
min-height: var(--control-h-lg);
padding: 0 var(--sp-4);
border-radius: var(--radius-md);
font-size: var(--fs-md);
}
.ui-input {
flex: 1 1 auto;
width: 100%;
min-width: 0;
border: 0;
outline: none;
background: transparent;
color: inherit;
font: inherit;
padding: 0;
}
.ui-input::placeholder {
color: var(--muted-light);
}
.ui-input-wrapper:focus-within {
outline: 2px solid var(--accent-soft);
border-color: var(--accent);
}
.ui-input-wrapper.hasError {
border-color: var(--danger);
}
.ui-input-wrapper.hasError:focus-within {
outline: 2px solid var(--danger-soft);
border-color: var(--danger);
}
.ui-input-wrapper.disabled {
background: var(--surface-subtle);
opacity: 0.65;
cursor: not-allowed;
}
.ui-input:disabled {
cursor: not-allowed;
}
</style>
+219
View File
@@ -0,0 +1,219 @@
<script setup lang="ts">
import { onUnmounted, watch } from 'vue';
import UiIcon from '@/components/UiIcon.vue';
const props = defineProps<{
open: boolean;
title: string;
}>();
const emit = defineEmits<{
close: [];
}>();
watch(
() => props.open,
(open) => {
document.body.style.overflow = open ? 'hidden' : '';
},
);
onUnmounted(() => {
document.body.style.overflow = '';
});
function onBackdrop(event: MouseEvent) {
if (event.target === event.currentTarget) emit('close');
}
</script>
<template>
<Teleport to="body">
<div v-if="open" class="backdrop" @click="onBackdrop">
<section
class="dialog"
role="dialog"
aria-modal="true"
:aria-label="title"
@click.stop
>
<header class="head">
<h2>{{ title }}</h2>
<button type="button" class="close" aria-label="بستن" @click="emit('close')">
<UiIcon name="x" :size="18" />
</button>
</header>
<div class="body">
<slot />
</div>
<footer v-if="$slots.footer" class="foot">
<slot name="footer" />
</footer>
</section>
</div>
</Teleport>
</template>
<style scoped>
.backdrop {
position: fixed;
inset: 0;
z-index: 80;
display: grid;
place-items: center;
padding: 16px;
background: rgba(15, 23, 42, 0.35);
}
.dialog {
width: min(880px, 100%);
max-height: min(88vh, 880px);
display: flex;
flex-direction: column;
background: #fff;
border: 1px solid var(--line);
border-radius: var(--radius, 10px);
box-shadow: 0 18px 48px rgba(15, 23, 42, 0.16);
overflow: hidden;
}
.head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 16px;
border-bottom: 1px solid var(--line);
flex-shrink: 0;
background: #fff;
z-index: 10;
}
.head h2 {
margin: 0;
font-size: 16px;
font-weight: 500;
color: var(--ink);
line-height: 1.4;
}
.close {
width: 36px;
height: 36px;
border: 1px solid var(--line);
border-radius: var(--radius, 10px);
background: #fff;
color: var(--muted);
display: grid;
place-items: center;
cursor: pointer;
transition: all var(--transition-fast);
}
.close:hover {
background: var(--surface-subtle);
color: var(--ink);
border-color: var(--line-strong);
}
.body {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
padding: 16px;
box-sizing: border-box;
}
.body :deep(.crm-page.embedded),
.body :deep(.page.embedded),
.body :deep(.product-form-page.embedded),
.body :deep(.company-form-page.embedded) {
display: flex;
flex-direction: column;
flex: 1 1 auto;
min-height: 100%;
}
.body :deep(.page.embedded > .form),
.body :deep(.page.embedded > form),
.body :deep(.crm-page.embedded > .form),
.body :deep(.crm-page.embedded > form),
.body :deep(.crm-page.embedded > .crm-form) {
flex: 1 1 auto;
min-height: 0;
}
.body :deep(.embed-actions),
.body :deep(.embedded-actions),
.body :deep(.form-bottom-actions),
.body :deep(.form-footer-actions) {
order: 99;
flex-shrink: 0;
position: sticky;
bottom: -16px;
margin-top: auto;
margin-inline: -16px;
margin-bottom: -16px;
display: flex;
align-items: center;
justify-content: flex-start;
gap: 12px;
padding: 16px;
background: #fff;
border-top: 1px solid var(--line);
z-index: 10;
box-shadow: 0 -4px 14px rgba(15, 23, 42, 0.05);
}
.body :deep(.embed-actions .btn),
.body :deep(.embedded-actions .btn),
.body :deep(.embed-actions .ui-btn),
.body :deep(.embedded-actions .ui-btn),
.body :deep(.form-bottom-actions .btn),
.body :deep(.form-bottom-actions .ui-btn),
.body :deep(.form-footer-actions .btn),
.body :deep(.form-footer-actions .ui-btn) {
border-radius: var(--radius, 10px);
}
.foot {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 12px;
padding: 16px;
border-top: 1px solid var(--line);
flex-shrink: 0;
background: #fff;
z-index: 10;
}
@media (max-width: 900px) {
.backdrop {
padding: 0;
place-items: stretch;
}
.dialog {
width: 100%;
height: 100%;
max-height: 100dvh;
border-radius: 0;
border: 0;
}
.head {
padding: 16px;
}
.body {
padding: 16px;
}
.foot {
padding: 16px calc(16px + env(safe-area-inset-bottom));
}
}
</style>
+122
View File
@@ -0,0 +1,122 @@
<script setup lang="ts">
import UiIcon from '@/components/UiIcon.vue';
withDefaults(
defineProps<{
title?: string;
lead?: string;
description?: string;
backTo?: string | object;
}>(),
{},
);
</script>
<template>
<header class="ui-page-header">
<div class="header-main">
<RouterLink v-if="backTo" :to="backTo" class="back-link" title="بازگشت">
<UiIcon name="arrow-right" :size="18" />
</RouterLink>
<div class="titles">
<h1 v-if="title" class="title">{{ title }}</h1>
<slot v-else name="title" />
<p v-if="lead || description" class="lead">{{ lead || description }}</p>
<slot v-else name="lead" />
</div>
</div>
<div v-if="$slots.actions" class="actions">
<slot name="actions" />
</div>
</header>
</template>
<style scoped>
.ui-page-header {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--sp-4);
min-width: 0;
width: 100%;
}
.header-main {
display: flex;
align-items: center;
gap: var(--sp-3);
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
justify-content: center;
width: var(--control-h-md);
height: var(--control-h-md);
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
color: var(--ink-secondary);
transition: background var(--transition-fast), border-color var(--transition-fast);
}
.back-link:hover {
background: var(--surface-subtle);
border-color: var(--line-strong);
color: var(--accent-deep);
}
.titles {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.title {
margin: 0;
font-size: var(--fs-2xl);
font-weight: var(--fw-extrabold);
color: var(--ink);
line-height: var(--lh-tight);
}
.lead {
margin: 0;
font-size: var(--fs-sm);
color: var(--muted);
line-height: var(--lh-normal);
}
.actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--sp-2);
}
@media (max-width: 900px) {
.ui-page-header {
flex-direction: column;
align-items: stretch;
gap: var(--sp-3);
}
.title {
font-size: var(--fs-xl);
}
.actions {
justify-content: stretch;
}
.actions > * {
flex: 1 1 auto;
}
}
</style>
+142
View File
@@ -0,0 +1,142 @@
<script setup lang="ts">
import { computed } from 'vue';
import UiButton from './UiButton.vue';
import UiIcon from '@/components/UiIcon.vue';
const props = withDefaults(
defineProps<{
page: number;
totalPages?: number;
totalItems?: number;
pageSize?: number;
}>(),
{
page: 1,
},
);
const emit = defineEmits<{
'update:page': [page: number];
change: [page: number];
}>();
const effectiveTotalPages = computed(() => {
if (props.totalPages != null) return Math.max(1, props.totalPages);
if (props.totalItems != null && props.pageSize != null && props.pageSize > 0) {
return Math.max(1, Math.ceil(props.totalItems / props.pageSize));
}
return 1;
});
function goTo(p: number) {
if (p < 1 || p > effectiveTotalPages.value || p === props.page) return;
emit('update:page', p);
emit('change', p);
}
</script>
<template>
<nav v-if="effectiveTotalPages > 1 || totalItems !== undefined" class="ui-pagination" aria-label="صفحه‌بندی">
<div class="pagination-info">
<span v-if="totalItems !== undefined">
مجموع: <strong>{{ totalItems }}</strong> مورد
</span>
<span v-if="effectiveTotalPages > 1" class="page-count">
(صفحه {{ page }} از {{ effectiveTotalPages }})
</span>
</div>
<div v-if="effectiveTotalPages > 1" class="pagination-controls">
<UiButton
variant="ghost"
size="sm"
:disabled="page <= 1"
title="صفحه اول"
@click="goTo(1)"
>
<UiIcon name="chevrons-right" :size="14" />
</UiButton>
<UiButton
variant="ghost"
size="sm"
:disabled="page <= 1"
title="صفحه قبل"
@click="goTo(page - 1)"
>
<UiIcon name="chevron-right" :size="14" />
قبلی
</UiButton>
<span class="current-indicator">
{{ page }} / {{ effectiveTotalPages }}
</span>
<UiButton
variant="ghost"
size="sm"
:disabled="page >= effectiveTotalPages"
title="صفحه بعد"
@click="goTo(page + 1)"
>
بعدی
<UiIcon name="chevron-left" :size="14" />
</UiButton>
<UiButton
variant="ghost"
size="sm"
:disabled="page >= effectiveTotalPages"
title="صفحه آخر"
@click="goTo(effectiveTotalPages)"
>
<UiIcon name="chevrons-left" :size="14" />
</UiButton>
</div>
</nav>
</template>
<style scoped>
.ui-pagination {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--sp-3);
padding-top: var(--sp-4);
width: 100%;
}
.pagination-info {
font-size: var(--fs-sm);
color: var(--muted);
display: flex;
align-items: center;
gap: var(--sp-2);
}
.page-count {
color: var(--muted-light);
}
.pagination-controls {
display: inline-flex;
align-items: center;
gap: var(--sp-1);
}
.current-indicator {
padding: 0 var(--sp-2);
font-size: var(--fs-xs);
font-weight: var(--fw-bold);
color: var(--ink-secondary);
}
@media (max-width: 900px) {
.ui-pagination {
flex-direction: column;
align-items: center;
gap: var(--sp-3);
}
}
</style>
+68
View File
@@ -0,0 +1,68 @@
<script setup lang="ts">
import UiIcon from '@/components/UiIcon.vue';
withDefaults(
defineProps<{
placeholder?: string;
}>(),
{ placeholder: 'جستجو...' },
);
const model = defineModel<string>({ default: '' });
</script>
<template>
<label class="ui-search">
<span class="sr">جستجو</span>
<input
v-model="model"
type="search"
:placeholder="placeholder"
/>
<UiIcon name="search" :size="16" />
</label>
</template>
<style scoped>
.ui-search {
display: flex;
align-items: center;
gap: 0.45rem;
min-width: 0;
height: var(--control-h);
min-height: var(--control-h);
padding: 0 0.75rem;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
color: var(--muted);
box-sizing: border-box;
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}
.ui-search input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: transparent;
color: var(--ink);
font: inherit;
font-size: var(--fs-sm);
padding: 0;
}
.ui-search:focus-within {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 2px var(--accent-soft);
}
.sr {
position: absolute;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
</style>
@@ -0,0 +1,65 @@
<script setup lang="ts" generic="T extends string">
defineProps<{
options: Array<{ value: T; label: string; icon?: 'grid' | 'list' }>;
}>();
const model = defineModel<T>({ required: true });
</script>
<template>
<div class="ui-seg" role="group">
<button
v-for="opt in options"
:key="opt.value"
type="button"
class="seg"
:class="{ on: model === opt.value }"
:aria-pressed="model === opt.value"
@click="model = opt.value"
>
<slot name="icon" :option="opt" />
<span class="seg-label">{{ opt.label }}</span>
</button>
</div>
</template>
<style scoped>
.ui-seg {
display: inline-flex;
align-items: center;
min-height: var(--control-h);
padding: 3px;
gap: 2px;
background: #e8eef1;
border-radius: var(--radius);
}
.seg {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
min-height: calc(var(--control-h) - 6px);
padding: 0 0.75rem;
border: 0;
border-radius: calc(var(--radius) - 2px);
background: transparent;
color: #7b8794;
font: inherit;
font-weight: 700;
font-size: 0.82rem;
cursor: pointer;
white-space: nowrap;
}
.seg.on {
background: #fff;
color: var(--accent-deep);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);
}
.seg:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
</style>
+105
View File
@@ -0,0 +1,105 @@
<script setup lang="ts">
import UiIcon from '@/components/UiIcon.vue';
withDefaults(
defineProps<{
disabled?: boolean;
error?: boolean | string;
size?: 'sm' | 'md' | 'lg';
id?: string;
required?: boolean;
}>(),
{
disabled: false,
size: 'md',
required: false,
},
);
const model = defineModel<string>({ default: '' });
</script>
<template>
<label class="ui-select" :class="[size, { disabled, hasError: !!error }]">
<select :id="id" v-model="model" :disabled="disabled" :required="required" :aria-invalid="!!error">
<slot />
</select>
<UiIcon class="chev" name="chevron" :size="size === 'sm' ? 14 : 16" />
</label>
</template>
<style scoped>
.ui-select {
position: relative;
display: block;
min-width: 0;
width: 100%;
}
.ui-select select {
appearance: none;
width: 100%;
min-height: var(--control-h-md);
padding: 0 2rem 0 var(--sp-3);
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
color: var(--ink);
font: inherit;
font-weight: var(--fw-medium);
font-size: var(--fs-base);
cursor: pointer;
box-sizing: border-box;
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}
.ui-select.sm select {
min-height: var(--control-h-sm);
padding: 0 1.75rem 0 var(--sp-2);
border-radius: var(--radius-sm);
font-size: var(--fs-xs);
}
.ui-select.md select {
min-height: var(--control-h-md);
padding: 0 2rem 0 var(--sp-3);
border-radius: var(--radius);
font-size: var(--fs-base);
}
.ui-select.lg select {
min-height: var(--control-h-lg);
padding: 0 2.25rem 0 var(--sp-4);
border-radius: var(--radius-md);
font-size: var(--fs-md);
}
.ui-select select:focus {
outline: 2px solid var(--accent-soft);
border-color: var(--accent);
}
.ui-select.hasError select {
border-color: var(--danger);
}
.ui-select.hasError select:focus {
outline: 2px solid var(--danger-soft);
border-color: var(--danger);
}
.ui-select.disabled select {
background: var(--surface-subtle);
opacity: 0.65;
cursor: not-allowed;
}
.chev {
position: absolute;
left: 0.65rem;
top: 50%;
color: var(--muted);
pointer-events: none;
transform: translateY(-50%) rotate(-90deg);
}
</style>
+81
View File
@@ -0,0 +1,81 @@
<script setup lang="ts">
withDefaults(
defineProps<{
placeholder?: string;
disabled?: boolean;
readonly?: boolean;
required?: boolean;
error?: boolean | string;
rows?: number;
maxlength?: number;
id?: string;
}>(),
{
rows: 3,
disabled: false,
readonly: false,
required: false,
},
);
const model = defineModel<string>({ default: '' });
</script>
<template>
<textarea
:id="id"
v-model="model"
class="ui-textarea"
:class="{ disabled, hasError: !!error }"
:placeholder="placeholder"
:disabled="disabled"
:readonly="readonly"
:required="required"
:rows="rows"
:maxlength="maxlength"
:aria-invalid="!!error"
/>
</template>
<style scoped>
.ui-textarea {
width: 100%;
min-width: 0;
box-sizing: border-box;
padding: var(--sp-3);
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
color: var(--ink);
font: inherit;
font-size: var(--fs-base);
line-height: var(--lh-normal);
resize: vertical;
min-height: 80px;
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}
.ui-textarea::placeholder {
color: var(--muted-light);
}
.ui-textarea:focus {
outline: 2px solid var(--accent-soft);
border-color: var(--accent);
}
.ui-textarea.hasError {
border-color: var(--danger);
}
.ui-textarea.hasError:focus {
outline: 2px solid var(--danger-soft);
border-color: var(--danger);
}
.ui-textarea.disabled {
background: var(--surface-subtle);
opacity: 0.65;
cursor: not-allowed;
}
</style>
+15
View File
@@ -0,0 +1,15 @@
export { default as UiButton } from './UiButton.vue';
export { default as UiInput } from './UiInput.vue';
export { default as UiTextarea } from './UiTextarea.vue';
export { default as UiSelect } from './UiSelect.vue';
export { default as UiField } from './UiField.vue';
export { default as UiCard } from './UiCard.vue';
export { default as UiModal } from './UiModal.vue';
export { default as UiPageHeader } from './UiPageHeader.vue';
export { default as UiBadge } from './UiBadge.vue';
export { default as UiPagination } from './UiPagination.vue';
export { default as UiEmptyState } from './UiEmptyState.vue';
export { default as UiSearch } from './UiSearch.vue';
export { default as UiFilterBar } from './UiFilterBar.vue';
export { default as UiSegmented } from './UiSegmented.vue';
export { default as UiChart, CHART_PALETTE, type UiChartOption } from './UiChart.vue';
File diff suppressed because it is too large Load Diff
+49 -7
View File
@@ -206,22 +206,64 @@ export function updateDealStage(
});
}
export type PipelineBoardFilter = {
query?: string;
amountMin?: number | null;
amountMax?: number | null;
};
export function filterStagesByQuery(
stages: PipelineStage[],
query: string,
): PipelineStage[] {
const q = query.trim().toLowerCase();
if (!q) return stages;
return filterStages(stages, { query });
}
export function filterStages(
stages: PipelineStage[],
filter: PipelineBoardFilter,
): PipelineStage[] {
const q = filter.query?.trim().toLowerCase() ?? '';
const min = filter.amountMin;
const max = filter.amountMax;
const hasFilter =
Boolean(q) ||
(min != null && !Number.isNaN(min)) ||
(max != null && !Number.isNaN(max));
if (!hasFilter) return stages;
return stages.map((stage) => ({
...stage,
deals: stage.deals.filter(
(d) =>
d.title.toLowerCase().includes(q) ||
d.description.toLowerCase().includes(q),
),
deals: stage.deals.filter((d) => {
if (
q &&
!d.title.toLowerCase().includes(q) &&
!d.description.toLowerCase().includes(q)
) {
return false;
}
if (min != null && !Number.isNaN(min) && d.amount < min) return false;
if (max != null && !Number.isNaN(max) && d.amount > max) return false;
return true;
}),
}));
}
export function toFaDealCount(n: number): string {
return `${new Intl.NumberFormat('fa-IR').format(n)} معامله`;
}
/** جابه‌جایی یک ستون به ایندکس جدید */
export function moveStageToIndex(
stages: PipelineStage[],
stageId: string,
toIndex: number,
): PipelineStage[] {
const from = stages.findIndex((s) => s.id === stageId);
if (from < 0) return stages;
const next = [...stages];
const [item] = next.splice(from, 1);
if (!item) return stages;
const clamped = Math.max(0, Math.min(toIndex, next.length));
next.splice(clamped, 0, item);
return next;
}
+15
View File
@@ -123,6 +123,21 @@ export const router = createRouter({
name: 'invoice-detail',
component: () => import('@/views/InvoiceFormView.vue'),
},
{
path: 'inventory',
name: 'inventory',
component: () => import('@/views/InventoryView.vue'),
},
{
path: 'cheques',
name: 'cheques',
component: () => import('@/views/ChequesView.vue'),
},
{
path: 'commissions',
name: 'commissions',
component: () => import('@/views/CommissionsView.vue'),
},
{
path: 'pipeline',
name: 'pipeline',
+3 -3
View File
@@ -70,12 +70,12 @@
font-display: swap;
}
/* map 800 → Black */
/* map 800 → Bold (avoid oversized heavy Black in UI) */
@font-face {
font-family: "IRANSans";
src:
url("../assets/fonts/iranSans/woff2/IRANSansWeb(FaNum)_Black.woff2") format("woff2"),
url("../assets/fonts/iranSans/woff/IRANSansWeb(FaNum)_Black.woff") format("woff");
url("../assets/fonts/iranSans/woff2/IRANSansWeb(FaNum)_Bold.woff2") format("woff2"),
url("../assets/fonts/iranSans/woff/IRANSansWeb(FaNum)_Bold.woff") format("woff");
font-weight: 800;
font-style: normal;
font-display: swap;
+147 -19
View File
@@ -1,17 +1,131 @@
@import "./fonts.css";
@import "./tokens.css";
:root {
--bg: #f4f7f8;
/* Surface & Background */
--bg: #f8fafc;
--surface: #ffffff;
--ink: #0f172a;
--muted: #64748b;
--line: #e2e8f0;
--accent: #0d9488;
--accent-soft: #ccfbf1;
--danger: #b42318;
--shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
--radius: 18px;
--surface-subtle: #f1f5f9;
--surface-hover: #f8fafc;
/* Typography & Foreground */
--font: "IRANSans", Tahoma, sans-serif;
--ink: #0f172a;
--ink-secondary: #334155;
--muted: #64748b;
--muted-light: #94a3b8;
--line: #e2e8f0;
--line-light: #f1f5f9;
--line-strong: #cbd5e1;
/* Accent / Primary (Teal) */
--accent: #14b8a6;
--accent-hover: #0d9488;
--accent-deep: #0f766e;
--accent-soft: #ccfbf1;
--accent-subtle: #f0fdfa;
--accent-contrast: #ffffff;
/* Semantics */
--danger: #b42318;
--danger-hover: #991b1b;
--danger-soft: #fee2e2;
--danger-deep: #7f1d1d;
--success: #10b981;
--success-soft: #d1fae5;
--success-deep: #047857;
--warning: #f59e0b;
--warning-soft: #fef3c7;
--warning-deep: #b45309;
--info: #0284c7;
--info-soft: #e0f2fe;
--info-deep: #0369a1;
/* Typography Scale */
--fs-xs: 0.75rem; /* 12px */
--fs-sm: 0.8125rem; /* 13px */
--fs-base: 0.875rem; /* 14px */
--fs-md: 0.9375rem; /* 15px */
--fs-lg: 1.0625rem; /* 17px */
--fs-xl: 1.25rem; /* 20px */
--fs-2xl: 1.5rem; /* 24px */
--fs-3xl: 1.75rem; /* 28px */
--fw-normal: 400;
--fw-medium: 500;
--fw-semibold: 600;
--fw-bold: 700;
--fw-extrabold: 700;
--lh-tight: 1.25;
--lh-normal: 1.5;
--lh-relaxed: 1.625;
/* Spacing Scale */
--sp-1: 0.25rem; /* 4px */
--sp-2: 0.5rem; /* 8px */
--sp-3: 0.75rem; /* 12px */
--sp-4: 1rem; /* 16px */
--sp-5: 1.25rem; /* 20px */
--sp-6: 1.5rem; /* 24px */
--sp-8: 2rem; /* 32px */
--sp-10: 2.5rem; /* 40px */
/* Radius - Single Source of Truth (Globally 10px as requested) */
--radius: 10px;
--radius-xs: var(--radius);
--radius-sm: var(--radius);
--radius-md: var(--radius);
--radius-lg: var(--radius);
--radius-xl: var(--radius);
--radius-2xl: var(--radius);
--radius-full: 9999px;
/* Control Dimensions */
--control-h-sm: 30px;
--control-h: 36px;
--control-h-md: 36px;
--control-h-lg: 42px;
--pad-modal: 16px;
/* Shadows */
--shadow-xs: 0 1px 2px rgba(15, 23, 42, 0.05);
--shadow-sm: 0 1px 3px rgba(15, 23, 42, 0.08), 0 1px 2px rgba(15, 23, 42, 0.04);
--shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
--shadow-md: 0 4px 12px rgba(15, 23, 42, 0.08);
--shadow-lg: 0 12px 32px rgba(15, 23, 42, 0.12);
--shadow-xl: 0 20px 48px rgba(15, 23, 42, 0.16);
/* Transitions */
--transition-fast: 150ms ease;
--transition-normal: 200ms ease;
/* Z-index */
--z-dropdown: 50;
--z-sticky: 60;
--z-modal-backdrop: 80;
--z-modal: 90;
--z-toast: 100;
/* Compatibility aliases for legacy views */
--color-border: var(--line);
--color-border-light: var(--line-light);
--color-text: var(--ink);
--color-text-primary: var(--ink);
--color-text-secondary: var(--ink-secondary);
--color-text-muted: var(--muted);
--color-text-emphasis: var(--ink);
--color-surface: var(--surface);
--color-surface-sunken: var(--surface-subtle);
--color-primary: var(--accent);
--color-primary-dark: var(--accent-deep);
--color-primary-light: var(--accent-soft);
--color-primary-surface: var(--accent-subtle);
--color-danger: var(--danger);
--color-danger-surface: var(--danger-soft);
--color-warning: var(--warning);
}
* {
@@ -60,12 +174,21 @@ textarea {
.btn {
border: 0;
border-radius: 12px;
padding: 0.75rem 1.1rem;
border-radius: var(--radius);
height: var(--control-h);
min-height: var(--control-h);
padding: 0 0.85rem;
cursor: pointer;
background: var(--accent);
color: white;
font-weight: 600;
font-size: var(--fs-sm);
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
box-sizing: border-box;
transition: background var(--transition-fast), border-color var(--transition-fast), opacity var(--transition-fast);
}
.btn:disabled {
@@ -97,15 +220,24 @@ textarea {
}
.field input,
.field select,
.field textarea {
.field select {
border: 1px solid var(--line);
border-radius: 12px;
padding: 0.8rem 0.95rem;
border-radius: var(--radius);
min-height: var(--control-h);
padding: 0 0.85rem;
background: #fff;
width: 100%;
}
.field textarea {
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0.7rem 0.85rem;
background: #fff;
width: 100%;
min-height: 88px;
}
.field input:focus,
.field select:focus,
.field textarea:focus {
@@ -122,8 +254,4 @@ textarea {
h1 {
font-size: clamp(1.35rem, 5vw, 1.75rem);
}
.btn {
padding: 0.7rem 0.95rem;
}
}
+496
View File
@@ -0,0 +1,496 @@
/**
* Montact CRM (منتکت) Design System - Core Tokens & Utilities
* RTL-first, IRANSans typography, unified spacing, controls & surfaces.
*/
/* ==========================================================================
Page Layout
========================================================================== */
.crm-page,
.page,
.dashboard,
.profile,
.notes-page {
display: flex;
flex-direction: column;
gap: var(--sp-5);
padding: 0;
margin: 0;
max-width: 100%;
width: 100%;
min-width: 0;
box-sizing: border-box;
}
.crm-page.narrow,
.crm-page.wide,
.crm-page.full {
max-width: 100%;
}
.crm-page.embedded {
padding: 0;
gap: var(--sp-4);
}
/* ==========================================================================
Page Header
========================================================================== */
.crm-page-header {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--sp-4);
min-width: 0;
}
.crm-page-header-titles {
display: flex;
flex-direction: column;
gap: var(--sp-1);
min-width: 0;
}
.crm-page-title {
margin: 0;
font-size: var(--fs-xl);
font-weight: var(--fw-bold);
color: var(--ink);
line-height: var(--lh-tight);
}
.crm-page-lead {
margin: 0;
font-size: var(--fs-sm);
color: var(--muted);
line-height: var(--lh-normal);
}
.crm-header-actions {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--sp-2);
}
/* ==========================================================================
Toolbar & Filter Bar
========================================================================== */
.crm-toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--sp-3);
min-width: 0;
width: 100%;
}
.crm-toolbar-stretch,
.crm-toolbar .toolbar-search,
.crm-toolbar .search-box,
.crm-toolbar .crm-search {
flex: 1 1 200px;
min-width: 180px;
max-width: 380px;
}
.crm-toolbar .toolbar-select,
.crm-toolbar .ui-select:not(.block) {
width: auto;
min-width: 130px;
max-width: 220px;
}
.crm-toolbar .ui-btn,
.crm-toolbar .btn {
flex-shrink: 0;
}
/* ==========================================================================
Card & Container Surfaces
========================================================================== */
.crm-card {
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow-xs);
padding: var(--sp-5);
box-sizing: border-box;
transition: box-shadow var(--transition-fast), border-color var(--transition-fast);
}
.crm-card-sm {
padding: var(--sp-3);
}
.crm-card-lg {
padding: var(--sp-6);
}
.crm-card-interactive:hover {
border-color: var(--line-strong);
box-shadow: var(--shadow-sm);
}
.crm-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-3);
padding-bottom: var(--sp-3);
margin-bottom: var(--sp-4);
border-bottom: 1px solid var(--line-light);
}
.crm-card-title {
margin: 0;
font-size: var(--fs-md);
font-weight: var(--fw-semibold);
color: var(--ink);
}
.crm-card-actions {
display: flex;
align-items: center;
gap: var(--sp-2);
}
/* ==========================================================================
Forms & Field Layouts
========================================================================== */
.crm-form {
display: flex;
flex-direction: column;
gap: var(--sp-5);
width: 100%;
}
.crm-form-section {
display: flex;
flex-direction: column;
gap: var(--sp-3);
}
.crm-form-section-title {
margin: 0;
font-size: var(--fs-md);
font-weight: var(--fw-semibold);
color: var(--ink);
padding-bottom: var(--sp-2);
border-bottom: 1px solid var(--line-light);
}
.crm-form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
gap: var(--sp-4);
width: 100%;
}
.crm-form-grid-2 {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: var(--sp-4);
width: 100%;
}
.crm-form-grid-3 {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: var(--sp-4);
width: 100%;
}
.crm-form-grid-4 {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: var(--sp-4);
width: 100%;
}
.crm-col-span-2 {
grid-column: span 2;
}
.crm-col-span-full {
grid-column: 1 / -1;
}
.crm-field {
display: flex;
flex-direction: column;
gap: var(--sp-1);
min-width: 0;
}
.crm-label {
display: flex;
align-items: center;
gap: var(--sp-1);
font-size: var(--fs-sm);
font-weight: var(--fw-medium);
color: var(--ink-secondary);
}
.crm-required-indicator {
color: var(--danger);
}
.crm-hint {
font-size: var(--fs-xs);
color: var(--muted);
line-height: var(--lh-normal);
}
.crm-field-error {
font-size: var(--fs-xs);
color: var(--danger);
font-weight: var(--fw-medium);
display: flex;
align-items: center;
gap: var(--sp-1);
}
.crm-form-actions {
display: flex;
align-items: center;
justify-content: flex-start;
gap: var(--sp-3);
padding-top: var(--sp-4);
margin-top: var(--sp-2);
border-top: 1px solid var(--line-light);
flex-wrap: wrap;
}
/* ==========================================================================
Data Table
========================================================================== */
.crm-table-container {
width: 100%;
overflow-x: auto;
background: var(--surface);
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: var(--shadow-xs);
-webkit-overflow-scrolling: touch;
}
.crm-table {
width: 100%;
border-collapse: collapse;
text-align: right;
font-size: var(--fs-sm);
}
.crm-table th {
background: var(--surface-subtle);
color: var(--muted);
font-weight: var(--fw-semibold);
padding: var(--sp-3) var(--sp-4);
border-bottom: 1px solid var(--line);
white-space: nowrap;
}
.crm-table td {
padding: var(--sp-3) var(--sp-4);
border-bottom: 1px solid var(--line-light);
color: var(--ink);
vertical-align: middle;
}
.crm-table tbody tr:last-child td {
border-bottom: none;
}
.crm-table tbody tr:hover td {
background: var(--surface-hover);
}
.crm-table-actions {
display: inline-flex;
align-items: center;
gap: var(--sp-1);
white-space: nowrap;
}
/* ==========================================================================
Badges & Status Indicators
========================================================================== */
.crm-badge {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
padding: 0.2rem 0.6rem;
border-radius: var(--radius-full);
font-size: var(--fs-xs);
font-weight: var(--fw-semibold);
line-height: 1.2;
white-space: nowrap;
border: 1px solid transparent;
}
.crm-badge-sm {
padding: 0.1rem 0.45rem;
font-size: 0.7rem;
}
.crm-badge-neutral {
background: var(--surface-subtle);
color: var(--ink-secondary);
border-color: var(--line);
}
.crm-badge-accent,
.crm-badge-primary {
background: var(--accent-soft);
color: var(--accent-deep);
border-color: color-mix(in srgb, var(--accent) 30%, transparent);
}
.crm-badge-success {
background: var(--success-soft);
color: var(--success-deep);
border-color: color-mix(in srgb, var(--success) 30%, transparent);
}
.crm-badge-warning {
background: var(--warning-soft);
color: var(--warning-deep);
border-color: color-mix(in srgb, var(--warning) 30%, transparent);
}
.crm-badge-danger {
background: var(--danger-soft);
color: var(--danger);
border-color: color-mix(in srgb, var(--danger) 30%, transparent);
}
.crm-badge-info {
background: var(--info-soft);
color: var(--info-deep);
border-color: color-mix(in srgb, var(--info) 30%, transparent);
}
/* ==========================================================================
Pagination
========================================================================== */
.crm-pagination {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: var(--sp-3);
padding-top: var(--sp-3);
}
.crm-pagination-info {
font-size: var(--fs-sm);
color: var(--muted);
}
.crm-pagination-nav {
display: inline-flex;
align-items: center;
gap: var(--sp-1);
}
/* ==========================================================================
Empty States
========================================================================== */
.crm-empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: var(--sp-10) var(--sp-6);
gap: var(--sp-3);
color: var(--muted);
background: var(--surface);
border: 1px dashed var(--line-strong);
border-radius: var(--radius);
}
.crm-empty-title {
margin: 0;
font-size: var(--fs-md);
font-weight: var(--fw-semibold);
color: var(--ink);
}
.crm-empty-desc {
margin: 0;
font-size: var(--fs-sm);
max-width: 360px;
line-height: var(--lh-relaxed);
}
/* ==========================================================================
Typography Utilities
========================================================================== */
.crm-text-xs { font-size: var(--fs-xs); }
.crm-text-sm { font-size: var(--fs-sm); }
.crm-text-base { font-size: var(--fs-base); }
.crm-text-md { font-size: var(--fs-md); }
.crm-text-lg { font-size: var(--fs-lg); }
.crm-text-xl { font-size: var(--fs-xl); }
.crm-text-2xl { font-size: var(--fs-2xl); }
.crm-font-normal { font-weight: var(--fw-normal); }
.crm-font-medium { font-weight: var(--fw-medium); }
.crm-font-semibold { font-weight: var(--fw-semibold); }
.crm-font-bold { font-weight: var(--fw-bold); }
.crm-font-extrabold { font-weight: var(--fw-extrabold); }
.crm-text-ink { color: var(--ink); }
.crm-text-secondary { color: var(--ink-secondary); }
.crm-text-muted { color: var(--muted); }
.crm-text-accent { color: var(--accent); }
.crm-text-danger { color: var(--danger); }
.crm-text-success { color: var(--success); }
.crm-text-warning { color: var(--warning); }
/* ==========================================================================
Responsive Breakpoints
========================================================================== */
@media (max-width: 900px) {
.crm-page {
padding: 0;
gap: var(--sp-4);
}
.crm-page-title {
font-size: var(--fs-xl);
}
.crm-page-header {
flex-direction: column;
align-items: stretch;
gap: var(--sp-3);
}
.crm-header-actions {
justify-content: stretch;
}
.crm-header-actions > * {
flex: 1 1 auto;
}
.crm-form-grid-2,
.crm-form-grid-3,
.crm-form-grid-4 {
grid-template-columns: 1fr;
}
.crm-col-span-2 {
grid-column: auto;
}
.crm-pagination {
flex-direction: column;
align-items: center;
}
}
+10 -10
View File
@@ -405,7 +405,7 @@ onMounted(() => {
h1 {
margin: 0 0 0.3rem;
font-size: clamp(1.45rem, 2.5vw, 1.85rem);
font-weight: 800;
font-weight: 600;
}
h2 {
@@ -426,9 +426,9 @@ h2 {
align-items: center;
justify-content: center;
gap: 0.35rem;
min-height: 42px;
padding: 0.55rem 1rem;
border-radius: 12px;
min-height: var(--control-h);
padding: 0 0.95rem;
border-radius: var(--radius);
font-weight: 700;
border: 1px solid transparent;
cursor: pointer;
@@ -461,7 +461,7 @@ h2 {
gap: 0.75rem;
flex-wrap: wrap;
background: #fff;
border-radius: 18px;
border-radius: var(--radius);
padding: 0.75rem 0.95rem;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
}
@@ -493,7 +493,7 @@ h2 {
.calendar {
background: #fff;
border-radius: 18px;
border-radius: var(--radius);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
padding: 0.85rem;
min-width: 0;
@@ -519,7 +519,7 @@ h2 {
.day {
min-height: 92px;
border: 1px solid #e2e8f0;
border-radius: 14px;
border-radius: var(--radius);
background: #f8fafc;
padding: 0.45rem;
text-align: right;
@@ -553,7 +553,7 @@ h2 {
}
.day.has .num {
font-weight: 800;
font-weight: 600;
color: #0f766e;
}
@@ -594,7 +594,7 @@ h2 {
.day-panel {
background: #fff;
border-radius: 18px;
border-radius: var(--radius);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
padding: 1rem;
display: grid;
@@ -623,7 +623,7 @@ h2 {
gap: 0.15rem;
padding: 0.75rem 0.85rem;
border: 1px solid #f1f5f9;
border-radius: 14px;
border-radius: var(--radius);
background: #f8fafc;
text-decoration: none;
color: inherit;
+151 -75
View File
@@ -10,7 +10,14 @@ import {
startOfLocalDay,
toFaDigits,
} from '@/lib/jalali';
import {
UiButton,
UiModal,
UiPageHeader,
UiPagination,
} from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue';
import ActivityFormView from '@/views/ActivityFormView.vue';
import type {
ActivityDto,
ActivityFilter,
@@ -62,6 +69,10 @@ const q = ref(typeof route.query.q === 'string' ? route.query.q : '');
const typeFilter = ref<TypeFilter>('all');
const filterOpen = ref(false);
const ideasOpen = ref(false);
const activityModal = ref<{
type?: ActivityType;
title?: string;
} | null>(null);
const menuId = ref<string | null>(null);
const counts = ref<Record<ActivityFilter, number>>({
today: 0,
@@ -112,8 +123,11 @@ const pageCount = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE))
const filterLabel = computed(() => TABS.find((t) => t.key === filter.value)?.label ?? 'امروز');
const trulyEmpty = computed(() => !loading.value && counts.value.all === 0 && !q.value.trim());
const listEmpty = computed(() => !loading.value && !items.value.length);
const rangeFrom = computed(() => (total.value ? (page.value - 1) * PAGE_SIZE + 1 : 0));
const rangeTo = computed(() => Math.min(page.value * PAGE_SIZE, total.value));
function isLastItem(id: string) {
const rows = items.value;
return rows.length > 0 && rows[rows.length - 1]?.id === id;
}
function isOverdue(item: ActivityDto) {
if (item.status !== 'open' || !item.dueAt) return false;
@@ -270,23 +284,23 @@ onMounted(() => {
<span>فعالیت‌ها</span>
</nav>
<header class="page-head">
<div>
<p class="eyebrow">پیگیری</p>
<h1>فعالیت‌ها</h1>
<p class="lead">تماس، جلسه و وظیفه — امروز و عقب‌افتاده‌ها یکجا.</p>
</div>
<div class="head-actions">
<RouterLink class="btn primary" :to="{ name: 'activity-new' }">
<span>+</span>
<UiPageHeader
title="فعالیت‌ها"
lead="تماس، جلسه و وظیفه — امروز و عقب‌افتاده‌ها یکجا."
>
<template #actions>
<UiButton variant="primary" @click="activityModal = {}">
<UiIcon name="plus" :size="16" />
فعالیت جدید
</UiButton>
<RouterLink :to="{ name: 'activities-calendar' }">
<UiButton variant="ghost">
<UiIcon name="calendar" :size="16" />
تقویم
</UiButton>
</RouterLink>
<RouterLink class="btn ghost" :to="{ name: 'activities-calendar' }">
<UiIcon name="calendar" :size="18" />
تقویم
</RouterLink>
</div>
</header>
</template>
</UiPageHeader>
<div class="tabs" role="tablist" aria-label="فیلتر فعالیت">
<button
@@ -355,24 +369,23 @@ onMounted(() => {
: 'فیلتر یا جستجو را عوض کنید، یا یک فعالیت جدید بسازید.'
}}
</p>
<RouterLink class="btn primary wide" :to="{ name: 'activity-new' }">
<span>+</span>
<UiButton block type="button" @click="activityModal = {}">
{{ trulyEmpty ? 'اولین فعالیتت رو ثبت کن' : 'فعالیت جدید' }}
</RouterLink>
</UiButton>
<button class="btn ghost wide" type="button" @click="ideasOpen = !ideasOpen">
<UiIcon name="lightbulb" :size="18" />
ایده‌هایی برای شروع
</button>
<div v-if="ideasOpen" class="idea-list">
<RouterLink :to="{ name: 'activity-new', query: { type: 'call', title: 'تماس پیگیری' } }">
<button type="button" @click="activityModal = { type: 'call', title: 'تماس پیگیری' }">
تماس پیگیری
</RouterLink>
<RouterLink :to="{ name: 'activity-new', query: { type: 'meeting', title: 'جلسه دمو' } }">
</button>
<button type="button" @click="activityModal = { type: 'meeting', title: 'جلسه دمو' }">
جلسه دمو
</RouterLink>
<RouterLink :to="{ name: 'activity-new', query: { type: 'task', title: 'وظیفه یادآوری' } }">
</button>
<button type="button" @click="activityModal = { type: 'task', title: 'وظیفه یادآوری' }">
وظیفه یادآوری
</RouterLink>
</button>
</div>
</div>
@@ -393,7 +406,13 @@ onMounted(() => {
<span>وضعیت</span>
<span />
</div>
<article v-for="item in items" :key="item.id" class="trow" role="row">
<article
v-for="item in items"
:key="item.id"
class="trow"
:class="{ 'menu-open': menuId === item.id }"
role="row"
>
<div class="title-cell">
<UiIcon name="star" :size="16" class="star" />
<div>
@@ -435,7 +454,11 @@ onMounted(() => {
>
<UiIcon name="dots-v" :size="16" />
</button>
<div v-if="menuId === item.id" class="popover">
<div
v-if="menuId === item.id"
class="popover"
:class="{ 'drop-up': isLastItem(item.id) }"
>
<RouterLink :to="{ name: 'activity-detail', params: { id: item.id } }" @click="menuId = null">
مشاهده
</RouterLink>
@@ -484,7 +507,12 @@ onMounted(() => {
<UiIcon :name="typeIcon[item.type]" :size="18" />
</span>
<span class="type-pill" :class="item.type">{{ typeLabel[item.type] }}</span>
<div v-if="menuId === item.id" class="popover" @click.stop>
<div
v-if="menuId === item.id"
class="popover"
:class="{ 'drop-up': isLastItem(item.id) }"
@click.stop
>
<RouterLink :to="{ name: 'activity-detail', params: { id: item.id } }" @click="menuId = null">
مشاهده
</RouterLink>
@@ -515,24 +543,29 @@ onMounted(() => {
</article>
</div>
<footer v-if="total" class="pager">
<p>نمایش {{ toFaDigits(rangeFrom) }} تا {{ toFaDigits(rangeTo) }} از {{ toFaDigits(total) }} فعالیت</p>
<div class="pages">
<button type="button" :disabled="page <= 1" @click="setPage(page - 1)">‹</button>
<button
v-for="n in pageCount"
:key="n"
type="button"
:class="{ on: n === page }"
@click="setPage(n)"
>
{{ toFaDigits(n) }}
</button>
<button type="button" :disabled="page >= pageCount" @click="setPage(page + 1)">›</button>
</div>
<p class="per">نمایش {{ toFaDigits(PAGE_SIZE) }} در هر صفحه</p>
</footer>
<UiPagination
v-if="total"
:page="page"
:total-pages="pageCount"
:total-items="total"
@update:page="setPage"
/>
</template>
<UiModal
:open="Boolean(activityModal)"
title="فعالیت جدید"
@close="activityModal = null"
>
<ActivityFormView
v-if="activityModal"
embedded
:initial-type="activityModal.type"
:initial-title="activityModal.title"
@saved="activityModal = null; void load(); void loadCounts()"
@cancel="activityModal = null"
/>
</UiModal>
</section>
</template>
@@ -603,26 +636,34 @@ h1 {
align-items: center;
justify-content: center;
gap: 0.35rem;
min-height: 42px;
padding: 0.55rem 1rem;
border-radius: 12px;
font-weight: 700;
height: var(--control-h);
min-height: var(--control-h);
padding: 0 0.85rem;
border-radius: var(--radius);
font-weight: 600;
font-size: var(--fs-sm);
border: 1px solid transparent;
cursor: pointer;
font: inherit;
text-decoration: none;
box-sizing: border-box;
transition: background var(--transition-fast), border-color var(--transition-fast);
}
.btn.primary {
background: #14b8a6;
background: var(--accent);
color: #fff;
box-shadow: 0 8px 18px rgba(20, 184, 166, 0.24);
}
.btn.ghost {
background: #fff;
color: #0f766e;
border-color: #99f6e4;
color: var(--ink-secondary);
border-color: var(--line);
}
.btn.ghost:hover {
background: var(--surface-subtle);
border-color: var(--line-strong);
}
.btn.wide {
@@ -668,25 +709,38 @@ h1 {
}
.search {
flex: 1;
min-width: 0;
flex: 1 1 200px;
min-width: 180px;
max-width: 400px;
height: var(--control-h);
min-height: var(--control-h);
display: flex;
align-items: center;
gap: 0.5rem;
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 0 0.85rem;
color: #94a3b8;
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0 0.75rem;
color: var(--muted);
box-sizing: border-box;
transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
}
.search:focus-within {
border-color: var(--accent);
box-shadow: 0 0 0 2px var(--accent-soft);
}
.search input {
flex: 1;
min-width: 0;
border: 0;
outline: none;
background: none;
padding: 0.75rem 0;
padding: 0;
font: inherit;
font-size: var(--fs-sm);
color: var(--ink);
}
.filter-wrap,
@@ -705,11 +759,16 @@ h1 {
inset-inline-end: 0;
min-width: 11rem;
background: #fff;
border-radius: 12px;
border-radius: var(--radius);
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.14);
padding: 0.35rem;
display: grid;
z-index: 8;
z-index: 20;
}
.popover.drop-up {
top: auto;
bottom: calc(100% + 6px);
}
.popover a,
@@ -720,7 +779,7 @@ h1 {
border: 0;
background: none;
padding: 0.6rem 0.7rem;
border-radius: 8px;
border-radius: var(--radius);
font: inherit;
cursor: pointer;
color: #0f172a;
@@ -735,7 +794,7 @@ h1 {
.empty-card {
background: #fff;
border-radius: 22px;
border-radius: var(--radius);
box-shadow: 0 10px 28px rgba(15, 23, 42, 0.05);
padding: 2.4rem 1.2rem 2rem;
display: grid;
@@ -767,9 +826,15 @@ h1 {
width: min(100%, 320px);
}
.idea-list a {
.idea-list a,
.idea-list button {
border: 0;
width: 100%;
text-align: right;
font: inherit;
cursor: pointer;
background: #f8fafc;
border-radius: 10px;
border-radius: var(--radius);
padding: 0.65rem 0.8rem;
color: #0f766e;
font-weight: 700;
@@ -788,8 +853,8 @@ h1 {
.table {
background: #fff;
border-radius: 18px;
overflow: hidden;
border-radius: var(--radius);
overflow: visible;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
}
@@ -805,14 +870,25 @@ h1 {
.thead {
color: #94a3b8;
font-size: 0.78rem;
font-weight: 700;
font-weight: 600;
border-bottom: 1px solid #f1f5f9;
border-radius: var(--radius) var(--radius) 0 0;
}
.trow {
position: relative;
border-bottom: 1px solid #f8fafc;
}
.trow:last-child {
border-bottom: 0;
border-radius: 0 0 var(--radius) var(--radius);
}
.trow.menu-open {
z-index: 12;
}
.title-cell {
display: flex;
gap: 0.55rem;
@@ -826,7 +902,7 @@ h1 {
.title {
color: inherit;
font-weight: 800;
font-weight: 600;
overflow-wrap: anywhere;
}
@@ -944,7 +1020,7 @@ time.note {
border: 0;
background: none;
color: #64748b;
border-radius: 8px;
border-radius: var(--radius);
display: grid;
place-items: center;
cursor: pointer;
@@ -958,7 +1034,7 @@ time.note {
.card {
background: #fff;
border: 1px solid #eef2f6;
border-radius: 18px;
border-radius: var(--radius);
padding: 0.9rem 0.95rem 0.75rem;
}
@@ -976,7 +1052,7 @@ time.note {
.card-main time {
display: inline-block;
background: none;
font-weight: 800;
font-weight: 600;
font-size: 0.95rem;
margin-bottom: 0.2rem;
}
@@ -1068,7 +1144,7 @@ time.note {
height: 32px;
border: 0;
background: #fff;
border-radius: 8px;
border-radius: var(--radius);
cursor: pointer;
}
+10 -10
View File
@@ -313,13 +313,12 @@ onMounted(load);
<style scoped>
.page {
max-width: 640px;
width: 100%;
max-width: 100%;
min-width: 0;
margin: 0 auto;
margin: 0;
display: grid;
gap: 0.9rem;
padding-bottom: 5.8rem;
}
.nav {
@@ -331,7 +330,7 @@ onMounted(load);
}
.brand {
font-weight: 800;
font-weight: 600;
color: #0f766e;
letter-spacing: -0.04em;
}
@@ -341,7 +340,7 @@ onMounted(load);
height: 38px;
border: 0;
background: #fff;
border-radius: 12px;
border-radius: var(--radius);
display: grid;
place-items: center;
color: #334155;
@@ -362,7 +361,7 @@ onMounted(load);
inset-inline-end: 0;
min-width: 10rem;
background: #fff;
border-radius: 12px;
border-radius: var(--radius);
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.14);
padding: 0.35rem;
display: grid;
@@ -377,7 +376,7 @@ onMounted(load);
border: 0;
background: none;
padding: 0.62rem 0.75rem;
border-radius: 8px;
border-radius: var(--radius);
font: inherit;
cursor: pointer;
color: #0f172a;
@@ -407,7 +406,7 @@ h1 {
.card {
background: #fff;
border-radius: 20px;
border-radius: var(--radius);
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.05);
padding: 1rem 1.05rem;
}
@@ -585,8 +584,9 @@ dd {
align-items: center;
justify-content: center;
gap: 0.3rem;
min-height: 46px;
border-radius: 14px;
min-height: var(--control-h);
height: var(--control-h);
border-radius: var(--radius);
border: 1px solid #99f6e4;
background: #fff;
color: #0f766e;
+210 -136
View File
@@ -17,6 +17,13 @@ import { appendSpokenText } from '@/lib/spoken-text';
import UiIcon from '@/components/UiIcon.vue';
import { brand } from '@mento/shared';
import UserAvatar from '@/components/UserAvatar.vue';
import {
UiBadge,
UiButton,
UiInput,
UiPageHeader,
UiTextarea,
} from '@/components/ui';
import type {
ActivityDto,
ActivityPriority,
@@ -29,11 +36,28 @@ import type {
PipelineBoardDto,
} from '@mento/shared';
const props = withDefaults(
defineProps<{
embedded?: boolean;
entityId?: string;
initialPersonId?: string;
initialType?: ActivityType;
initialTitle?: string;
}>(),
{ embedded: false },
);
const emit = defineEmits<{ saved: []; cancel: [] }>();
const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const id = computed(() => (typeof route.params.id === 'string' ? route.params.id : ''));
const isNew = computed(() => route.name === 'activity-new');
const id = computed(() => {
if (props.embedded) return props.entityId ?? '';
return typeof route.params.id === 'string' ? route.params.id : '';
});
const isNew = computed(() =>
props.embedded ? !props.entityId : route.name === 'activity-new',
);
const loading = ref(false);
const saving = ref(false);
@@ -190,18 +214,21 @@ async function load() {
isDone.value = data.status === 'done';
} else {
resetForm();
if (typeof route.query.personId === 'string' && route.query.personId) {
personId.value = route.query.personId;
}
const incomingPerson =
props.initialPersonId ||
(typeof route.query.personId === 'string' ? route.query.personId : '');
if (incomingPerson) personId.value = incomingPerson;
const incomingType = props.initialType || route.query.type;
if (
typeof route.query.type === 'string' &&
typeOptions.some((o) => o.value === route.query.type)
typeof incomingType === 'string' &&
typeOptions.some((o) => o.value === incomingType)
) {
type.value = route.query.type as ActivityType;
}
if (typeof route.query.title === 'string' && route.query.title) {
title.value = route.query.title;
type.value = incomingType as ActivityType;
}
const incomingTitle =
props.initialTitle ||
(typeof route.query.title === 'string' ? route.query.title : '');
if (incomingTitle) title.value = incomingTitle;
if (typeof route.query.dueAt === 'string' && route.query.dueAt) {
splitDue(new Date(route.query.dueAt).toISOString());
}
@@ -271,6 +298,10 @@ async function submit(next: 'detail' | 'new' = 'detail') {
status: isDone.value ? 'done' : 'open',
});
}
if (props.embedded) {
emit('saved');
return;
}
if (next === 'new') {
if (!isNew.value) {
await router.push({ name: 'activity-new' });
@@ -299,6 +330,10 @@ function bumpDuration(delta: number) {
}
function cancel() {
if (props.embedded) {
emit('cancel');
return;
}
if (!isNew.value && id.value) {
void router.push({ name: 'activity-detail', params: { id: id.value } });
return;
@@ -310,38 +345,44 @@ watch([id, isNew], () => void load(), { immediate: true });
</script>
<template>
<section class="page" @click="typeOpen = assigneeOpen = personOpen = false">
<header class="desktop-head">
<p class="crumb">
<RouterLink :to="{ name: 'activities' }">فعالیت‌ها</RouterLink>
<span>‹</span>
<strong>{{ pageTitle }}</strong>
</p>
<div class="desk-actions">
<button class="btn primary" type="button" :disabled="saving" @click="submit('detail')">
<UiIcon name="check-plain" :size="16" />
<section class="crm-page" :class="{ embedded }" @click="typeOpen = assigneeOpen = personOpen = false">
<UiPageHeader
v-if="!embedded"
:title="pageTitle"
:back-to="{ name: 'activities' }"
>
<template #lead>
<span class="crumb">
<RouterLink :to="{ name: 'activities' }">فعالیت‌ها</RouterLink>
<span>›</span>
<strong>{{ pageTitle }}</strong>
</span>
</template>
<template #actions>
<UiButton
variant="primary"
type="button"
:disabled="saving"
:loading="saving"
@click="submit('detail')"
>
<UiIcon name="check" :size="16" />
{{ saving ? 'در حال ذخیره…' : 'ذخیره فعالیت' }}
</button>
<button class="btn outline" type="button" :disabled="saving" @click="submit('new')">
</UiButton>
<UiButton
variant="outline"
type="button"
:disabled="saving"
@click="submit('new')"
>
<UiIcon name="plus" :size="16" />
ذخیره و ایجاد جدید
</button>
<button class="btn cancel" type="button" :disabled="saving" @click="cancel">
<UiIcon name="x" :size="16" />
</UiButton>
<UiButton variant="ghost" type="button" :disabled="saving" @click="cancel">
انصراف
</button>
</div>
</header>
<header class="mobile-head">
<button class="icon-btn" type="button" aria-label="ذخیره" :disabled="saving" @click="submit('detail')">
<UiIcon name="check-plain" :size="22" />
</button>
<h1>{{ pageTitle }}</h1>
<button class="icon-btn" type="button" aria-label="بستن" @click="cancel">
<UiIcon name="x" :size="20" />
</button>
</header>
</UiButton>
</template>
</UiPageHeader>
<nav class="tabs">
<button type="button" :class="{ on: tab === 'main' }" @click="tab = 'main'">اطلاعات اصلی</button>
@@ -376,7 +417,7 @@ watch([id, isNew], () => void load(), { immediate: true });
</div>
<div class="field">
<label for="title">عنوان فعالیت <i>*</i></label>
<input
<UiInput
id="title"
v-model="title"
required
@@ -526,10 +567,10 @@ watch([id, isNew], () => void load(), { immediate: true });
@transcript="(text) => (description = appendSpokenText(description, text))"
/>
</div>
<textarea
<UiTextarea
id="description"
v-model="description"
rows="8"
:rows="8"
placeholder="جزئیات تماس، نتیجه جلسه یا یادداشت مرتبط را بنویسید…"
/>
</div>
@@ -569,104 +610,108 @@ watch([id, isNew], () => void load(), { immediate: true });
</div>
<div>
<dt>وضعیت انجام</dt>
<dd>{{ statusText }}</dd>
<dd>
<UiBadge :variant="isDone ? 'success' : 'neutral'" size="sm">
{{ statusText }}
</UiBadge>
</dd>
</div>
<div>
<dt>اولویت</dt>
<dd>{{ priorityText }}</dd>
<dd>
<UiBadge
:variant="priority === 'very_high' || priority === 'high' ? 'danger' : priority === 'medium' ? 'warning' : 'neutral'"
size="sm"
>
{{ priorityText }}
</UiBadge>
</dd>
</div>
</dl>
</aside>
</div>
<footer class="mobile-save">
<button class="btn primary" type="button" :disabled="saving || loading" @click="submit('detail')">
<footer v-if="!embedded" class="mobile-save">
<UiButton
variant="primary"
type="button"
:disabled="saving || loading"
:loading="saving"
@click="submit('detail')"
>
{{ saving ? 'در حال ذخیره…' : 'ذخیره فعالیت' }}
</button>
</UiButton>
</footer>
<!-- Embedded Modal Actions (Fixed at bottom) -->
<div v-if="embedded" class="embed-actions">
<UiButton
variant="primary"
type="button"
:disabled="saving"
:loading="saving"
@click="submit('detail')"
>
<UiIcon name="check" :size="16" />
{{ saving ? 'در حال ذخیره…' : 'ذخیره فعالیت' }}
</UiButton>
<UiButton variant="ghost" type="button" :disabled="saving" @click="cancel">انصراف</UiButton>
</div>
</section>
</template>
<style scoped>
.page {
display: grid;
gap: 0.85rem;
padding-bottom: 5.5rem;
.crm-page.embedded {
padding-bottom: 0;
}
.desktop-head {
display: none;
justify-content: space-between;
gap: 1rem;
align-items: center;
.embed-actions {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin-bottom: var(--sp-3);
}
.crumb {
margin: 0;
display: flex;
align-items: center;
gap: 0.4rem;
color: #64748b;
gap: var(--sp-2);
color: var(--color-text-muted);
font-size: var(--fs-xs);
}
.crumb a {
color: #0f766e;
color: var(--color-primary-dark);
font-weight: 700;
}
.desk-actions {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.mobile-head {
display: grid;
grid-template-columns: 40px 1fr 40px;
align-items: center;
}
.mobile-head h1 {
margin: 0;
text-align: center;
font-size: 1.05rem;
}
.icon-btn {
width: 40px;
height: 40px;
border: 0;
background: none;
color: #0f766e;
display: grid;
place-items: center;
cursor: pointer;
text-decoration: none;
}
.tabs {
display: flex;
gap: 1.2rem;
border-bottom: 1px solid #e2e8f0;
gap: var(--sp-4);
border-bottom: 1px solid var(--color-border);
}
.tabs button {
border: 0;
background: none;
padding: 0.55rem 0;
padding: var(--sp-2) 0;
font: inherit;
color: #94a3b8;
color: var(--color-text-muted);
cursor: pointer;
transition: all var(--transition-fast);
}
.tabs .on {
color: #0f766e;
font-weight: 800;
box-shadow: inset 0 -2px 0 #14b8a6;
color: var(--color-primary);
font-weight: 700;
box-shadow: inset 0 -2px 0 var(--color-primary);
}
.layout {
display: grid;
gap: 0.85rem;
gap: var(--sp-3);
}
.summary {
@@ -676,32 +721,34 @@ watch([id, isNew], () => void load(), { immediate: true });
.form,
.stack {
display: grid;
gap: 0.75rem;
gap: var(--sp-3);
}
.card {
position: relative;
background: #fff;
border-radius: 18px;
padding: 0.95rem;
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.04);
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-xl);
padding: var(--sp-4);
box-shadow: var(--shadow-sm);
}
.field {
display: grid;
gap: 0.4rem;
gap: var(--sp-1);
min-width: 0;
}
.field label,
.pri-label {
margin: 0;
color: #64748b;
font-size: 0.82rem;
color: var(--color-text-muted);
font-size: var(--fs-xs);
font-weight: 600;
}
.field i {
color: #dc2626;
color: var(--color-danger);
font-style: normal;
}
@@ -711,17 +758,26 @@ watch([id, isNew], () => void load(), { immediate: true });
.note-card textarea {
width: 100%;
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 0.75rem 0.85rem;
border-radius: var(--radius);
min-height: var(--control-h);
padding: 0 0.85rem;
font: inherit;
background: #fff;
box-sizing: border-box;
}
.field textarea,
.note-card textarea {
min-height: 5.5rem;
padding: 0.65rem 0.85rem;
}
.picker {
width: 100%;
min-height: 48px;
min-height: var(--control-h);
height: var(--control-h);
border: 1px solid #e2e8f0;
border-radius: 12px;
border-radius: var(--radius);
background: #fff;
display: flex;
align-items: center;
@@ -777,7 +833,7 @@ watch([id, isNew], () => void load(), { immediate: true });
}
.who b {
font-weight: 800;
font-weight: 600;
}
.who small {
@@ -794,7 +850,7 @@ watch([id, isNew], () => void load(), { immediate: true });
padding: 0.35rem;
list-style: none;
background: #fff;
border-radius: 12px;
border-radius: var(--radius);
box-shadow: 0 16px 40px rgba(15, 23, 42, 0.14);
max-height: 16rem;
overflow: auto;
@@ -808,7 +864,7 @@ watch([id, isNew], () => void load(), { immediate: true });
border: 0;
background: none;
padding: 0.55rem 0.5rem;
border-radius: 8px;
border-radius: var(--radius);
font: inherit;
text-align: start;
cursor: pointer;
@@ -873,17 +929,18 @@ watch([id, isNew], () => void load(), { immediate: true });
display: flex;
align-items: center;
justify-content: space-between;
min-height: 48px;
min-height: var(--control-h);
height: var(--control-h);
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 0.2rem;
border-radius: var(--radius);
padding: 0.15rem;
}
.stepper button {
width: 40px;
height: 40px;
width: 28px;
height: 28px;
border: 0;
border-radius: 10px;
border-radius: var(--radius);
background: #f0fdfa;
color: #0f766e;
display: grid;
@@ -901,22 +958,33 @@ watch([id, isNew], () => void load(), { immediate: true });
.priorities {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
align-items: center;
justify-content: space-between;
gap: 0.25rem;
gap: 0.45rem;
margin-top: 0.45rem;
min-width: 0;
}
.pri {
display: grid;
justify-items: center;
gap: 0.2rem;
font-size: 0.68rem;
display: inline-flex;
flex-direction: row;
align-items: center;
gap: 0.28rem;
font-size: 0.72rem;
color: #64748b;
cursor: pointer;
white-space: nowrap;
flex: 0 0 auto;
}
.pri input {
accent-color: #14b8a6;
width: 13px;
height: 13px;
margin: 0;
flex-shrink: 0;
}
.pri.very-high {
@@ -940,12 +1008,13 @@ watch([id, isNew], () => void load(), { immediate: true });
}
.pri.on span {
font-weight: 800;
font-weight: 600;
}
.reminder :deep(.trigger) {
border: 0;
min-height: 48px;
min-height: var(--control-h);
height: var(--control-h);
padding-inline: 0.15rem;
}
@@ -960,7 +1029,7 @@ watch([id, isNew], () => void load(), { immediate: true });
.channel-title {
margin: 0;
font-size: 0.88rem;
font-weight: 800;
font-weight: 600;
color: #0f172a;
}
@@ -970,7 +1039,7 @@ watch([id, isNew], () => void load(), { immediate: true });
gap: 0.55rem;
cursor: pointer;
padding: 0.55rem 0.65rem;
border-radius: 12px;
border-radius: var(--radius);
border: 1px solid #e2e8f0;
background: #f8fafc;
}
@@ -1039,11 +1108,11 @@ watch([id, isNew], () => void load(), { immediate: true });
align-items: center;
justify-content: center;
gap: 0.35rem;
min-height: 44px;
border-radius: 12px;
padding: 0.55rem 0.95rem;
min-height: var(--control-h);
border-radius: var(--radius);
padding: 0 0.95rem;
font: inherit;
font-weight: 800;
font-weight: 600;
cursor: pointer;
}
@@ -1079,8 +1148,9 @@ watch([id, isNew], () => void load(), { immediate: true });
.mobile-save .btn {
width: 100%;
min-height: 50px;
border-radius: 14px;
min-height: var(--control-h);
height: var(--control-h);
border-radius: var(--radius);
}
@media (min-width: 960px) {
@@ -1109,7 +1179,7 @@ watch([id, isNew], () => void load(), { immediate: true });
position: sticky;
top: 0.8rem;
background: #fff;
border-radius: 20px;
border-radius: var(--radius);
padding: 1rem 1.05rem 0.7rem;
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.04);
}
@@ -1128,7 +1198,7 @@ watch([id, isNew], () => void load(), { immediate: true });
justify-items: center;
gap: 0.45rem;
padding: 1rem 0.6rem;
border-radius: 14px;
border-radius: var(--radius);
background: #f8fafc;
color: #94a3b8;
text-align: center;
@@ -1183,7 +1253,11 @@ watch([id, isNew], () => void load(), { immediate: true });
.priorities {
justify-content: flex-start;
gap: 1.1rem;
gap: 1.15rem;
}
.pri {
gap: 0.32rem;
}
}
</style>
+481 -285
View File
@@ -1,86 +1,217 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import {
UiBadge,
UiButton,
UiInput,
UiPageHeader,
} from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue';
import AutomationCanvas from '@/components/automations/AutomationCanvas.vue';
import type { AutomationAddPayload } from '@/components/automations/AutomationCanvas.vue';
import AutomationInspector from '@/components/automations/AutomationInspector.vue';
import { toFaDigits } from '@/lib/jalali';
import type {
AutomationAction,
AutomationRuleDto,
AutomationStep,
AutomationTrigger,
CreateAutomationRuleRequest,
OrgUserDto,
} from '@mento/shared';
import {
AUTOMATION_ACTION_LABELS,
AUTOMATION_TRIGGER_LABELS,
MAX_AUTOMATION_STEPS,
conditionFieldsForTrigger,
firstAutomationAction,
isAutomationCondition,
normalizeAutomationSteps,
packAutomationConfig,
} from '@mento/shared';
const AUTOMATION_TRIGGER_LABELS: Record<AutomationTrigger, string> = {
deal_won: 'معامله برنده شد',
ticket_resolved: 'تیکت حل شد',
};
const AUTOMATION_ACTION_LABELS: Record<AutomationAction, string> = {
create_activity: 'ساخت فعالیت',
create_notification: 'ارسال اعلان',
add_loyalty_points: 'افزودن امتیاز باشگاه',
};
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const ok = ref('');
const items = ref<AutomationRuleDto[]>([]);
const users = ref<OrgUserDto[]>([]);
const editingId = ref<string | null>(null);
const name = ref('');
const name = ref('قانون بدون نام');
const trigger = ref<AutomationTrigger>('deal_won');
const action = ref<AutomationAction>('create_activity');
const isActive = ref(true);
const title = ref('');
const body = ref('');
const points = ref(100);
const steps = ref<AutomationStep[]>([makeStep('create_activity')]);
const selected = ref<'trigger' | string>('trigger');
const savedSnap = ref('');
const triggers = Object.keys(AUTOMATION_TRIGGER_LABELS) as AutomationTrigger[];
const actions = Object.keys(AUTOMATION_ACTION_LABELS) as AutomationAction[];
const dirty = computed(() => snap() !== savedSnap.value);
const canSave = computed(
() => name.value.trim().length >= 2 && Boolean(firstAutomationAction(steps.value)),
);
function resetForm() {
editingId.value = null;
name.value = '';
trigger.value = 'deal_won';
action.value = 'create_activity';
isActive.value = true;
title.value = '';
body.value = '';
points.value = 100;
function makeStep(action: AutomationAction): AutomationStep {
return {
id: `s-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
kind: 'action',
action,
activityType: action === 'create_activity' ? 'task' : undefined,
points: action === 'add_loyalty_points' ? 100 : undefined,
notifyChannel: action === 'create_notification' ? 'app' : undefined,
notifyTarget: action === 'create_notification' ? 'staff' : undefined,
assigneeId: null,
notifyUserId: null,
};
}
function startEdit(row: AutomationRuleDto) {
function makeCondition(): AutomationStep {
const field = conditionFieldsForTrigger(trigger.value)[0] ?? 'has_person';
return {
id: `s-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
kind: 'condition',
conditionField: field,
conditionOp:
field === 'deal_amount' ? 'gte' : field === 'ticket_priority' ? 'eq' : 'is_set',
conditionValue:
field === 'deal_amount' ? 0 : field === 'ticket_priority' ? 'normal' : undefined,
};
}
function snap() {
return JSON.stringify({
name: name.value.trim(),
trigger: trigger.value,
isActive: isActive.value,
steps: steps.value,
});
}
function markClean() {
savedSnap.value = snap();
}
function errText(e: unknown, fallback: string) {
if (axios.isAxiosError(e) && !e.response) return 'اتصال به API برقرار نشد.';
const msg = axios.isAxiosError(e) ? e.response?.data?.message : null;
if (Array.isArray(msg) && msg.length) return msg.join(' ');
if (typeof msg === 'string' && msg.trim()) return msg;
return fallback;
}
function hydrate(row?: AutomationRuleDto | null) {
if (!row) {
editingId.value = null;
name.value = 'قانون بدون نام';
trigger.value = 'deal_won';
isActive.value = true;
steps.value = [makeStep('create_activity')];
selected.value = 'trigger';
markClean();
return;
}
editingId.value = row.id;
name.value = row.name;
trigger.value = row.trigger;
action.value = row.action;
isActive.value = row.isActive;
title.value = row.config.title ?? '';
body.value = row.config.body ?? '';
points.value = row.config.points ?? 100;
ok.value = '';
steps.value = normalizeAutomationSteps(row.action, row.config).map((s, i) => ({
...s,
id: s.id || `step-${i}`,
kind: s.kind === 'condition' ? 'condition' : 'action',
assigneeId: s.assigneeId ?? null,
notifyUserId: s.notifyUserId ?? null,
notifyChannel:
s.notifyChannel ??
(s.action === 'create_notification' ? 'app' : undefined),
notifyTarget:
s.notifyTarget ??
(s.action === 'create_notification' ? 'staff' : undefined),
activityType:
s.activityType ?? (s.action === 'create_activity' ? 'task' : undefined),
points: s.points ?? (s.action === 'add_loyalty_points' ? 100 : undefined),
}));
if (!steps.value.length) steps.value = [makeStep('create_activity')];
selected.value = 'trigger';
markClean();
}
function confirmLeave() {
if (!dirty.value) return true;
return confirm('تغییرات ذخیره نشده از بین می‌رود. ادامه می‌دهید؟');
}
function startNew() {
if (!confirmLeave()) return;
hydrate(null);
}
function openRule(row: AutomationRuleDto) {
if (editingId.value === row.id) return;
if (!confirmLeave()) return;
hydrate(row);
}
function addStep(payload: AutomationAddPayload, index: number) {
if (steps.value.length >= MAX_AUTOMATION_STEPS) {
error.value = `حداکثر ${toFaDigits(MAX_AUTOMATION_STEPS)} مرحله در هر قانون مجاز است.`;
return;
}
error.value = '';
const step =
payload.kind === 'condition'
? makeCondition()
: makeStep(payload.action);
steps.value.splice(index, 0, step);
selected.value = step.id;
}
function removeStep(stepId: string) {
if (steps.value.length <= 1) {
error.value = 'حداقل یک مرحله باید در زنجیره باقی بماند.';
return;
}
const i = steps.value.findIndex((s) => s.id === stepId);
if (i < 0) return;
steps.value.splice(i, 1);
if (selected.value === stepId) {
const next = steps.value[Math.max(0, i - 1)];
selected.value = next?.id ?? 'trigger';
}
}
function chainLabel(row: AutomationRuleDto) {
const t = AUTOMATION_TRIGGER_LABELS[row.trigger] ?? row.trigger;
const a = AUTOMATION_ACTION_LABELS[row.action] ?? row.action;
return `${t} ← ${a}`;
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<AutomationRuleDto[]>('/automations');
items.value = data;
} catch (e) {
if (axios.isAxiosError(e) && !e.response) {
error.value = 'اتصال به API برقرار نشد.';
} else {
error.value = 'بارگذاری اتوماسیون ناموفق بود.';
const [rulesRes, usersRes] = await Promise.all([
api.get<AutomationRuleDto[]>('/automations'),
api.get<OrgUserDto[]>('/users').catch(() => ({ data: [] as OrgUserDto[] })),
]);
items.value = rulesRes.data;
users.value = usersRes.data;
if (editingId.value) {
const cur = items.value.find((x) => x.id === editingId.value);
if (cur && !dirty.value) hydrate(cur);
else if (!cur) hydrate(items.value[0] ?? null);
}
} catch (e) {
error.value = errText(e, 'بارگذاری اتوماسیون ناموفق بود.');
} finally {
loading.value = false;
}
}
async function save() {
if (name.value.trim().length < 2) {
error.value = 'نام قانون را وارد کنید.';
const action = firstAutomationAction(steps.value);
if (!name.value.trim() || !action) {
error.value = !action ? 'حداقل یک عمل در زنجیره لازم است.' : 'نام قانون را وارد کنید.';
return;
}
saving.value = true;
@@ -90,28 +221,22 @@ async function save() {
const payload: CreateAutomationRuleRequest = {
name: name.value.trim(),
trigger: trigger.value,
action: action.value,
action,
isActive: isActive.value,
config: {
title: title.value.trim() || undefined,
body: body.value.trim() || undefined,
points:
action.value === 'add_loyalty_points'
? Math.max(1, Math.floor(points.value))
: undefined,
},
config: packAutomationConfig(steps.value),
};
if (editingId.value) {
await api.patch(`/automations/${editingId.value}`, payload);
ok.value = 'قانون به‌روز شد.';
} else {
await api.post('/automations', payload);
const { data } = await api.post<AutomationRuleDto>('/automations', payload);
editingId.value = data.id;
ok.value = 'قانون ساخته شد.';
}
resetForm();
markClean();
await load();
} catch {
error.value = 'ذخیره قانون ناموفق بود.';
} catch (e) {
error.value = errText(e, 'ذخیره قانون ناموفق بود.');
} finally {
saving.value = false;
}
@@ -121,289 +246,360 @@ async function removeRule(id: string) {
if (!confirm('قانون حذف شود؟')) return;
try {
await api.delete(`/automations/${id}`);
if (editingId.value === id) hydrate(null);
await load();
} catch {
error.value = 'حذف ناموفق بود.';
} catch (e) {
error.value = errText(e, 'حذف ناموفق بود.');
}
}
async function toggleActive(row: AutomationRuleDto) {
try {
await api.patch(`/automations/${row.id}`, { isActive: !row.isActive });
if (editingId.value === row.id) isActive.value = !row.isActive;
await load();
} catch {
error.value = 'تغییر وضعیت ناموفق بود.';
} catch (e) {
error.value = errText(e, 'تغییر وضعیت ناموفق بود.');
}
}
onMounted(load);
onMounted(async () => {
await load();
if (editingId.value) return;
hydrate(items.value[0] ?? null);
});
watch(trigger, (next) => {
const allowed = conditionFieldsForTrigger(next);
const fallback = allowed[0] ?? 'has_person';
for (const step of steps.value) {
if (!isAutomationCondition(step)) continue;
if (step.conditionField && allowed.includes(step.conditionField)) continue;
step.conditionField = fallback;
step.conditionOp =
fallback === 'deal_amount'
? 'gte'
: fallback === 'ticket_priority'
? 'eq'
: 'is_set';
step.conditionValue =
fallback === 'deal_amount'
? 0
: fallback === 'ticket_priority'
? 'normal'
: undefined;
}
});
</script>
<template>
<section class="page">
<header class="page-head">
<div class="head-copy">
<h1>اگر / آنگاه</h1>
<p class="lead">
بعد از بردن معامله یا حل شدن تیکت، فعالیت، اعلان یا امتیاز باشگاه بسازید.
</p>
</div>
<button class="btn ghost" type="button" :disabled="loading" @click="load">
بروزرسانی
</button>
</header>
<section class="crm-page">
<UiPageHeader
title="اتوماسیون"
subtitle="مثل یک بوم کاری: گره «اگر» را به چند عمل پشت‌سرهم وصل کنید."
>
<template #actions>
<UiButton variant="ghost" :disabled="loading" @click="load">
بروزرسانی
</UiButton>
<UiButton variant="primary" @click="startNew">
<UiIcon name="plus" :size="16" />
قانون جدید
</UiButton>
</template>
</UiPageHeader>
<p v-if="error" class="error">{{ error }}</p>
<p v-if="ok" class="ok">{{ ok }}</p>
<p v-if="error" class="error-msg">{{ error }}</p>
<p v-if="ok" class="ok-msg">{{ ok }}</p>
<form class="panel form" @submit.prevent="save">
<h2>{{ editingId ? 'ویرایش قانون' : 'قانون جدید' }}</h2>
<label>
نام
<input v-model="name" type="text" required minlength="2" maxlength="120" />
</label>
<div class="grid2">
<label>
اگر (محرک)
<select v-model="trigger">
<option v-for="t in triggers" :key="t" :value="t">
{{ AUTOMATION_TRIGGER_LABELS[t] }}
</option>
</select>
</label>
<label>
آنگاه (عمل)
<select v-model="action">
<option v-for="a in actions" :key="a" :value="a">
{{ AUTOMATION_ACTION_LABELS[a] }}
</option>
</select>
</label>
</div>
<label>
عنوان / متن عمل
<input v-model="title" type="text" maxlength="200" placeholder="اختیاری" />
</label>
<label>
توضیح
<textarea v-model="body" rows="3" maxlength="1000" placeholder="اختیاری" />
</label>
<label v-if="action === 'add_loyalty_points'">
امتیاز
<input v-model.number="points" type="number" min="1" />
</label>
<label class="check">
<input v-model="isActive" type="checkbox" />
فعال
</label>
<div class="actions">
<button class="btn primary" type="submit" :disabled="saving">
{{ saving ? 'در حال ذخیره…' : editingId ? 'به‌روزرسانی' : 'ساخت' }}
</button>
<button
v-if="editingId"
class="btn ghost"
type="button"
@click="resetForm"
>
انصراف
</button>
</div>
</form>
<section class="panel">
<h2>قوانین</h2>
<ul class="list">
<li v-for="row in items" :key="row.id">
<div>
<strong>{{ row.name }}</strong>
<p class="muted">
اگر {{ AUTOMATION_TRIGGER_LABELS[row.trigger] }} →
{{ AUTOMATION_ACTION_LABELS[row.action] }}
<span v-if="!row.isActive"> · غیرفعال</span>
</p>
</div>
<div class="row-actions">
<button class="link" type="button" @click="toggleActive(row)">
{{ row.isActive ? 'غیرفعال' : 'فعال' }}
</button>
<button class="link" type="button" @click="startEdit(row)">ویرایش</button>
<button class="link danger" type="button" @click="removeRule(row.id)">
حذف
<div class="workspace">
<aside class="rules">
<div class="rules-head">
<h2>قوانین</h2>
<UiBadge variant="neutral" size="sm">{{ items.length }} قانون</UiBadge>
</div>
<ul>
<li
v-for="row in items"
:key="row.id"
:class="{ on: editingId === row.id }"
>
<button class="pick" type="button" @click="openRule(row)">
<div class="pick-top">
<strong>{{ row.name }}</strong>
<UiBadge :variant="row.isActive ? 'success' : 'neutral'" size="sm" dot>
{{ row.isActive ? 'فعال' : 'غیرفعال' }}
</UiBadge>
</div>
<span class="chain-preview">{{ chainLabel(row) }}</span>
</button>
<div class="mini">
<UiButton variant="ghost" size="sm" @click="toggleActive(row)">
{{ row.isActive ? 'غیرفعال‌سازی' : 'فعال‌سازی' }}
</UiButton>
<UiButton variant="danger" size="sm" @click="removeRule(row.id)">
حذف
</UiButton>
</div>
</li>
</ul>
<p v-if="!items.length && !loading" class="muted">هنوز قانونی نیست.</p>
</aside>
<div class="studio">
<div class="toolbar">
<div class="name-field">
<span class="name-label">نام قانون:</span>
<UiInput v-model="name" required minlength="2" maxlength="120" placeholder="نام قانون اتوماسیون…" />
</div>
</li>
</ul>
<p v-if="!items.length && !loading" class="muted">هنوز قانونی نیست.</p>
</section>
<label class="check">
<input v-model="isActive" type="checkbox" />
<span>فعال</span>
</label>
<UiButton
variant="primary"
type="button"
:disabled="saving || !canSave"
:loading="saving"
@click="save"
>
{{ saving ? 'در حال ذخیره…' : editingId ? 'ذخیره قانون' : 'ساخت قانون' }}
</UiButton>
</div>
<div class="stage">
<AutomationCanvas
:trigger="trigger"
:steps="steps"
:selected="selected"
@select="selected = $event"
@add="addStep"
@remove="removeStep"
/>
<AutomationInspector
v-model:trigger="trigger"
v-model:steps="steps"
:selected="selected"
:users="users"
/>
</div>
</div>
</div>
</section>
</template>
<style scoped>
.page {
display: grid;
gap: 1rem;
max-width: 860px;
min-width: 0;
overflow-x: clip;
.error-msg {
color: var(--color-danger);
font-size: var(--fs-sm);
font-weight: 600;
margin: 0;
}
.page-head {
.ok-msg {
color: var(--color-success);
font-size: var(--fs-sm);
font-weight: 600;
margin: 0;
}
.workspace {
display: grid;
grid-template-columns: 1fr;
gap: var(--sp-4);
align-items: start;
min-width: 0;
}
.rules,
.studio {
border: 1px solid var(--color-border);
border-radius: var(--radius-xl);
background: var(--color-surface);
box-shadow: var(--shadow-sm);
}
.rules {
padding: var(--sp-4);
display: grid;
gap: var(--sp-3);
align-content: start;
}
.rules-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
align-items: flex-start;
}
.head-copy {
min-width: 0;
}
h1 {
margin: 0 0 0.3rem;
font-size: clamp(1.45rem, 2.5vw, 1.85rem);
font-weight: 800;
}
.lead,
.muted {
.rules-head h2 {
margin: 0;
color: #64748b;
}
.panel {
border: 1px solid #e2e8f0;
border-radius: 18px;
padding: 1.1rem;
background: #fff;
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.04);
display: grid;
gap: 0.75rem;
}
h2 {
margin: 0;
font-size: 1.05rem;
font-size: var(--fs-base);
font-weight: 700;
color: #0f172a;
}
.form label {
display: grid;
gap: 0.35rem;
font-size: 0.9rem;
color: #64748b;
}
input,
select,
textarea {
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 0.6rem 0.75rem;
font: inherit;
color: #0f172a;
background: #fff;
}
.grid2 {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.65rem;
}
.check {
display: flex !important;
align-items: center;
gap: 0.45rem;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 42px;
padding: 0.55rem 1rem;
border-radius: 12px;
font-weight: 700;
border: 1px solid transparent;
cursor: pointer;
font: inherit;
}
.btn.primary {
background: #14b8a6;
color: #fff;
box-shadow: 0 8px 18px rgba(20, 184, 166, 0.24);
}
.btn.ghost {
background: #fff;
color: #0f766e;
border-color: #99f6e4;
box-shadow: none;
}
.actions,
.row-actions {
display: flex;
gap: 0.55rem;
flex-wrap: wrap;
}
.list {
.rules ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.7rem;
gap: var(--sp-2);
}
.list li {
display: flex;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
border-bottom: 1px solid #e2e8f0;
padding-bottom: 0.65rem;
.rules li {
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
padding: var(--sp-3);
display: grid;
gap: var(--sp-2);
transition: all var(--transition-fast);
}
.link {
.rules li.on {
border-color: var(--color-primary);
background: var(--color-primary-surface);
}
.pick {
display: grid;
gap: var(--sp-1);
text-align: start;
border: 0;
background: none;
border: none;
color: #0f766e;
padding: 0;
cursor: pointer;
font: inherit;
padding: 0;
color: inherit;
width: 100%;
}
.pick-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--sp-2);
width: 100%;
}
.pick-top strong {
font-size: var(--fs-sm);
color: var(--color-text-emphasis);
}
.chain-preview {
color: var(--color-text-muted);
font-size: var(--fs-xs);
}
.mini {
display: flex;
gap: var(--sp-2);
justify-content: flex-end;
border-top: 1px dashed var(--color-border);
padding-top: var(--sp-2);
}
.studio {
padding: var(--sp-4);
display: grid;
gap: var(--sp-3);
min-width: 0;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: var(--sp-3);
align-items: center;
}
.name-field {
display: flex;
align-items: center;
gap: var(--sp-2);
flex: 1 1 16rem;
}
.name-label {
font-size: var(--fs-sm);
font-weight: 600;
color: var(--color-text-muted);
white-space: nowrap;
}
.danger {
color: #b91c1c;
.check {
display: flex;
align-items: center;
gap: var(--sp-2);
color: var(--color-text);
font-size: var(--fs-sm);
cursor: pointer;
}
.error {
margin: 0;
color: #b91c1c;
.stage {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--sp-3);
min-width: 0;
}
.ok {
margin: 0;
color: #0f766e;
font-weight: 600;
.stage :deep(.canvas) {
width: 100%;
min-width: 0;
}
@media (max-width: 700px) {
.grid2 {
grid-template-columns: 1fr;
.muted {
color: var(--color-text-muted);
font-size: var(--fs-sm);
}
@media (min-width: 1280px) {
.workspace {
grid-template-columns: minmax(15rem, 20rem) minmax(0, 1fr);
grid-template-areas:
'rules toolbar'
'stage stage';
}
.actions,
.row-actions,
.list li {
flex-direction: column;
align-items: stretch;
.rules {
grid-area: rules;
height: 100%;
}
.studio {
display: contents;
border: 0;
padding: 0;
box-shadow: none;
background: transparent;
}
.toolbar {
grid-area: toolbar;
border: 1px solid #e2e8f0;
border-radius: var(--radius);
background: #fff;
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.04);
padding: 0.85rem 1rem;
align-items: end;
}
.stage {
grid-area: stage;
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 1279px) {
.rules ul {
display: flex;
overflow-x: auto;
gap: 0.5rem;
}
.rules li {
min-width: 13rem;
flex: 0 0 auto;
}
}
</style>

Some files were not shown because too many files have changed in this diff Show More