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>
This commit is contained in:
2026-09-09 13:12:13 +03:30
co-authored by Cursor
parent 48d3469eea
commit 3ec87ff912
17 changed files with 2355 additions and 410 deletions
@@ -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 {}
+218 -26
View File
@@ -1,16 +1,34 @@
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;
@@ -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,53 @@ 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,
};
}
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,
};
}
private async execute(
action: AutomationAction,
config: AutomationRuleConfig,
@@ -155,25 +239,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 +254,83 @@ 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 =
ctx.entityType === 'deal'
? `/deals/${ctx.entityId}`
: `/tickets/${ctx.entityId}`;
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,6 +359,55 @@ 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}`;
@@ -0,0 +1,551 @@
<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;
min-height: 22rem;
border-radius: 16px;
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: 12px;
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: 10px;
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: 12px;
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: 8px;
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: 800;
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: 14px;
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,338 @@
<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_LABELS,
AUTOMATION_TRIGGERS,
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">
<option v-for="t in AUTOMATION_TRIGGERS" :key="t" :value="t">
{{ AUTOMATION_TRIGGER_LABELS[t] }}
</option>
</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: 16px;
min-width: 0;
}
h2 {
margin: 0;
font-size: 0.98rem;
font-weight: 800;
}
.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: 12px;
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>
@@ -18,7 +18,7 @@ const emit = defineEmits<{
class="add-deal"
:style="{
'--add-color': PIPELINE_ACCENT[accent].text,
'--add-border': PIPELINE_ACCENT[accent].border,
'--add-border': PIPELINE_ACCENT[accent].solid,
'--add-soft': PIPELINE_ACCENT[accent].soft,
}"
aria-label="افزودن معامله"
@@ -34,16 +34,17 @@ const emit = defineEmits<{
display: flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
gap: 0.4rem;
width: 100%;
margin-top: 0.35rem;
padding: 0.85rem 1rem;
margin-top: 0.15rem;
padding: 0.9rem 1rem;
border: 1.5px dashed var(--add-border);
border-radius: 16px;
background: color-mix(in srgb, var(--add-soft) 55%, white);
background: #fff;
color: var(--add-color);
font-weight: 700;
font-size: 0.9rem;
white-space: nowrap;
cursor: pointer;
transition: background 0.15s ease, border-color 0.15s ease, transform 0.15s ease;
}
+74 -44
View File
@@ -43,7 +43,7 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
<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>
<p v-if="deal.description" class="desc">{{ deal.description }}</p>
</div>
</div>
<button
@@ -56,23 +56,24 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
</button>
</div>
<div class="amount" dir="ltr">
<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 class="meta">
<div class="who">
<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>
<div class="amount" dir="ltr">
<strong>{{ money.number }}</strong>
<span>{{ money.unit }}</span>
</div>
</div>
</article>
</template>
@@ -83,6 +84,8 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
border: 1px solid color-mix(in srgb, var(--line) 70%, transparent);
border-radius: 16px;
padding: 1rem;
min-width: 0;
overflow: hidden;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.04);
cursor: grab;
transition:
@@ -146,6 +149,7 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
.titles {
min-width: 0;
flex: 1;
}
.titles h3 {
@@ -155,6 +159,11 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
line-height: 1.45;
color: var(--ink);
cursor: pointer;
overflow: hidden;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow-wrap: anywhere;
}
.desc {
@@ -162,6 +171,9 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
color: var(--muted);
font-size: 0.8rem;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.menu {
@@ -180,12 +192,52 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
background: #f1f5f9;
}
.amount {
.meta {
margin-top: 0.85rem;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 0.5rem;
min-width: 0;
}
.who {
display: flex;
align-items: center;
gap: 0.5rem;
min-width: 0;
}
.avatar {
width: 28px;
height: 28px;
max-width: 28px;
border-radius: 999px;
object-fit: cover;
border: 1px solid var(--line);
flex: 0 0 auto;
}
.date {
display: inline-flex;
align-items: center;
gap: 0.3rem;
min-width: 0;
color: var(--muted);
font-size: 0.78rem;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.amount {
text-align: left;
display: grid;
justify-items: start;
gap: 0.05rem;
gap: 0.02rem;
flex: 0 1 auto;
min-width: 0;
}
.amount strong {
@@ -193,6 +245,8 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
font-weight: 800;
color: var(--ink);
letter-spacing: -0.01em;
max-width: 100%;
overflow-wrap: anywhere;
}
.amount span {
@@ -200,28 +254,4 @@ const colors = computed(() => PIPELINE_ACCENT[props.accent]);
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);
}
.date {
display: inline-flex;
align-items: center;
gap: 0.3rem;
color: var(--muted);
font-size: 0.78rem;
font-weight: 600;
}
</style>
@@ -45,20 +45,31 @@ const emit = defineEmits<{
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 {
overflow-x: auto;
padding-bottom: 0.75rem;
scroll-snap-type: x mandatory;
-webkit-overflow-scrolling: touch;
scrollbar-width: none;
}
.board::-webkit-scrollbar {
height: 8px;
}
.board::-webkit-scrollbar {
display: none;
.board::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--muted) 38%, transparent);
border-radius: 999px;
}
@container pipeline (max-width: 720px) {
.board {
scroll-snap-type: x mandatory;
scroll-padding-inline: 0.25rem;
}
}
</style>
@@ -95,10 +95,10 @@ 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;
padding: 0.15rem 0.1rem 0.35rem;
border-radius: 18px;
border: 1px solid transparent;
background: transparent;
@@ -138,12 +138,16 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
font-size: 0.98rem;
font-weight: 800;
color: var(--ink);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.head-actions {
display: flex;
align-items: center;
gap: 0.45rem;
flex: 0 0 auto;
}
.count {
@@ -154,13 +158,13 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
}
.plus {
width: 1.7rem;
height: 1.7rem;
border-radius: 999px;
border: 0;
width: 1.75rem;
height: 1.75rem;
border-radius: 8px;
border: 1.5px solid var(--accent);
display: grid;
place-items: center;
background: color-mix(in srgb, var(--accent) 14%, white);
background: #fff;
color: var(--accent);
cursor: pointer;
}
@@ -176,6 +180,7 @@ function onCardDrop(stageId: string, index: number, event: DragEvent) {
flex-direction: column;
gap: 0.7rem;
flex: 1;
min-width: 0;
min-height: 4rem;
}
@@ -190,20 +195,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: 18px;
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: 800;
}
.titles {
display: grid;
gap: 0.1rem;
min-width: 0;
}
.titles strong {
font-size: 0.92rem;
font-weight: 800;
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: 800;
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: 8px;
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: 16px;
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>
@@ -3,20 +3,33 @@ import UiIcon from '@/components/UiIcon.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 }>;
selectedPipelineId: string;
viewMode: PipelineViewMode;
search: string;
canCreate?: boolean;
}>(),
{ canCreate: false },
);
const emit = defineEmits<{
'update:viewMode': [PipelineViewMode];
'update:search': [string];
'update:selectedPipelineId': [string];
filter: [];
create: [];
}>();
function onPick(value: string) {
if (value === '__create__') {
emit('create');
return;
}
emit('update:selectedPipelineId', value);
}
</script>
<template>
@@ -25,7 +38,7 @@ 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="نوع نمایش">
@@ -37,7 +50,7 @@ const emit = defineEmits<{
@click="emit('update:viewMode', 'kanban')"
>
<UiIcon name="grid" :size="16" />
نمای کاریز
<span class="seg-label">نمای کاریز</span>
</button>
<button
type="button"
@@ -47,7 +60,7 @@ const emit = defineEmits<{
@click="emit('update:viewMode', 'list')"
>
<UiIcon name="list" :size="16" />
نمای لیست
<span class="seg-label">نمای لیست</span>
</button>
</div>
@@ -55,12 +68,7 @@ const emit = defineEmits<{
<span class="sr">انتخاب کاریز</span>
<select
:value="selectedPipelineId"
@change="
emit(
'update:selectedPipelineId',
($event.target as HTMLSelectElement).value,
)
"
@change="onPick(($event.target as HTMLSelectElement).value)"
>
<option
v-for="opt in pipelineOptions"
@@ -69,6 +77,7 @@ const emit = defineEmits<{
>
{{ opt.name }}
</option>
<option v-if="canCreate" value="__create__">کاریز جدید…</option>
</select>
<UiIcon class="chev" name="chevron" :size="16" />
</label>
@@ -94,17 +103,20 @@ const emit = defineEmits<{
<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 {
@@ -115,35 +127,42 @@ const emit = defineEmits<{
place-items: center;
background: #0f766e;
color: #fff;
flex: 0 0 auto;
}
h1 {
margin: 0;
font-size: 1.25rem;
font-size: 1.2rem;
font-weight: 800;
color: var(--ink);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.view-toggle {
display: inline-flex;
background: #eef2f4;
background: #e8eef1;
border-radius: 12px;
padding: 0.2rem;
gap: 0.15rem;
padding: 0.18rem;
gap: 0.12rem;
flex: 0 0 auto;
}
.seg {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
border: 0;
background: transparent;
color: var(--muted);
color: #7b8794;
font-weight: 700;
font-size: 0.82rem;
padding: 0.45rem 0.75rem;
padding: 0.42rem 0.7rem;
border-radius: 10px;
cursor: pointer;
white-space: nowrap;
}
.seg.on {
@@ -161,7 +180,8 @@ h1 {
position: relative;
display: inline-flex;
align-items: center;
min-width: 140px;
min-width: 8.5rem;
flex: 0 1 13rem;
}
.pipeline-pick select {
@@ -169,12 +189,16 @@ h1 {
border: 1px solid var(--line);
background: #fff;
border-radius: 12px;
padding: 0.55rem 2rem 0.55rem 0.85rem;
padding: 0.52rem 2rem 0.52rem 0.85rem;
font: inherit;
font-weight: 600;
color: var(--ink);
min-width: 150px;
width: 100%;
min-width: 0;
cursor: pointer;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pipeline-pick .chev {
@@ -186,11 +210,11 @@ h1 {
}
.search {
flex: 1 1 180px;
min-width: 160px;
display: flex;
align-items: center;
gap: 0.45rem;
flex: 1 1 8rem;
min-width: 6.5rem;
background: #fff;
border: 1px solid var(--line);
border-radius: 12px;
@@ -203,6 +227,7 @@ h1 {
outline: none;
background: transparent;
width: 100%;
min-width: 0;
color: var(--ink);
font: inherit;
}
@@ -210,15 +235,17 @@ h1 {
.filter-btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
border: 0;
border-radius: 12px;
padding: 0.55rem 0.95rem;
padding: 0.52rem 0.95rem;
background: var(--accent);
color: #fff;
font-weight: 700;
cursor: pointer;
white-space: nowrap;
flex: 0 0 auto;
}
.filter-btn:focus-visible,
@@ -236,25 +263,45 @@ h1 {
clip: rect(0 0 0 0);
}
@media (max-width: 900px) {
@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;
.view-toggle {
width: 100%;
}
.pipeline-pick select,
.filter-btn {
.seg {
flex: 1 1 0;
}
.pipeline-pick {
flex: 1 1 auto;
min-width: 0;
}
.search {
flex: 1 1 12rem;
}
}
@container pipeline (max-width: 520px) {
.seg-label {
display: none;
}
.filter-btn,
.pipeline-pick {
width: 100%;
flex: 1 1 100%;
}
.filter-btn {
justify-content: center;
}
}
+6
View File
@@ -1000,6 +1000,12 @@ onUnmounted(() => {
overflow-x: clip;
}
@media (max-width: 1280px) and (min-width: 901px) {
.content {
padding-inline: 1rem;
}
}
.burger {
width: 16px;
height: 2px;
+41 -5
View File
@@ -115,6 +115,11 @@ 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;
return startOfLocalDay(new Date(item.dueAt)).getTime() < startOfLocalDay().getTime();
@@ -393,7 +398,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 +446,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 +499,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>
@@ -709,7 +729,12 @@ h1 {
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,
@@ -789,7 +814,7 @@ h1 {
.table {
background: #fff;
border-radius: 18px;
overflow: hidden;
overflow: visible;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
}
@@ -807,12 +832,23 @@ h1 {
font-size: 0.78rem;
font-weight: 700;
border-bottom: 1px solid #f1f5f9;
border-radius: 18px 18px 0 0;
}
.trow {
position: relative;
border-bottom: 1px solid #f8fafc;
}
.trow:last-child {
border-bottom: 0;
border-radius: 0 0 18px 18px;
}
.trow.menu-open {
z-index: 12;
}
.title-cell {
display: flex;
gap: 0.55rem;
+21 -6
View File
@@ -901,22 +901,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 {
@@ -1183,7 +1194,11 @@ watch([id, isNew], () => void load(), { immediate: true });
.priorities {
justify-content: flex-start;
gap: 1.1rem;
gap: 1.15rem;
}
.pri {
gap: 0.32rem;
}
}
</style>
+402 -215
View File
@@ -1,86 +1,202 @@
<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 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 =
trigger.value === 'deal_won' ? 'deal_amount' : 'ticket_priority';
return {
id: `s-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
kind: 'condition',
conditionField: field,
conditionOp: field === 'deal_amount' ? 'gte' : 'eq',
conditionValue: field === 'deal_amount' ? 0 : 'normal',
};
}
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;
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);
ok.value = '';
}
function openRule(row: AutomationRuleDto) {
if (editingId.value === row.id) return;
if (!confirmLeave()) return;
hydrate(row);
ok.value = '';
}
function addStep(payload: AutomationAddPayload, index: number) {
if (steps.value.length >= MAX_AUTOMATION_STEPS) return;
const step = payload.kind === 'condition' ? makeCondition() : makeStep(payload.action);
steps.value.splice(index, 0, step);
selected.value = step.id;
}
function removeStep(id: string) {
const target = steps.value.find((s) => s.id === id);
if (!target) return;
const actionCount = steps.value.filter((s) => !isAutomationCondition(s)).length;
if (!isAutomationCondition(target) && actionCount <= 1) return;
if (steps.value.length <= 1) return;
steps.value = steps.value.filter((s) => s.id !== id);
if (selected.value === id) selected.value = 'trigger';
}
function chainLabel(row: AutomationRuleDto) {
const chain = normalizeAutomationSteps(row.action, row.config);
if (chain.length <= 1) {
return `${AUTOMATION_TRIGGER_LABELS[row.trigger]} → ${AUTOMATION_ACTION_LABELS[row.action]}`;
}
return `${AUTOMATION_TRIGGER_LABELS[row.trigger]} → ${toFaDigits(chain.length)} عمل`;
}
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 current = items.value.find((r) => r.id === editingId.value);
if (current && !dirty.value) hydrate(current);
}
} 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 (!canSave.value || !action) {
error.value = !action ? 'حداقل یک عمل در زنجیره لازم است.' : 'نام قانون را وارد کنید.';
return;
}
saving.value = true;
@@ -90,28 +206,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,121 +231,128 @@ 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);
for (const step of steps.value) {
if (!isAutomationCondition(step)) continue;
if (step.conditionField && allowed.includes(step.conditionField)) continue;
step.conditionField = next === 'deal_won' ? 'deal_amount' : 'ticket_priority';
step.conditionOp = next === 'deal_won' ? 'gte' : 'eq';
step.conditionValue = next === 'deal_won' ? 0 : 'normal';
}
});
</script>
<template>
<section class="page">
<header class="page-head">
<div class="head-copy">
<h1>اگر / آنگاه</h1>
<h1>اتوماسیون</h1>
<p class="lead">
بعد از بردن معامله یا حل شدن تیکت، فعالیت، اعلان یا امتیاز باشگاه بسازید.
مثل یک بوم کاری: گره «اگر» را به چند عمل پشت‌سرهم وصل کنید.
</p>
</div>
<button class="btn ghost" type="button" :disabled="loading" @click="load">
بروزرسانی
</button>
<div class="head-actions">
<button class="btn ghost" type="button" :disabled="loading" @click="load">
بروزرسانی
</button>
<button class="btn primary" type="button" @click="startNew">
<UiIcon name="plus" :size="16" />
قانون جدید
</button>
</div>
</header>
<p v-if="error" class="error">{{ error }}</p>
<p v-if="ok" class="ok">{{ 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>
<div class="workspace">
<aside class="rules">
<h2>قوانین</h2>
<ul>
<li
v-for="row in items"
:key="row.id"
:class="{ on: editingId === row.id }"
>
<button class="pick" type="button" @click="openRule(row)">
<strong>{{ row.name }}</strong>
<span>{{ chainLabel(row) }}</span>
</button>
<div class="mini">
<button type="button" @click="toggleActive(row)">
{{ row.isActive ? 'فعال' : 'غیرفعال' }}
</button>
<button class="danger" type="button" @click="removeRule(row.id)">
حذف
</button>
</div>
</li>
</ul>
<p v-if="!items.length && !loading" class="muted">هنوز قانونی نیست.</p>
</aside>
<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)">
حذف
</button>
</div>
</li>
</ul>
<p v-if="!items.length && !loading" class="muted">هنوز قانونی نیست.</p>
</section>
<div class="studio">
<div class="toolbar">
<label class="name">
نام قانون
<input v-model="name" type="text" required minlength="2" maxlength="120" />
</label>
<label class="check">
<input v-model="isActive" type="checkbox" />
فعال
</label>
<button
class="btn primary"
type="button"
:disabled="saving || !canSave"
@click="save"
>
{{ saving ? 'در حال ذخیره…' : editingId ? 'ذخیره' : 'ساخت' }}
</button>
</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>
@@ -243,9 +360,7 @@ onMounted(load);
.page {
display: grid;
gap: 1rem;
max-width: 860px;
min-width: 0;
overflow-x: clip;
}
.page-head {
@@ -260,6 +375,12 @@ onMounted(load);
min-width: 0;
}
.head-actions {
display: flex;
gap: 0.55rem;
flex-wrap: wrap;
}
h1 {
margin: 0 0 0.3rem;
font-size: clamp(1.45rem, 2.5vw, 1.85rem);
@@ -272,57 +393,147 @@ h1 {
color: #64748b;
}
.panel {
.workspace {
display: grid;
grid-template-columns: 1fr;
gap: 0.9rem;
align-items: start;
}
.rules,
.studio {
border: 1px solid #e2e8f0;
border-radius: 18px;
padding: 1.1rem;
background: #fff;
box-shadow: 0 8px 22px rgba(15, 23, 42, 0.04);
}
.rules {
padding: 1rem;
display: grid;
gap: 0.75rem;
gap: 0.7rem;
align-content: start;
}
h2 {
margin: 0;
font-size: 1.05rem;
font-weight: 700;
color: #0f172a;
font-size: 1rem;
font-weight: 800;
}
.form label {
.rules ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.45rem;
}
.rules li {
border: 1px solid #e8eef3;
border-radius: 14px;
padding: 0.55rem 0.65rem 0.45rem;
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;
.rules li.on {
border-color: #99f6e4;
background: #f0fdfa;
}
.grid2 {
.pick {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.15rem;
text-align: start;
border: 0;
background: none;
padding: 0;
cursor: pointer;
font: inherit;
color: inherit;
}
.pick strong {
font-size: 0.9rem;
}
.pick span {
color: #64748b;
font-size: 0.75rem;
}
.mini {
display: flex;
gap: 0.65rem;
}
.mini button {
border: 0;
background: none;
color: #0f766e;
cursor: pointer;
font: inherit;
font-size: 0.78rem;
font-weight: 700;
padding: 0;
}
.mini .danger {
color: #b91c1c;
}
.studio {
padding: 0.85rem;
display: grid;
gap: 0.75rem;
min-width: 0;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.7rem;
align-items: end;
}
.name {
display: grid;
gap: 0.3rem;
font-size: 0.82rem;
color: #64748b;
flex: 1 1 14rem;
}
.name input {
border: 1px solid #e2e8f0;
border-radius: 12px;
padding: 0.55rem 0.7rem;
font: inherit;
color: #0f172a;
}
.check {
display: flex !important;
display: flex;
align-items: center;
gap: 0.45rem;
gap: 0.4rem;
color: #334155;
font-size: 0.88rem;
padding-bottom: 0.45rem;
}
.stage {
display: grid;
grid-template-columns: 1fr;
gap: 0.75rem;
min-width: 0;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
min-height: 42px;
padding: 0.55rem 1rem;
border-radius: 12px;
@@ -338,49 +549,15 @@ textarea {
box-shadow: 0 8px 18px rgba(20, 184, 166, 0.24);
}
.btn.primary:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.btn.ghost {
background: #fff;
color: #0f766e;
border-color: #99f6e4;
box-shadow: none;
}
.actions,
.row-actions {
display: flex;
gap: 0.55rem;
flex-wrap: wrap;
}
.list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: 0.7rem;
}
.list li {
display: flex;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
border-bottom: 1px solid #e2e8f0;
padding-bottom: 0.65rem;
}
.link {
background: none;
border: none;
color: #0f766e;
cursor: pointer;
font: inherit;
padding: 0;
font-weight: 600;
}
.danger {
color: #b91c1c;
}
.error {
@@ -394,16 +571,26 @@ textarea {
font-weight: 600;
}
@media (max-width: 700px) {
.grid2 {
grid-template-columns: 1fr;
@media (min-width: 1280px) {
.workspace {
grid-template-columns: minmax(15rem, 17.5rem) minmax(0, 1fr);
}
.actions,
.row-actions,
.list li {
flex-direction: column;
align-items: stretch;
.stage {
grid-template-columns: minmax(0, 1fr) minmax(16rem, 19rem);
}
}
@media (max-width: 1279px) {
.rules ul {
display: flex;
overflow-x: auto;
gap: 0.5rem;
}
.rules li {
min-width: 13rem;
flex: 0 0 auto;
}
}
</style>
+3 -3
View File
@@ -303,9 +303,9 @@ async function load() {
closeMenus();
try {
const [invRes, quoteRes, peopleRes] = await Promise.all([
api.get<PaginatedResponse<InvoiceDto>>('/invoices', { params: { limit: 200 } }),
api.get<PaginatedResponse<QuoteDto>>('/quotes', { params: { limit: 200 } }),
api.get<PaginatedResponse<PersonDto>>('/people', { params: { limit: 200 } }),
api.get<PaginatedResponse<InvoiceDto>>('/invoices', { params: { limit: 100 } }),
api.get<PaginatedResponse<QuoteDto>>('/quotes', { params: { limit: 100 } }),
api.get<PaginatedResponse<PersonDto>>('/people', { params: { limit: 100 } }),
]);
invoices.value = invRes.data.items;
quotes.value = quoteRes.data.items;
+33 -34
View File
@@ -7,6 +7,7 @@ import { formatJalaliNumeric } from '@/lib/jalali';
import PipelineToolbar from '@/components/pipeline/PipelineToolbar.vue';
import type { PipelineViewMode } from '@/components/pipeline/PipelineToolbar.vue';
import PipelineBoard from '@/components/pipeline/PipelineBoard.vue';
import PipelineList from '@/components/pipeline/PipelineList.vue';
import DealCardOverlay from '@/components/pipeline/DealCardOverlay.vue';
import type { PipelineDeal, PipelineStage } from '@/lib/pipeline-board';
import {
@@ -45,7 +46,7 @@ const moving = ref(false);
const pipelineOptions = computed(() =>
pipelines.value.map((p) => ({
id: p.id,
name: p.isDefault ? `${p.name} (پیش‌فرض)` : p.name,
name: p.name,
})),
);
@@ -264,25 +265,14 @@ defineExpose({ updateDealStage: applyUpdateDealStage });
:selected-pipeline-id="selectedPipelineId"
:view-mode="viewMode"
:search="search"
:can-create="canCreatePipeline"
@update:view-mode="viewMode = $event"
@update:search="search = $event"
@update:selected-pipeline-id="selectedPipelineId = $event"
@filter="onFilter"
@create="showCreate = !showCreate"
/>
<div v-if="canCreatePipeline" class="create-row">
<button
class="btn-ghost-sm"
type="button"
@click="showCreate = !showCreate"
>
کاریز جدید
</button>
<button class="btn-ghost-sm" type="button" :disabled="loading" @click="load">
بروزرسانی
</button>
</div>
<form
v-if="showCreate && canCreatePipeline"
class="create-box"
@@ -305,12 +295,15 @@ defineExpose({ updateDealStage: applyUpdateDealStage });
<p v-if="error" class="error">{{ error }}</p>
<p v-else-if="loading && !stages.length" class="muted">در حال بارگذاری کاریز…</p>
<div v-if="viewMode === 'list'" class="list-placeholder">
نمای لیست معاملات
</div>
<PipelineList
v-if="viewMode === 'list' && (!loading || stages.length)"
:stages="visibleStages"
@open-deal="onOpenDeal"
@menu-deal="onMenuDeal"
/>
<PipelineBoard
v-else-if="stages.length"
v-else-if="viewMode === 'kanban' && stages.length"
:stages="visibleStages"
:dragging-id="draggingId"
:drop-stage-id="dropStageId"
@@ -345,16 +338,13 @@ defineExpose({ updateDealStage: applyUpdateDealStage });
<style scoped>
.page {
display: grid;
gap: 0.55rem;
gap: 0.15rem;
min-width: 0;
max-width: 100%;
direction: rtl;
text-align: right;
}
.create-row {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
container-type: inline-size;
container-name: pipeline;
}
.btn-ghost-sm {
@@ -373,10 +363,12 @@ defineExpose({ updateDealStage: applyUpdateDealStage });
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
min-width: 0;
}
.create-box input {
flex: 1 1 180px;
min-width: 0;
border: 1px solid var(--line);
border-radius: 12px;
padding: 0.65rem 0.85rem;
@@ -384,21 +376,28 @@ defineExpose({ updateDealStage: applyUpdateDealStage });
font: inherit;
}
.list-placeholder {
margin-top: 0.5rem;
padding: 2.5rem 1rem;
text-align: center;
color: var(--muted);
background: var(--surface);
border: 1px dashed var(--line);
border-radius: var(--radius);
font-weight: 700;
@container pipeline (max-width: 560px) {
.create-box {
flex-direction: column;
align-items: stretch;
}
.create-box input,
.create-box .btn,
.create-box .btn-ghost-sm {
width: 100%;
}
}
.muted {
color: var(--muted);
}
.error {
color: var(--danger);
font-weight: 600;
}
.menu-pop {
position: fixed;
inset-inline-start: 1rem;
+181
View File
@@ -1739,13 +1739,123 @@ export const AUTOMATION_ACTION_LABELS: Record<AutomationAction, string> = {
add_loyalty_points: "افزودن امتیاز باشگاه",
};
export const MAX_AUTOMATION_STEPS = 8;
export const AUTOMATION_ACTIONS = [
"create_activity",
"create_notification",
"add_loyalty_points",
] as const satisfies readonly AutomationAction[];
export const AUTOMATION_TRIGGERS = [
"deal_won",
"ticket_resolved",
] as const satisfies readonly AutomationTrigger[];
export type AutomationStepKind = "action" | "condition";
export type AutomationConditionField =
| "deal_amount"
| "has_person"
| "has_company"
| "ticket_priority";
export type AutomationConditionOp =
| "gte"
| "lte"
| "eq"
| "neq"
| "is_set"
| "is_empty";
export type AutomationNotifyChannel = "app" | "sms" | "both";
export type AutomationNotifyTarget = "staff" | "person";
export const AUTOMATION_CONDITION_FIELD_LABELS: Record<
AutomationConditionField,
string
> = {
deal_amount: "مبلغ معامله",
has_person: "مخاطب دارد",
has_company: "شرکت دارد",
ticket_priority: "اولویت تیکت",
};
export const AUTOMATION_CONDITION_OP_LABELS: Record<
AutomationConditionOp,
string
> = {
gte: "بزرگ‌تر یا مساوی",
lte: "کوچک‌تر یا مساوی",
eq: "مساوی",
neq: "نامساوی",
is_set: "دارد",
is_empty: "ندارد",
};
export const AUTOMATION_NOTIFY_CHANNEL_LABELS: Record<
AutomationNotifyChannel,
string
> = {
app: "ناتیفیکیشن داخلی",
sms: "پیامک",
both: "هر دو",
};
export const AUTOMATION_NOTIFY_CHANNELS = [
"app",
"sms",
"both",
] as const satisfies readonly AutomationNotifyChannel[];
export function isAutomationCondition(step: Pick<AutomationStep, "kind">): boolean {
return step.kind === "condition";
}
export function firstAutomationAction(
steps: AutomationStep[],
): AutomationAction | null {
const step = steps.find((s) => !isAutomationCondition(s) && s.action);
return step?.action ?? null;
}
export function conditionFieldsForTrigger(
trigger: AutomationTrigger,
): AutomationConditionField[] {
if (trigger === "deal_won") {
return ["deal_amount", "has_person", "has_company"];
}
return ["ticket_priority", "has_person", "has_company"];
}
export interface AutomationStep {
id: string;
kind?: AutomationStepKind;
action?: AutomationAction;
title?: string;
body?: string;
assigneeId?: string | null;
notifyUserId?: string | null;
notifyChannel?: AutomationNotifyChannel;
notifyTarget?: AutomationNotifyTarget;
activityType?: "call" | "meeting" | "task" | "note";
points?: number;
conditionField?: AutomationConditionField;
conditionOp?: AutomationConditionOp;
conditionValue?: string | number;
}
export interface AutomationRuleConfig {
title?: string;
body?: string;
assigneeId?: string | null;
notifyUserId?: string | null;
notifyChannel?: AutomationNotifyChannel;
notifyTarget?: AutomationNotifyTarget;
activityType?: "call" | "meeting" | "task" | "note";
points?: number;
/** زنجیرهٔ اعمال؛ اگر خالی باشد همان action تکی استفاده می‌شود */
steps?: AutomationStep[];
}
export interface AutomationRuleDto {
@@ -1769,6 +1879,77 @@ export interface CreateAutomationRuleRequest {
export type UpdateAutomationRuleRequest = Partial<CreateAutomationRuleRequest>;
export function normalizeAutomationSteps(
action: AutomationAction,
config?: AutomationRuleConfig | null,
): AutomationStep[] {
const cfg = config ?? {};
if (Array.isArray(cfg.steps) && cfg.steps.length) {
return cfg.steps
.filter((s) => s && (s.kind === "condition" || s.action))
.map((s, i) => ({
id: s.id || `step-${i}`,
kind: s.kind === "condition" ? "condition" : "action",
action: s.action,
title: s.title,
body: s.body,
assigneeId: s.assigneeId,
notifyUserId: s.notifyUserId,
notifyChannel: s.notifyChannel,
notifyTarget: s.notifyTarget,
activityType: s.activityType,
points: s.points,
conditionField: s.conditionField,
conditionOp: s.conditionOp,
conditionValue: s.conditionValue,
}));
}
return [
{
id: "step-0",
kind: "action",
action,
title: cfg.title,
body: cfg.body,
assigneeId: cfg.assigneeId,
notifyUserId: cfg.notifyUserId,
notifyChannel: cfg.notifyChannel,
notifyTarget: cfg.notifyTarget,
activityType: cfg.activityType,
points: cfg.points,
},
];
}
export function packAutomationConfig(steps: AutomationStep[]): AutomationRuleConfig {
const first =
steps.find((s) => (s.kind ?? "action") !== "condition") ?? steps[0];
return {
steps,
title: first?.title,
body: first?.body,
assigneeId: first?.assigneeId,
notifyUserId: first?.notifyUserId,
notifyChannel: first?.notifyChannel,
notifyTarget: first?.notifyTarget,
activityType: first?.activityType,
points: first?.points,
};
}
export function automationStepToConfig(step: AutomationStep): AutomationRuleConfig {
return {
title: step.title,
body: step.body,
assigneeId: step.assigneeId,
notifyUserId: step.notifyUserId,
notifyChannel: step.notifyChannel,
notifyTarget: step.notifyTarget,
activityType: step.activityType,
points: step.points,
};
}
// —— ته‌حساب / حسابداری ——
export const TAHSAB_SANAD_TYPES = [