Files
CRM_Montzar/apps/web/src/components/automations/AutomationCanvas.vue
T

756 lines
19 KiB
Vue

<script setup lang="ts">
import { computed, ref } from 'vue';
import UiIcon from '@/components/UiIcon.vue';
import AutomationNode from '@/components/automations/AutomationNode.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,
formConditionValues,
isAutomationCondition,
splitAutomationBranches,
type AutomationAction,
type AutomationChainMode,
type AutomationStep,
type AutomationTrigger,
type LeadFormDto,
type OrgUserDto,
type TeamDto,
} from '@mento/shared';
import { toFaDigits } from '@/lib/jalali';
export type AutomationAddPayload =
| { kind: 'action'; action: AutomationAction }
| { kind: 'condition' };
type AddAllow = 'both' | 'action' | 'condition';
type LaneItem =
| { kind: 'wire'; key: string; index: number; allow: AddAllow; end?: boolean }
| { kind: 'node'; key: string; index: number };
type BranchLane = { key: string; start: number; end: number; items: LaneItem[] };
const props = withDefaults(
defineProps<{
trigger: AutomationTrigger;
steps: AutomationStep[];
selected: 'trigger' | string;
chainMode?: AutomationChainMode;
form?: LeadFormDto | null;
users?: OrgUserDto[];
teams?: TeamDto[];
}>(),
{ chainMode: 'stop', form: null, users: () => [], teams: () => [] },
);
const emit = defineEmits<{
select: [id: 'trigger' | string];
add: [payload: AutomationAddPayload, index: number];
remove: [id: string];
removeRange: [start: number, end: number];
addBranch: [];
}>();
const addAt = ref<{ key: string; index: number; allow: AddAllow } | null>(null);
const canAdd = computed(() => props.steps.length < MAX_AUTOMATION_STEPS);
const actionCount = computed(
() => props.steps.filter((s) => !isAutomationCondition(s)).length,
);
const layout = computed((): { main: LaneItem[]; branches: BranchLane[] } => {
const steps = props.steps;
const { prefixEnd, branches } = splitAutomationBranches(steps);
if (props.chainMode !== 'branches' || !branches.length) {
const main: LaneItem[] = [];
steps.forEach((s, i) => {
main.push({ kind: 'wire', key: `w-${s.id}`, index: i, allow: 'both' });
main.push({ kind: 'node', key: s.id, index: i });
});
main.push({ kind: 'wire', key: 'w-end', index: steps.length, allow: 'both', end: true });
return { main, branches: [] };
}
const main: LaneItem[] = [];
for (let i = 0; i < prefixEnd; i++) {
main.push({ kind: 'wire', key: `w-${steps[i].id}`, index: i, allow: 'action' });
main.push({ kind: 'node', key: steps[i].id, index: i });
}
const lanes = branches.map((b): BranchLane => {
const items: LaneItem[] = [];
for (let j = b.start; j < b.end; j++) {
const allow: AddAllow =
j === b.start || isAutomationCondition(steps[j])
? 'condition'
: isAutomationCondition(steps[j - 1])
? 'both'
: 'action';
items.push({ kind: 'wire', key: `w-${steps[j].id}`, index: j, allow });
items.push({ kind: 'node', key: steps[j].id, index: j });
}
const last = steps[b.end - 1];
items.push({
kind: 'wire',
key: `w-end-${steps[b.start].id}`,
index: b.end,
allow: isAutomationCondition(last) ? 'both' : 'action',
end: true,
});
return { key: steps[b.start].id, start: b.start, end: b.end, items };
});
return { main, branches: lanes };
});
const forked = computed(() => layout.value.branches.length > 0);
const canAddBranch = computed(() => {
if (props.steps.length + 2 > MAX_AUTOMATION_STEPS) return false;
const last = props.steps[props.steps.length - 1];
return !last || !isAutomationCondition(last);
});
function branchActionCount(lane: BranchLane) {
return props.steps
.slice(lane.start, lane.end)
.filter((s) => !isAutomationCondition(s)).length;
}
function canRemoveBranch(lane: BranchLane) {
return actionCount.value - branchActionCount(lane) >= 1;
}
function canRemove(index: number) {
const step = props.steps[index];
if (!step || props.steps.length <= 1) return false;
if (!isAutomationCondition(step)) return actionCount.value > 1;
if (!forked.value) return true;
const lane = layout.value.branches.find((b) => index >= b.start && index < b.end);
if (!lane) return true;
const conds = props.steps
.slice(lane.start, lane.end)
.filter((s) => isAutomationCondition(s)).length;
return conds > 1;
}
function userName(id?: string | null) {
return props.users.find((u) => u.id === id)?.fullName ?? 'کاربر';
}
function assignHint(step: AutomationStep) {
const mode = step.assignMode ?? (step.assigneeId ? 'user' : 'owner');
if (mode === 'user') return userName(step.assigneeId);
if (mode === 'team_round_robin') {
const t = props.teams.find((x) => x.id === step.assigneeTeamId);
return `نوبتی: ${t?.name ?? 'تیم'}`;
}
if (mode === 'users_round_robin') {
return `نوبتی بین ${toFaDigits((step.assigneeUserIds ?? []).length)} نفر`;
}
return 'مسئول پرونده';
}
function actionIcon(action: AutomationAction) {
if (action === 'create_notification') return 'bell';
if (action === 'add_loyalty_points') return 'gift';
return 'flag';
}
function stepTitle(step: AutomationStep) {
if (isAutomationCondition(step)) {
const field = step.conditionField ?? 'has_person';
if (field === 'form_field') {
const f = props.form?.fields.find((x) => x.key === step.conditionKey);
return f?.label ?? AUTOMATION_CONDITION_FIELD_LABELS[field];
}
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 === 'form_field') {
if (op === 'is_set' || op === 'is_empty') return opLabel;
const joiner = op === 'contains_any' || op === 'not_contains' ? ' یا ' : ' و ';
return `${opLabel} ${formConditionValues(step).map((v) => `«${v}»`).join(joiner) || '«»'}`;
}
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'] ?? 'وظیفه'} — ${assignHint(step)}`;
}
function openAdd(item: { key: string; index: number; allow: AddAllow }) {
if (!canAdd.value) return;
addAt.value =
addAt.value?.key === item.key
? null
: { key: item.key, index: item.index, allow: item.allow };
}
function pickAction(action: AutomationAction) {
if (!addAt.value) return;
emit('add', { kind: 'action', action }, addAt.value.index);
addAt.value = null;
}
function pickCondition() {
if (!addAt.value) return;
emit('add', { kind: 'condition' }, addAt.value.index);
addAt.value = null;
}
function removeBranch(lane: BranchLane) {
addAt.value = null;
emit('removeRange', lane.start, lane.end);
}
</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="item in layout.main" :key="item.key">
<div
v-if="item.kind === 'wire'"
class="wire"
:class="{ open: addAt?.key === item.key, end: item.end }"
>
<button
v-if="canAdd"
class="plus"
:class="{ big: item.end }"
type="button"
title="افزودن گره"
@click.stop="openAdd(item)"
>
<UiIcon name="plus" :size="item.end ? 16 : 14" />
</button>
</div>
<AutomationNode
v-else
:step="steps[item.index]"
:title="stepTitle(steps[item.index])"
:hint="stepHint(steps[item.index])"
:selected="selected === steps[item.index].id"
:removable="canRemove(item.index)"
@select="emit('select', steps[item.index].id)"
@remove="emit('remove', steps[item.index].id)"
/>
</template>
<template v-if="forked">
<div class="wire stub" />
<div class="branches">
<div v-for="(lane, bi) in layout.branches" :key="lane.key" class="branch">
<div class="branch-tag">
<span>شاخه {{ toFaDigits(bi + 1) }}</span>
<button
v-if="canRemoveBranch(lane)"
type="button"
title="حذف این شاخه"
@click.stop="removeBranch(lane)"
>
<UiIcon name="trash" :size="12" />
</button>
</div>
<template v-for="item in lane.items" :key="item.key">
<div
v-if="item.kind === 'wire'"
class="wire"
:class="{ open: addAt?.key === item.key, end: item.end }"
>
<button
v-if="canAdd"
class="plus"
type="button"
:title="item.allow === 'condition' ? 'افزودن شرط («و»)' : 'افزودن گره'"
@click.stop="openAdd(item)"
>
<UiIcon name="plus" :size="14" />
</button>
</div>
<AutomationNode
v-else
:step="steps[item.index]"
:title="stepTitle(steps[item.index])"
:hint="stepHint(steps[item.index])"
:selected="selected === steps[item.index].id"
:removable="canRemove(item.index)"
@select="emit('select', steps[item.index].id)"
@remove="emit('remove', steps[item.index].id)"
/>
</template>
</div>
<button
class="add-branch"
type="button"
:disabled="!canAddBranch"
:title="canAddBranch ? '' : 'ابتدا برای شاخهٔ آخر یک عمل بگذارید'"
@click.stop="emit('addBranch')"
>
<UiIcon name="plus" :size="14" />
شاخهٔ جدید
</button>
</div>
</template>
</div>
<div v-if="addAt" class="picker" @click.stop>
<p>
{{
addAt.allow === 'condition'
? 'شرط جدید با «و» به شرط‌های این شاخه اضافه می‌شود'
: 'گره بعدی را انتخاب کنید'
}}
</p>
<div class="picks">
<button
v-if="addAt.allow !== 'action'"
type="button"
class="condition"
@click="pickCondition"
>
<UiIcon name="filter" :size="16" />
شرط
</button>
<template v-if="addAt.allow !== 'condition'">
<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>
</template>
</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;
min-width: max-content;
min-height: 16rem;
}
.node.trigger {
width: 14.2rem;
min-height: 4.35rem;
display: flex;
align-items: center;
gap: 0.7rem;
text-align: start;
border-radius: 999px;
padding: 0.72rem 1rem;
border: 1px solid #fdba74;
background: #fff7ed;
box-shadow: 0 10px 24px rgba(23, 33, 28, 0.06);
cursor: pointer;
color: inherit;
font: inherit;
flex-shrink: 0;
}
.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);
}
.icon {
width: 2.35rem;
height: 2.35rem;
border-radius: 999px;
display: grid;
place-items: center;
flex-shrink: 0;
color: #c2410c;
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;
}
.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;
}
.wire.stub {
width: 1.6rem;
}
.wire.stub::after {
display: none;
}
.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;
}
/* انشعاب: یک خط عمودی که از وسط اولین شاخه تا وسط آخرین شاخه کشیده می‌شود */
.flow:has(.branches) {
padding-bottom: 2.6rem;
}
.branches {
position: relative;
display: flex;
flex-direction: column;
align-items: flex-start;
}
.branch {
position: relative;
display: flex;
align-items: center;
padding-block: 1.3rem;
}
.branch::before {
content: '';
position: absolute;
inset-inline-start: 0;
width: 2px;
top: 0;
bottom: 0;
background: #cbd5e1;
}
.branch:first-of-type::before {
top: 50%;
}
.branch:last-of-type::before {
bottom: 50%;
}
.branch-tag {
position: absolute;
top: 0.05rem;
inset-inline-start: 0.9rem;
display: inline-flex;
align-items: center;
gap: 0.25rem;
font-size: 0.68rem;
font-weight: 700;
color: #b45309;
background: #fff7ed;
border: 1px solid #fed7aa;
border-radius: 999px;
padding: 0.05rem 0.5rem;
white-space: nowrap;
}
.branch-tag button {
display: grid;
place-items: center;
border: 0;
background: none;
padding: 0;
color: #b91c1c;
cursor: pointer;
}
.add-branch {
position: absolute;
top: 100%;
inset-inline-start: 0.9rem;
display: inline-flex;
white-space: nowrap;
align-items: center;
gap: 0.35rem;
border: 1px dashed #f59e0b;
background: #fffbeb;
color: #b45309;
border-radius: 999px;
padding: 0.35rem 0.8rem;
font: inherit;
font-size: 0.78rem;
font-weight: 700;
cursor: pointer;
}
.add-branch:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.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) {
.canvas {
min-height: 0;
padding: 1rem 0.75rem;
}
.flow,
.flow:has(.branches) {
flex-direction: column;
align-items: center;
min-width: 0;
min-height: 0;
padding-bottom: 0;
}
.node.trigger {
width: min(100%, 15rem);
}
.wire,
.wire.stub {
width: 2px;
height: 2.1rem;
}
.wire::after {
inset-inline-end: auto;
top: auto;
bottom: -1px;
left: 50%;
transform: translateX(-50%);
border-block: 0;
border-inline: 5px solid transparent;
border-top: 7px solid #cbd5e1;
}
.wire.end {
width: 2px;
height: 2.4rem;
background: repeating-linear-gradient(180deg, #cbd5e1 0 6px, transparent 6px 10px);
}
.branches {
align-items: stretch;
width: 100%;
gap: 0.75rem;
}
.branch {
flex-direction: column;
align-items: center;
padding: 1.9rem 0.5rem 0.5rem;
border: 1px dashed #fed7aa;
border-radius: var(--radius);
background: rgba(255, 255, 255, 0.55);
}
.branch::before {
display: none;
}
.branch-tag {
top: 0.45rem;
inset-inline-start: 0.6rem;
}
.add-branch {
position: static;
align-self: center;
}
.picker {
max-width: none;
}
}
</style>