7 Commits
Author SHA1 Message Date
MahdiandCursor 9bed6cac03 fix(api): guard unmoved deals before pipeline merge delete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 21:32:21 +03:30
MahdiandCursor fd6e79c15d feat(web): pipeline merge wizard
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:55:14 +03:30
MahdiandCursor 9b42fec0a8 feat(web): pipeline settings page and nav entry
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:33:29 +03:30
MahdiandCursor d00f362376 feat(api): pipeline merge preview and merge endpoints
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:23:56 +03:30
MahdiandCursor fd8966e13f feat(pipelines): merge stage-map util and shared DTOs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:15:11 +03:30
MahdiandCursor 91eb9be1d4 docs: add pipeline merge implementation plan
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:10:03 +03:30
MahdiandCursor ffae63edbf docs: add pipeline merge design spec
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 20:07:09 +03:30
15 changed files with 1757 additions and 1 deletions
+17
View File
@@ -0,0 +1,17 @@
# Task 5 report
Status: DONE
- shared build: OK
- pipeline-merge.test.ts: 5/5 pass
- api typecheck: OK
- vue-tsc: see VUE_EXIT in controller log
- graphify: attempted (may crash)
No commit required for verification-only task.
## Follow-up fix: final review important findings
Status: DONE
- I-1: Added in-transaction unmoved-deal count guard before deleting the source pipeline.
- I-3: Added 30000ms timeout to the interactive merge transaction.
- M-1: Added `@IsIn(['retarget_all'])` validation to `MergePipelineDto.leadFormMode`.
- graphify update: OK
- `cd apps/api; npx tsx --test test/pipeline-merge.test.ts`: OK, 5/5 pass
- `npm run typecheck -w @mento/api`: OK
+1 -1
View File
@@ -12,7 +12,7 @@
"prisma:seed": "tsx prisma/seed.ts",
"lint": "echo \"api lint placeholder\"",
"typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p test/tsconfig.json",
"test": "tsx --test test/tahesab-methods.test.ts test/dates.test.ts test/message-automation.test.ts test/record-scope.test.ts test/gamification-engine.test.ts test/automation-branches.test.ts"
"test": "tsx --test test/tahesab-methods.test.ts test/dates.test.ts test/message-automation.test.ts test/record-scope.test.ts test/gamification-engine.test.ts test/automation-branches.test.ts test/pipeline-merge.test.ts"
},
"dependencies": {
"@mento/shared": "*",
+15
View File
@@ -4,6 +4,7 @@ import {
IsArray,
IsBoolean,
IsDateString,
IsIn,
IsInt,
IsNumber,
IsObject,
@@ -351,3 +352,17 @@ export class MoveDealDto {
@Min(0)
position?: number;
}
export class MergePipelineDto {
@IsString()
@MinLength(1)
targetPipelineId!: string;
@IsObject()
stageMap!: Record<string, string>;
@IsOptional()
@IsString()
@IsIn(['retarget_all'])
leadFormMode?: 'retarget_all';
}
@@ -0,0 +1,41 @@
export type MergeStageLike = {
id: string;
name: string;
isWon: boolean;
isLost: boolean;
};
export function dealStatusForStage(
stage: Pick<MergeStageLike, 'isWon' | 'isLost'>,
): 'open' | 'won' | 'lost' {
if (stage.isWon) return 'won';
if (stage.isLost) return 'lost';
return 'open';
}
export function assertStageMap(
sourceStages: MergeStageLike[],
targetStages: MergeStageLike[],
stageMap: Record<string, string>,
): void {
const targetById = new Map(targetStages.map((s) => [s.id, s]));
for (const src of sourceStages) {
const tid = stageMap[src.id];
if (!tid) {
throw new Error(`همهٔ ستون‌های مبدأ باید نگاشت شوند (ستون «${src.name}»).`);
}
const tgt = targetById.get(tid);
if (!tgt) {
throw new Error(`ستون مقصد برای «${src.name}» معتبر نیست.`);
}
if (src.isWon && !tgt.isWon) {
throw new Error(`ستون برندهٔ «${src.name}» فقط به ستون برندهٔ مقصد نگاشت می‌شود.`);
}
if (src.isLost && !tgt.isLost) {
throw new Error(`ستون از دست‌رفتهٔ «${src.name}» فقط به ستون از دست‌رفتهٔ مقصد نگاشت می‌شود.`);
}
if (!src.isWon && !src.isLost && (tgt.isWon || tgt.isLost)) {
throw new Error(`ستون باز «${src.name}» را به ستون برد/باخت مقصد نگاشت نکنید.`);
}
}
}
@@ -17,6 +17,7 @@ import type { Actor } from '../common/record-scope';
import {
CreatePipelineDto,
CreatePipelineStageDto,
MergePipelineDto,
ReorderPipelineStagesDto,
UpdatePipelineStageDto,
} from './dto';
@@ -49,6 +50,25 @@ export class PipelinesController {
return this.pipelinesService.create(user.organizationId, dto.name);
}
@Get(':pipelineId/merge-preview')
@Roles('owner', 'admin')
mergePreview(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
) {
return this.pipelinesService.mergePreview(user.organizationId, pipelineId);
}
@Post(':pipelineId/merge')
@Roles('owner', 'admin')
merge(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
@Body() dto: MergePipelineDto,
) {
return this.pipelinesService.merge(user.organizationId, pipelineId, dto);
}
@Post(':pipelineId/stages')
@Roles('owner', 'admin')
createStage(
+192
View File
@@ -5,8 +5,10 @@ import {
} from '@nestjs/common';
import type {
DealDto,
MergePipelineResultDto,
PipelineBoardDto,
PipelineDto,
PipelineMergePreviewDto,
PipelineStageDto,
} from '@mento/shared';
import { Prisma } from '@prisma/client';
@@ -14,6 +16,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { asCustomFields } from '../common/custom-fields';
import { type Actor, dealAccessWhere } from '../common/record-scope';
import { decimalToBase, loadOrgRates } from '../common/currency';
import { assertStageMap, dealStatusForStage } from './pipeline-merge.util';
export const DEFAULT_STAGES = [
{ name: 'سرنخ', isWon: false, isLost: false },
@@ -329,6 +332,195 @@ export class PipelinesService {
};
}
async mergePreview(
organizationId: string,
sourceId: string,
): Promise<PipelineMergePreviewDto> {
const source = await this.getOwnedPipeline(organizationId, sourceId);
const dealCounts = await this.prisma.deal.groupBy({
by: ['stageId'],
where: { organizationId, pipelineId: source.id },
_count: { _all: true },
});
const countByStage = new Map(
dealCounts.map((row) => [row.stageId, row._count._all]),
);
const leadForms = await this.prisma.leadForm.findMany({
where: { organizationId, pipelineId: source.id },
select: { id: true, name: true, isActive: true },
orderBy: { updatedAt: 'desc' },
});
const targets = await this.prisma.pipeline.findMany({
where: { organizationId, id: { not: source.id } },
include: { stages: { orderBy: { position: 'asc' } } },
orderBy: [{ isDefault: 'desc' }, { name: 'asc' }],
});
const stages = source.stages.map((stage) => ({
id: stage.id,
name: stage.name,
isWon: stage.isWon,
isLost: stage.isLost,
dealCount: countByStage.get(stage.id) ?? 0,
}));
return {
source: {
id: source.id,
name: source.name,
isDefault: source.isDefault,
},
stages,
dealCount: stages.reduce((sum, stage) => sum + stage.dealCount, 0),
leadForms,
targets: targets.map((target) => ({
id: target.id,
name: target.name,
isDefault: target.isDefault,
stages: target.stages.map((stage) => ({
id: stage.id,
name: stage.name,
isWon: stage.isWon,
isLost: stage.isLost,
})),
})),
};
}
async merge(
organizationId: string,
sourceId: string,
dto: {
targetPipelineId: string;
stageMap: Record<string, string>;
leadFormMode?: 'retarget_all';
},
): Promise<MergePipelineResultDto> {
if (sourceId === dto.targetPipelineId) {
throw new BadRequestException('مسیر مقصد باید با مسیر مبدأ متفاوت باشد');
}
if ((dto.leadFormMode ?? 'retarget_all') !== 'retarget_all') {
throw new BadRequestException('روش انتقال فرم‌های جذب نامعتبر است');
}
const [source, target] = await Promise.all([
this.getOwnedPipeline(organizationId, sourceId),
this.getOwnedPipeline(organizationId, dto.targetPipelineId),
]);
try {
assertStageMap(source.stages, target.stages, dto.stageMap);
} catch (error) {
throw new BadRequestException(
error instanceof Error ? error.message : 'نگاشت ستون‌ها نامعتبر است',
);
}
const targetStagesById = new Map(
target.stages.map((stage) => [stage.id, stage]),
);
let movedDeals = 0;
let retargetedLeadForms = 0;
await this.prisma.$transaction(
async (tx) => {
const closedAt = new Date();
for (const sourceStage of source.stages) {
const targetStageId = dto.stageMap[sourceStage.id];
const targetStage = targetStagesById.get(targetStageId);
if (!targetStage) {
throw new BadRequestException('نگاشت ستون‌ها نامعتبر است');
}
const status = dealStatusForStage(targetStage);
if (status === 'open') {
const result = await tx.deal.updateMany({
where: {
organizationId,
pipelineId: source.id,
stageId: sourceStage.id,
},
data: {
pipelineId: target.id,
stageId: targetStage.id,
status,
closedAt: null,
},
});
movedDeals += result.count;
continue;
}
const opened = await tx.deal.updateMany({
where: {
organizationId,
pipelineId: source.id,
stageId: sourceStage.id,
status: 'open',
},
data: {
pipelineId: target.id,
stageId: targetStage.id,
status,
closedAt,
},
});
const alreadyClosed = await tx.deal.updateMany({
where: {
organizationId,
pipelineId: source.id,
stageId: sourceStage.id,
status: { not: 'open' },
},
data: {
pipelineId: target.id,
stageId: targetStage.id,
status,
},
});
movedDeals += opened.count + alreadyClosed.count;
}
const leadForms = await tx.leadForm.updateMany({
where: { organizationId, pipelineId: source.id },
data: { pipelineId: target.id },
});
retargetedLeadForms = leadForms.count;
if (source.isDefault) {
await tx.pipeline.updateMany({
where: { organizationId, isDefault: true },
data: { isDefault: false },
});
await tx.pipeline.update({
where: { id: target.id },
data: { isDefault: true },
});
}
const remaining = await tx.deal.count({
where: { organizationId, pipelineId: source.id },
});
if (remaining > 0) {
throw new BadRequestException(
'برخی معامله‌ها منتقل نشدند؛ ادغام لغو شد.',
);
}
await tx.pipeline.delete({ where: { id: source.id } });
},
{ timeout: 30000 },
);
return {
ok: true,
targetPipelineId: target.id,
movedDeals,
retargetedLeadForms,
deletedPipelineId: source.id,
};
}
toDealDto(row: DealRow): DealDto {
return {
id: row.id,
+62
View File
@@ -0,0 +1,62 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import {
assertStageMap,
dealStatusForStage,
} from '../src/pipelines/pipeline-merge.util';
type S = { id: string; name: string; isWon: boolean; isLost: boolean };
const openA: S = { id: 'a1', name: 'سرنخ', isWon: false, isLost: false };
const wonA: S = { id: 'aW', name: 'برنده', isWon: true, isLost: false };
const lostA: S = { id: 'aL', name: 'از دست‌رفته', isWon: false, isLost: true };
const openB: S = { id: 'b1', name: 'تماس', isWon: false, isLost: false };
const wonB: S = { id: 'bW', name: 'برنده', isWon: true, isLost: false };
const lostB: S = { id: 'bL', name: 'باخت', isWon: false, isLost: true };
describe('pipeline merge stage map', () => {
it('rejects incomplete map', () => {
assert.throws(
() => assertStageMap([openA, wonA], [openB, wonB], { a1: 'b1' }),
/همهٔ ستون/,
);
});
it('rejects won → open', () => {
assert.throws(
() =>
assertStageMap([openA, wonA], [openB, wonB], {
a1: 'b1',
aW: 'b1',
}),
/برنده/,
);
});
it('rejects lost → open', () => {
assert.throws(
() =>
assertStageMap([openA, lostA], [openB, lostB], {
a1: 'b1',
aL: 'b1',
}),
/از دست/,
);
});
it('accepts valid mapping', () => {
assert.doesNotThrow(() =>
assertStageMap([openA, wonA, lostA], [openB, wonB, lostB], {
a1: 'b1',
aW: 'bW',
aL: 'bL',
}),
);
});
it('dealStatusForStage', () => {
assert.equal(dealStatusForStage(wonB), 'won');
assert.equal(dealStatusForStage(lostB), 'lost');
assert.equal(dealStatusForStage(openB), 'open');
});
});
@@ -0,0 +1,471 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import axios from 'axios';
import type {
MergePipelineRequest,
MergePipelineResultDto,
PipelineDto,
PipelineMergePreviewDto,
PipelineMergePreviewStageDto,
} from '@mento/shared';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import { UiButton, UiField, UiSelect } from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue';
type Step = 'target' | 'map' | 'review';
const props = defineProps<{
open: boolean;
sourceId: string | null;
pipelines: PipelineDto[];
}>();
const emit = defineEmits<{
close: [];
done: [];
}>();
const step = ref<Step>('target');
const targetId = ref('');
const preview = ref<PipelineMergePreviewDto | null>(null);
const stageMap = ref<Record<string, string>>({});
const busy = ref(false);
const error = ref('');
const sourceName = computed(() => {
if (preview.value) return preview.value.source.name;
return props.pipelines.find((pipeline) => pipeline.id === props.sourceId)?.name ?? '';
});
const selectedTarget = computed(
() => preview.value?.targets.find((target) => target.id === targetId.value) ?? null,
);
const canContinueTarget = computed(() => Boolean(targetId.value && selectedTarget.value));
const canContinueMap = computed(() => {
const current = preview.value;
if (!current) return false;
return current.stages.every((stage) => Boolean(stageMap.value[stage.id]));
});
function apiError(e: unknown, fallback: string) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
if (Array.isArray(msg)) return msg.join('، ');
if (msg) return msg;
if (!e.response) return 'اتصال به API برقرار نشد.';
}
return fallback;
}
function resetState() {
step.value = 'target';
targetId.value = '';
preview.value = null;
stageMap.value = {};
busy.value = false;
error.value = '';
}
function compatibleTargets(src: PipelineMergePreviewStageDto) {
const target = selectedTarget.value;
if (!target) return [];
return target.stages.filter((stage) => {
if (src.isWon) return stage.isWon;
if (src.isLost) return stage.isLost;
return !stage.isWon && !stage.isLost;
});
}
function statusLabel(stage: Pick<PipelineMergePreviewStageDto, 'isWon' | 'isLost'>) {
if (stage.isWon) return 'برد';
if (stage.isLost) return 'باخت';
return 'باز';
}
function syncStageMap() {
const current = preview.value;
if (!current || !targetId.value) {
stageMap.value = {};
return;
}
const next: Record<string, string> = {};
for (const sourceStage of current.stages) {
const compatible = compatibleTargets(sourceStage);
const currentTargetId = stageMap.value[sourceStage.id];
if (compatible.some((stage) => stage.id === currentTargetId)) {
next[sourceStage.id] = currentTargetId;
} else if (compatible.length === 1) {
next[sourceStage.id] = compatible[0].id;
} else {
next[sourceStage.id] = '';
}
}
stageMap.value = next;
}
async function loadPreview(id: string) {
busy.value = true;
error.value = '';
try {
const { data } = await api.get<PipelineMergePreviewDto>(`/pipelines/${id}/merge-preview`);
preview.value = data;
} catch (e) {
error.value = apiError(e, 'پیش‌نمایش ادغام ناموفق بود.');
} finally {
busy.value = false;
}
}
function nextFromTarget() {
if (!canContinueTarget.value) {
error.value = 'کاریز مقصد را انتخاب کنید.';
return;
}
error.value = '';
syncStageMap();
step.value = 'map';
}
function nextFromMap() {
if (!canContinueMap.value) {
error.value = 'برای همه مرحله‌ها مقصد سازگار انتخاب کنید.';
return;
}
error.value = '';
step.value = 'review';
}
async function submitMerge() {
if (!props.sourceId || !preview.value || !canContinueMap.value || busy.value) return;
busy.value = true;
error.value = '';
try {
const body: MergePipelineRequest = {
targetPipelineId: targetId.value,
stageMap: stageMap.value,
leadFormMode: 'retarget_all',
};
await api.post<MergePipelineResultDto>(`/pipelines/${props.sourceId}/merge`, body);
emit('done');
} catch (e) {
error.value = apiError(e, 'ادغام کاریز ناموفق بود.');
} finally {
busy.value = false;
}
}
watch(
() => [props.open, props.sourceId] as const,
async ([open, id]) => {
resetState();
if (!open || !id) return;
await loadPreview(id);
},
);
watch(targetId, () => {
error.value = '';
syncStageMap();
});
</script>
<template>
<div class="merge-wizard">
<ol class="steps" aria-label="مراحل ادغام کاریز">
<li :class="{ active: step === 'target', done: step !== 'target' }">۱. مقصد</li>
<li :class="{ active: step === 'map', done: step === 'review' }">۲. نگاشت</li>
<li :class="{ active: step === 'review' }">۳. بازبینی</li>
</ol>
<p v-if="busy && !preview" class="muted">در حال آماده‌سازی پیش‌نمایش…</p>
<template v-else-if="preview">
<section v-if="step === 'target'" class="step-panel">
<div class="intro">
<UiIcon name="layers" :size="20" />
<div>
<h3>کاریز مقصد را انتخاب کنید</h3>
<p>
معاملات و فرم‌های سرنخ از «{{ preview.source.name }}» به کاریز مقصد منتقل می‌شوند.
</p>
</div>
</div>
<UiField label="کاریز مقصد" required>
<UiSelect v-model="targetId" required>
<option value="" disabled>انتخاب کنید</option>
<option v-for="target in preview.targets" :key="target.id" :value="target.id">
{{ target.name }}
</option>
</UiSelect>
</UiField>
<div class="summary-grid">
<article>
<strong>{{ toFaDigits(preview.dealCount) }}</strong>
<span>معامله منتقل می‌شود</span>
</article>
<article>
<strong>{{ toFaDigits(preview.leadForms.length) }}</strong>
<span>فرم سرنخ به مقصد وصل می‌شود</span>
</article>
<article v-if="preview.source.isDefault" class="warn">
<strong>هشدار</strong>
<span>کاریز مبدا پیش‌فرض است و بعد از ادغام حذف می‌شود.</span>
</article>
</div>
<p v-if="selectedTarget?.isDefault" class="note">مقصد انتخاب‌شده کاریز پیش‌فرض است.</p>
</section>
<section v-else-if="step === 'map'" class="step-panel">
<div class="intro">
<UiIcon name="target" :size="20" />
<div>
<h3>مرحله‌های مبدا را نگاشت کنید</h3>
<p>هر مرحله فقط به مرحله‌ای با وضعیت سازگار در مقصد وصل می‌شود.</p>
</div>
</div>
<div class="map-list">
<article v-for="sourceStage in preview.stages" :key="sourceStage.id" class="map-row">
<div class="stage-info">
<strong>{{ sourceStage.name }}</strong>
<span>
{{ statusLabel(sourceStage) }} · {{ toFaDigits(sourceStage.dealCount) }} معامله
</span>
</div>
<UiSelect v-model="stageMap[sourceStage.id]" :error="!stageMap[sourceStage.id]">
<option value="" disabled>مرحله مقصد</option>
<option
v-for="targetStage in compatibleTargets(sourceStage)"
:key="targetStage.id"
:value="targetStage.id"
>
{{ targetStage.name }}
</option>
</UiSelect>
</article>
</div>
</section>
<section v-else class="step-panel">
<div class="intro">
<UiIcon name="check" :size="20" />
<div>
<h3>بازبینی نهایی</h3>
<p>
«{{ toFaDigits(preview.dealCount) }}» معامله منتقل می‌شود.
{{ toFaDigits(preview.leadForms.length) }} فرم سرنخ به مقصد وصل می‌شود.
کاریز «{{ preview.source.name }}» حذف می‌شود.
</p>
</div>
</div>
<dl class="review-list">
<div>
<dt>مبدا</dt>
<dd>{{ preview.source.name }}</dd>
</div>
<div>
<dt>مقصد</dt>
<dd>{{ selectedTarget?.name }}</dd>
</div>
<div>
<dt>روش فرم‌ها</dt>
<dd>همه فرم‌های سرنخ به مقصد وصل می‌شوند.</dd>
</div>
</dl>
</section>
</template>
<p v-else-if="!error" class="muted">
برای شروع ادغام، کاریز مبدا را انتخاب کنید.
<template v-if="sourceName">مبدا فعلی: {{ sourceName }}</template>
</p>
<p v-if="error" class="error">{{ error }}</p>
<div class="actions">
<UiButton variant="ghost" :disabled="busy" @click="emit('close')">بستن</UiButton>
<UiButton v-if="step === 'map'" variant="ghost" :disabled="busy" @click="step = 'target'">
قبلی
</UiButton>
<UiButton v-else-if="step === 'review'" variant="ghost" :disabled="busy" @click="step = 'map'">
قبلی
</UiButton>
<UiButton v-if="step === 'target'" :disabled="!preview || !canContinueTarget" @click="nextFromTarget">
ادامه
</UiButton>
<UiButton v-else-if="step === 'map'" :disabled="!canContinueMap" @click="nextFromMap">
بازبینی
</UiButton>
<UiButton v-else variant="danger" :loading="busy" :disabled="!canContinueMap" @click="submitMerge">
ادغام و حذف مبدا
</UiButton>
</div>
</div>
</template>
<style scoped>
.merge-wizard {
display: grid;
gap: 1rem;
}
.steps {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
padding: 0;
margin: 0;
list-style: none;
}
.steps li {
padding: 0.3rem 0.65rem;
border: 1px solid var(--line);
border-radius: 999px;
color: var(--muted);
font-size: 0.85rem;
}
.steps li.active {
border-color: var(--accent);
background: var(--accent-soft);
color: var(--accent);
}
.steps li.done {
color: var(--ink);
}
.step-panel {
display: grid;
gap: 1rem;
}
.intro {
display: flex;
gap: 0.65rem;
align-items: flex-start;
}
.intro h3,
.intro p {
margin: 0;
}
.intro h3 {
font-size: 1rem;
}
.intro p {
margin-top: 0.25rem;
color: var(--muted);
line-height: 1.8;
}
.summary-grid {
display: grid;
gap: 0.75rem;
grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));
}
.summary-grid article {
display: grid;
gap: 0.2rem;
padding: 0.75rem;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface-subtle);
}
.summary-grid strong {
color: var(--ink);
}
.summary-grid span,
.muted,
.note {
color: var(--muted);
font-size: 0.9rem;
}
.summary-grid .warn {
border-color: var(--danger);
background: var(--danger-soft);
}
.map-list {
display: grid;
gap: 0.65rem;
}
.map-row {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(12rem, 18rem);
gap: 0.75rem;
align-items: center;
padding: 0.75rem;
border: 1px solid var(--line);
border-radius: var(--radius);
}
.stage-info {
display: grid;
gap: 0.25rem;
}
.stage-info span {
color: var(--muted);
font-size: 0.85rem;
}
.review-list {
display: grid;
gap: 0.65rem;
margin: 0;
}
.review-list div {
display: flex;
justify-content: space-between;
gap: 1rem;
padding-bottom: 0.55rem;
border-bottom: 1px solid var(--line);
}
.review-list dt,
.review-list dd {
margin: 0;
}
.review-list dt {
color: var(--muted);
}
.actions {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
justify-content: flex-start;
padding-top: 0.75rem;
border-top: 1px solid var(--line);
}
.error {
color: #b91c1c;
margin: 0;
}
@media (max-width: 720px) {
.map-row {
grid-template-columns: 1fr;
}
}
</style>
+2
View File
@@ -64,6 +64,7 @@ const salesActive = computed(() =>
'/commissions',
'/sales/forecast',
'/settings/products',
'/settings/pipelines',
]),
);
const activitiesActive = computed(() => pathIn(['/activities']));
@@ -93,6 +94,7 @@ const settingsActive = computed(() =>
'/settings/team',
'/settings/audit-logs',
'/settings/public-api',
'/settings/pipelines',
'/settings/custom-fields',
'/settings/currencies',
'/settings/tahesab',
+18
View File
@@ -157,6 +157,15 @@ export const NAV_HUBS: NavHubDef[] = [
tint: 'mint',
module: 'pipeline',
},
{
to: '/settings/pipelines',
title: 'مسیر فروش و کاریزها',
desc: 'مدیریت کاریزها و ادغام مسیرهای فروش',
icon: 'filter',
tint: 'mint',
admin: true,
module: 'pipeline',
},
{
to: '/settings/products',
title: 'محصولات و خدمات',
@@ -410,6 +419,15 @@ export const NAV_HUBS: NavHubDef[] = [
module: 'teams',
admin: true,
},
{
to: '/settings/pipelines',
title: 'مسیر فروش و کاریزها',
desc: 'مدیریت کاریزها و ادغام مسیرهای فروش',
icon: 'filter',
tint: 'mint',
admin: true,
module: 'pipeline',
},
{
to: '/settings/audit-logs',
title: 'لاگ فعالیت کاربران',
+6
View File
@@ -331,6 +331,12 @@ export const router = createRouter({
component: () => import('@/views/LeadStagesSettingsView.vue'),
meta: { roles: ['owner', 'admin'] as UserRole[] },
},
{
path: 'settings/pipelines',
name: 'pipeline-settings',
component: () => import('@/views/PipelineSettingsView.vue'),
meta: { roles: ['owner', 'admin'] as UserRole[], module: 'pipeline' },
},
{
path: 'settings/lead-forms',
name: 'lead-forms',
+255
View File
@@ -0,0 +1,255 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import axios from 'axios';
import { api } from '@/lib/api';
import { toFaDigits } from '@/lib/jalali';
import { UiButton, UiCard, UiEmptyState, UiField, UiInput, UiModal, UiPageHeader } from '@/components/ui';
import UiIcon from '@/components/UiIcon.vue';
import PipelineMergeWizard from '@/components/pipeline/PipelineMergeWizard.vue';
import type { PipelineDto } from '@mento/shared';
type PipelineListItem = PipelineDto & {
dealCount?: number | null;
};
const loading = ref(false);
const saving = ref(false);
const error = ref('');
const okMsg = ref('');
const pipelines = ref<PipelineListItem[]>([]);
const name = ref('');
const mergeOpen = ref(false);
const mergeSourceId = ref<string | null>(null);
const canMerge = computed(() => pipelines.value.length >= 2);
function apiError(e: unknown, fallback: string) {
if (axios.isAxiosError(e)) {
const msg = (e.response?.data as { message?: string | string[] })?.message;
if (Array.isArray(msg)) return msg.join('، ');
if (msg) return msg;
if (!e.response) return 'اتصال به API برقرار نشد.';
}
return fallback;
}
async function load() {
loading.value = true;
error.value = '';
try {
const { data } = await api.get<PipelineListItem[]>('/pipelines');
pipelines.value = data;
} catch (e) {
error.value = apiError(e, 'بارگذاری کاریزها ناموفق بود.');
} finally {
loading.value = false;
}
}
async function createPipeline() {
const nextName = name.value.trim();
if (nextName.length < 2 || saving.value) {
error.value = 'نام کاریز را حداقل با ۲ کاراکتر وارد کنید.';
return;
}
saving.value = true;
error.value = '';
okMsg.value = '';
try {
await api.post<PipelineDto>('/pipelines', { name: nextName });
name.value = '';
okMsg.value = 'کاریز جدید ساخته شد.';
await load();
} catch (e) {
error.value = apiError(e, 'ساخت کاریز ناموفق بود.');
} finally {
saving.value = false;
}
}
function openMerge(pipeline: PipelineListItem) {
if (!canMerge.value) return;
mergeSourceId.value = pipeline.id;
mergeOpen.value = true;
}
function closeMerge() {
mergeOpen.value = false;
mergeSourceId.value = null;
}
async function onMergeDone() {
okMsg.value = 'کاریز با موفقیت ادغام شد.';
await load();
closeMerge();
}
onMounted(load);
</script>
<template>
<section class="crm-page">
<UiPageHeader
title="مسیر فروش و کاریزها"
lead="مدیریت کاریزهای فروش و آماده‌سازی ادغام مسیرها"
/>
<p v-if="okMsg" class="ok">{{ okMsg }}</p>
<p v-if="error" class="error">{{ error }}</p>
<p v-else-if="loading" class="muted">در حال بارگذاری…</p>
<form class="crm-form" @submit.prevent="createPipeline">
<UiCard>
<template #header>
<div class="card-title">
<UiIcon name="plus" :size="18" />
<h3>کاریز جدید</h3>
</div>
</template>
<div class="form-grid">
<UiField label="نام کاریز" required for-id="pipeline-name">
<UiInput id="pipeline-name" v-model="name" required placeholder="مثلاً فروش سازمانی" />
</UiField>
</div>
<template #footer>
<UiButton type="submit" :loading="saving">افزودن کاریز</UiButton>
</template>
</UiCard>
</form>
<div v-if="pipelines.length" class="list">
<UiCard v-for="pipeline in pipelines" :key="pipeline.id" padding="sm" class="pipeline-card">
<div class="row">
<span class="dot" aria-hidden="true" />
<div class="info">
<div class="title-row">
<strong>{{ pipeline.name }}</strong>
<em v-if="pipeline.isDefault">پیش‌فرض</em>
</div>
<span class="muted">
{{ toFaDigits(pipeline.stages.length) }} مرحله
<template v-if="pipeline.dealCount != null">
· {{ toFaDigits(pipeline.dealCount) }} معامله
</template>
</span>
</div>
<div class="ops">
<UiButton
size="sm"
variant="ghost"
:disabled="!canMerge"
@click="openMerge(pipeline)"
>
ادغام
</UiButton>
</div>
</div>
</UiCard>
</div>
<UiEmptyState
v-else-if="!loading"
title="کاریزی تعریف نشده."
description="اولین مسیر فروش را اضافه کنید."
/>
<UiModal :open="mergeOpen" title="ادغام کاریز" @close="closeMerge">
<PipelineMergeWizard
:open="mergeOpen"
:source-id="mergeSourceId"
:pipelines="pipelines"
@close="closeMerge"
@done="onMergeDone"
/>
</UiModal>
</section>
</template>
<style scoped>
.crm-page {
display: grid;
gap: 1rem;
}
.card-title {
display: flex;
align-items: center;
gap: 0.45rem;
}
.card-title h3 {
margin: 0;
font-size: 1rem;
}
.form-grid {
display: grid;
gap: 0.75rem;
grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
align-items: end;
}
.list {
display: grid;
gap: 0.65rem;
}
.row {
display: flex;
align-items: center;
gap: 0.65rem;
flex-wrap: wrap;
}
.dot {
width: 0.7rem;
height: 0.7rem;
border-radius: 50%;
flex-shrink: 0;
background: var(--accent);
}
.info {
flex: 1 1 12rem;
display: grid;
gap: 0.2rem;
min-width: 0;
}
.title-row {
display: flex;
align-items: center;
gap: 0.45rem;
flex-wrap: wrap;
}
.title-row em {
font-style: normal;
font-size: 0.75rem;
padding: 0.1rem 0.45rem;
border-radius: 999px;
background: var(--accent-soft);
color: var(--accent);
}
.ops {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
}
.muted {
color: var(--muted);
font-size: 0.85rem;
}
.ok {
color: #0f766e;
margin: 0;
}
.error {
color: #b91c1c;
margin: 0;
}
</style>
@@ -0,0 +1,516 @@
# Pipeline Merge Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Allow admins to merge one sales pipeline into another with manual stage mapping, retarget lead forms, transfer default flag, and delete the source pipeline safely.
**Architecture:** Pure validation helpers in `apps/api/src/pipelines/pipeline-merge.util.ts` (unit-tested). `PipelinesService.mergePreview` / `merge` run in one Prisma transaction. New settings page `PipelineSettingsView.vue` with a multi-step merge wizard; entry from settings hub + sales hub.
**Tech Stack:** NestJS, Prisma, class-validator, `@mento/shared`, Vue 3, Vue Router, existing `UiModal` / `UiSelect` / `UiButton`.
## Global Constraints
- Package manager: npm workspaces (`npm run … -w @mento/…`); never pnpm/yarn
- Prisma only from `apps/api` (needs `apps/api/.env`)
- API roles for mutate: `@Roles('owner', 'admin')` (same as create pipeline)
- Lead forms v1: only `leadFormMode: 'retarget_all'`
- Won/lost source stages map only to won/lost target stages
- Spec: `docs/superpowers/specs/2026-10-12-pipeline-merge-design.md`
- After code edits: `graphify update .` (may crash; non-blocking)
- Shell is PowerShell: use `;` not `&&`
## File Map
| File | Responsibility |
|---|---|
| `packages/shared/src/index.ts` | DTOs for preview + merge request/response |
| `apps/api/src/pipelines/pipeline-merge.util.ts` | Pure stage-map validation + status from stage flags |
| `apps/api/test/pipeline-merge.test.ts` | Unit tests for util |
| `apps/api/src/pipelines/dto.ts` | `MergePipelineDto` |
| `apps/api/src/pipelines/pipelines.service.ts` | `mergePreview`, `merge` |
| `apps/api/src/pipelines/pipelines.controller.ts` | GET/POST merge routes |
| `apps/api/package.json` | Register new test file in `test` script |
| `apps/web/src/views/PipelineSettingsView.vue` | List pipelines + open merge wizard |
| `apps/web/src/components/pipeline/PipelineMergeWizard.vue` | Multi-step merge UI |
| `apps/web/src/router/index.ts` | Route `settings/pipelines` |
| `apps/web/src/lib/nav-hubs.ts` | Hub cards to the new page |
---
### Task 1: Shared types + pure merge validation (TDD)
**Files:**
- Create: `apps/api/src/pipelines/pipeline-merge.util.ts`
- Create: `apps/api/test/pipeline-merge.test.ts`
- Modify: `packages/shared/src/index.ts` (near `PipelineDto` / deal types ~960–1050)
- Modify: `apps/api/package.json` (`test` script)
**Interfaces:**
- Produces:
- `PipelineMergeLeadFormMode = 'retarget_all'`
- `PipelineMergePreviewDto`, `MergePipelineRequest`, `MergePipelineResultDto`
- `assertStageMap(sourceStages, targetStages, stageMap): void` throws `Error` with Persian message
- `dealStatusForStage(stage: { isWon: boolean; isLost: boolean }): 'open' | 'won' | 'lost'`
- [ ] **Step 1: Add shared types** in `packages/shared/src/index.ts` after `PipelineDto` / board types:
```ts
export type PipelineMergeLeadFormMode = 'retarget_all';
export interface PipelineMergePreviewStageDto {
id: string;
name: string;
isWon: boolean;
isLost: boolean;
dealCount: number;
}
export interface PipelineMergePreviewTargetDto {
id: string;
name: string;
isDefault: boolean;
stages: Array<{
id: string;
name: string;
isWon: boolean;
isLost: boolean;
}>;
}
export interface PipelineMergePreviewDto {
source: { id: string; name: string; isDefault: boolean };
stages: PipelineMergePreviewStageDto[];
dealCount: number;
leadForms: Array<{ id: string; name: string; isActive: boolean }>;
targets: PipelineMergePreviewTargetDto[];
}
export interface MergePipelineRequest {
targetPipelineId: string;
stageMap: Record<string, string>;
leadFormMode?: PipelineMergeLeadFormMode;
}
export interface MergePipelineResultDto {
ok: true;
targetPipelineId: string;
movedDeals: number;
retargetedLeadForms: number;
deletedPipelineId: string;
}
```
- [ ] **Step 2: Write failing unit tests** — create `apps/api/test/pipeline-merge.test.ts`:
```ts
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import {
assertStageMap,
dealStatusForStage,
} from '../src/pipelines/pipeline-merge.util';
type S = { id: string; name: string; isWon: boolean; isLost: boolean };
const openA: S = { id: 'a1', name: 'سرنخ', isWon: false, isLost: false };
const wonA: S = { id: 'aW', name: 'برنده', isWon: true, isLost: false };
const lostA: S = { id: 'aL', name: 'از دست‌رفته', isWon: false, isLost: true };
const openB: S = { id: 'b1', name: 'تماس', isWon: false, isLost: false };
const wonB: S = { id: 'bW', name: 'برنده', isWon: true, isLost: false };
const lostB: S = { id: 'bL', name: 'باخت', isWon: false, isLost: true };
describe('pipeline merge stage map', () => {
it('rejects incomplete map', () => {
assert.throws(
() => assertStageMap([openA, wonA], [openB, wonB], { a1: 'b1' }),
/همهٔ ستون/,
);
});
it('rejects won → open', () => {
assert.throws(
() =>
assertStageMap([openA, wonA], [openB, wonB], {
a1: 'b1',
aW: 'b1',
}),
/برنده/,
);
});
it('rejects lost → open', () => {
assert.throws(
() =>
assertStageMap([openA, lostA], [openB, lostB], {
a1: 'b1',
aL: 'b1',
}),
/از دست/,
);
});
it('accepts valid mapping', () => {
assert.doesNotThrow(() =>
assertStageMap([openA, wonA, lostA], [openB, wonB, lostB], {
a1: 'b1',
aW: 'bW',
aL: 'bL',
}),
);
});
it('dealStatusForStage', () => {
assert.equal(dealStatusForStage(wonB), 'won');
assert.equal(dealStatusForStage(lostB), 'lost');
assert.equal(dealStatusForStage(openB), 'open');
});
});
```
- [ ] **Step 3: Run test — expect FAIL** (module missing)
```powershell
cd apps/api; npx tsx --test test/pipeline-merge.test.ts
```
- [ ] **Step 4: Implement util** — `apps/api/src/pipelines/pipeline-merge.util.ts`:
```ts
export type MergeStageLike = {
id: string;
name: string;
isWon: boolean;
isLost: boolean;
};
export function dealStatusForStage(
stage: Pick<MergeStageLike, 'isWon' | 'isLost'>,
): 'open' | 'won' | 'lost' {
if (stage.isWon) return 'won';
if (stage.isLost) return 'lost';
return 'open';
}
export function assertStageMap(
sourceStages: MergeStageLike[],
targetStages: MergeStageLike[],
stageMap: Record<string, string>,
): void {
const targetById = new Map(targetStages.map((s) => [s.id, s]));
for (const src of sourceStages) {
const tid = stageMap[src.id];
if (!tid) {
throw new Error(`همهٔ ستون‌های مبدأ باید نگاشت شوند (ستون «${src.name}»).`);
}
const tgt = targetById.get(tid);
if (!tgt) {
throw new Error(`ستون مقصد برای «${src.name}» معتبر نیست.`);
}
if (src.isWon && !tgt.isWon) {
throw new Error(`ستون برندهٔ «${src.name}» فقط به ستون برندهٔ مقصد نگاشت می‌شود.`);
}
if (src.isLost && !tgt.isLost) {
throw new Error(`ستون از دست‌رفتهٔ «${src.name}» فقط به ستون از دست‌رفتهٔ مقصد نگاشت می‌شود.`);
}
if (!src.isWon && !src.isLost && (tgt.isWon || tgt.isLost)) {
throw new Error(`ستون باز «${src.name}» را به ستون برد/باخت مقصد نگاشت نکنید.`);
}
}
}
```
- [ ] **Step 5: Register test + run pass**
In `apps/api/package.json` `test` script, append `test/pipeline-merge.test.ts`.
```powershell
cd apps/api; npx tsx --test test/pipeline-merge.test.ts
npm run build -w @mento/shared
```
Expected: all tests PASS; shared builds.
- [ ] **Step 6: Commit**
```powershell
git add packages/shared/src/index.ts apps/api/src/pipelines/pipeline-merge.util.ts apps/api/test/pipeline-merge.test.ts apps/api/package.json
git commit -m "feat(pipelines): merge stage-map util and shared DTOs"
```
---
### Task 2: API merge-preview + merge
**Files:**
- Modify: `apps/api/src/pipelines/dto.ts`
- Modify: `apps/api/src/pipelines/pipelines.service.ts`
- Modify: `apps/api/src/pipelines/pipelines.controller.ts`
**Interfaces:**
- Consumes: `assertStageMap`, `dealStatusForStage`, shared DTOs
- Produces: `PipelinesService.mergePreview(orgId, sourceId)`, `PipelinesService.merge(orgId, sourceId, dto)`
- [ ] **Step 1: DTO**
```ts
export class MergePipelineDto {
@IsString()
@MinLength(1)
targetPipelineId!: string;
@IsObject()
stageMap!: Record<string, string>;
@IsOptional()
@IsString()
leadFormMode?: 'retarget_all';
}
```
- [ ] **Step 2: Service methods** (add to `PipelinesService`)
`mergePreview`:
1. Load source pipeline + stages (404 if missing / wrong org).
2. Count deals per stage + total.
3. `leadForm.findMany({ where: { organizationId, pipelineId: sourceId } })`.
4. Load other pipelines as `targets` with stages.
5. Return `PipelineMergePreviewDto`.
`merge`:
1. Load source + target (same org); reject if same id or missing.
2. `assertStageMap` inside try → `BadRequestException` with message.
3. `leadFormMode` default `'retarget_all'`; reject other values.
4. `prisma.$transaction(async (tx) => { ... })`:
- For each source stage id in map: `tx.deal.updateMany({ where: { organizationId, pipelineId: sourceId, stageId: src }, data: { pipelineId: targetId, stageId: tgt, status: dealStatusForStage(tgtStage), closedAt: status==='open' ? null : undefined } })`
Prefer per-stage updates so status/closedAt are correct. For closedAt when becoming won/lost set `closedAt: new Date()` if previously open; when becoming open set `closedAt: null`.
- `tx.leadForm.updateMany({ where: { organizationId, pipelineId: sourceId }, data: { pipelineId: targetId } })`
- If `source.isDefault`: set target `isDefault: true`, source `isDefault: false` (and clear other defaults if needed — org should have one default: `updateMany isDefault true → false` then set target true).
- `tx.pipeline.delete({ where: { id: sourceId } })` (stages cascade; deals already moved so Restrict on stage is fine).
5. Return `MergePipelineResultDto` with counts.
Important: update deals **before** deleting pipeline; never delete while deals still point at source stages.
- [ ] **Step 3: Controller routes** (keep concrete paths; place near other `:pipelineId` routes)
```ts
@Get(':pipelineId/merge-preview')
@Roles('owner', 'admin')
mergePreview(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
) {
return this.pipelinesService.mergePreview(user.organizationId, pipelineId);
}
@Post(':pipelineId/merge')
@Roles('owner', 'admin')
merge(
@CurrentUser() user: { organizationId: string },
@Param('pipelineId') pipelineId: string,
@Body() dto: MergePipelineDto,
) {
return this.pipelinesService.merge(user.organizationId, pipelineId, dto);
}
```
- [ ] **Step 4: Typecheck API**
```powershell
npm run typecheck -w @mento/api
```
Expected: EXIT 0
- [ ] **Step 5: Commit**
```powershell
git add apps/api/src/pipelines/dto.ts apps/api/src/pipelines/pipelines.service.ts apps/api/src/pipelines/pipelines.controller.ts
git commit -m "feat(api): pipeline merge preview and merge endpoints"
```
---
### Task 3: Settings page + nav + router
**Files:**
- Create: `apps/web/src/views/PipelineSettingsView.vue`
- Modify: `apps/web/src/router/index.ts` (after `settings/lead-stages` block ~329)
- Modify: `apps/web/src/lib/nav-hubs.ts` (settings cards + optional sales card)
- Modify: `apps/web/src/layouts/AppLayout.vue` if `settingsActive` path list needs `/settings/pipelines`
**Interfaces:**
- Produces: route name `pipeline-settings`, path `/settings/pipelines`
- Opens `PipelineMergeWizard` (Task 4) via prop/emit
- [ ] **Step 1: Router**
```ts
{
path: 'settings/pipelines',
name: 'pipeline-settings',
component: () => import('@/views/PipelineSettingsView.vue'),
meta: { module: 'pipeline' },
},
```
(Match neighboring routes’ `meta` style.)
- [ ] **Step 2: Nav hub card** in `settings.cards` (and optionally under `sales.cards` with `admin: true`):
```ts
{
to: '/settings/pipelines',
title: 'مسیر فروش و کاریزها',
desc: 'مدیریت کاریزها و ادغام مسیرهای فروش',
icon: 'filter',
tint: 'mint',
admin: true,
module: 'pipeline',
},
```
- [ ] **Step 3: Minimal settings page** — list pipelines from `GET /pipelines`, show name, default badge, deal count if available (optional: from preview later). Buttons: «ادغام» (disabled if `pipelines.length < 2`), «کاریز جدید» reusing `POST /pipelines` like board. Pattern after `LeadStagesSettingsView.vue` (`UiPageHeader`, `UiCard`, RTL).
- [ ] **Step 4: vue-tsc**
```powershell
npx vue-tsc --noEmit -p apps/web/tsconfig.json
```
- [ ] **Step 5: Commit**
```powershell
git add apps/web/src/views/PipelineSettingsView.vue apps/web/src/router/index.ts apps/web/src/lib/nav-hubs.ts apps/web/src/layouts/AppLayout.vue
git commit -m "feat(web): pipeline settings page and nav entry"
```
---
### Task 4: Merge wizard UI
**Files:**
- Create: `apps/web/src/components/pipeline/PipelineMergeWizard.vue`
- Modify: `apps/web/src/views/PipelineSettingsView.vue`
**Interfaces:**
- Props: `open: boolean`, `sourceId: string | null`, `pipelines: PipelineDto[]`
- Emits: `close`, `done` (after successful merge)
- Calls: `GET /pipelines/:id/merge-preview`, `POST /pipelines/:id/merge`
- [ ] **Step 1: Wizard steps state**
```ts
type Step = 'target' | 'map' | 'review';
const step = ref<Step>('target');
const targetId = ref('');
const preview = ref<PipelineMergePreviewDto | null>(null);
const stageMap = ref<Record<string, string>>({});
const busy = ref(false);
const error = ref('');
```
- [ ] **Step 2: Load preview when `open && sourceId`**
```ts
watch(
() => [props.open, props.sourceId] as const,
async ([open, id]) => {
if (!open || !id) return;
step.value = 'target';
targetId.value = '';
stageMap.value = {};
error.value = '';
const { data } = await api.get<PipelineMergePreviewDto>(
`/pipelines/${id}/merge-preview`,
);
preview.value = data;
},
);
```
- [ ] **Step 3: Target step** — `UiSelect` of `preview.targets`; show dependency summary (dealCount, leadForms length, isDefault warning).
- [ ] **Step 4: Map step** — for each `preview.stages` row, select among compatible target stages:
```ts
function compatibleTargets(src: PipelineMergePreviewStageDto) {
const t = preview.value?.targets.find((x) => x.id === targetId.value);
if (!t) return [];
return t.stages.filter((s) => {
if (src.isWon) return s.isWon;
if (src.isLost) return s.isLost;
return !s.isWon && !s.isLost;
});
}
```
Pre-fill when only one compatible option.
- [ ] **Step 5: Review step** — Persian summary:
«N معامله منتقل می‌شود. M فرم سرنخ به مقصد وصل می‌شود. کاریز «X» حذف می‌شود.»
Confirm button →
```ts
await api.post(`/pipelines/${sourceId}/merge`, {
targetPipelineId: targetId.value,
stageMap: stageMap.value,
leadFormMode: 'retarget_all',
});
emit('done');
```
Show API errors under the actions (same axios message pattern as other settings views).
- [ ] **Step 6: Wire into settings page** with `UiModal` (`:open="mergeOpen"`). On `done`, reload list and close.
- [ ] **Step 7: Manual check** — `npm run dev:web`, open `/settings/pipelines`, merge two test pipelines; confirm source gone and deals on target.
- [ ] **Step 8: vue-tsc + commit**
```powershell
npx vue-tsc --noEmit -p apps/web/tsconfig.json
git add apps/web/src/components/pipeline/PipelineMergeWizard.vue apps/web/src/views/PipelineSettingsView.vue
git commit -m "feat(web): pipeline merge wizard"
```
---
### Task 5: Verification + graphify
- [ ] **Step 1: Full checks**
```powershell
npm run build -w @mento/shared
cd apps/api; npx tsx --test test/pipeline-merge.test.ts; cd ../..
npm run typecheck -w @mento/api
npx vue-tsc --noEmit -p apps/web/tsconfig.json
```
Expected: all green.
- [ ] **Step 2: `graphify update .`** (ignore crash if known)
- [ ] **Step 3: Stop** — do not push/deploy unless user asks. Paste locked deploy block only when user requests deploy.
---
## Spec coverage checklist
| Spec item | Task |
|---|---|
| Settings entry + manage pipelines page | 3 |
| Merge wizard + stage mapping | 4 |
| Dependency preview (deals, forms, default) | 2 + 4 |
| Won/lost mapping rules | 1 + 4 |
| `retarget_all` lead forms | 2 + 4 |
| Default flag transfer | 2 |
| Transactional delete source | 2 |
| Unit tests for map rules | 1 |
| Admin roles | 2 |
## Self-review notes
- No automation rewrite (out of scope).
- `LeadForm.pipelineId` has no Prisma FK; `updateMany` by string id is correct.
- Deal `stage` Restrict requires moves before pipeline/stage deletion — covered in Task 2.
- Route `GET board` stays before `:pipelineId/*` — existing order preserved; new routes are under `:pipelineId/merge-preview` and do not collide with `board`.
@@ -0,0 +1,97 @@
# ادغام کاریز (مسیر فروش)
تاریخ: ۲۰۲۶-۱۰-۱۲
وضعیت: تأییدشده توسط کاربر
## هدف
ادغام یک کاریز مبدأ در کاریز مقصد با نگاشت دستی ستون‌ها، به‌روزرسانی وابستگی‌ها، و حذف کاریز مبدأ — بدون از دست رفتن معامله یا قطع بی‌خبر اتصال‌ها.
## محدوده
- فقط مسیر فروش (Pipeline / Deal)، نه بُرد پروژه یا میز کار.
- محل ورود: تنظیمات مسیر فروش → مدیریت کاریزها → «ادغام کاریز».
- دسترسی: همان نقش‌هایی که کاریز می‌سازند (`canManageSettings`).
## خارج از محدوده (نسخهٔ اول)
- ادغام خودکار ستون‌ها بر اساس نام.
- بازنویسی اتوماسیون‌ها (فعلاً شناسهٔ کاریز/ستون معامله را نگه نمی‌دارند).
- مهاجرت فیلترهای ذخیره‌شدهٔ سمت کلاینت (پس از ادغام، UI روی مقصد می‌ماند).
## جریان UI (ویزارد)
1. **مبدأ و مقصد:** انتخاب دو کاریز؛ مبدأ ≠ مقصد؛ حداقل یک کاریز دیگر برای مقصد لازم است.
2. **پیش‌نمایش وابستگی‌ها:** تعداد معاملات، تعداد فرم‌های سرنخ متصل، آیا مبدأ پیش‌فرض است.
3. **نگاشت ستون‌ها:** برای هر ستون مبدأ یک ستون مقصد اجباری است.
- ستون `isWon` مبدأ فقط به ستون `isWon` مقصد.
- ستون `isLost` مبدأ فقط به ستون `isLost` مقصد.
- بقیه به ستون‌های باز (غیر برد/باخت) مقصد.
4. **فرم‌های سرنخ:** نسخهٔ اول فقط حالت `retarget_all` — همهٔ فرم‌های متصل به مبدأ به مقصد منتقل می‌شوند. در پیش‌نمایش نام فرم‌ها نشان داده می‌شود تا کاربر بداند چه چیزی جابه‌جا می‌شود.
5. **پیش‌فرض:** اگر مبدأ `isDefault` است، پس از ادغام مقصد پیش‌فرض می‌شود.
6. **تأیید:** خلاصهٔ قابل‌خواندن + اجرای عمل.
اگر صفحهٔ «تنظیمات مسیر فروش / مدیریت کاریزها» هنوز وجود ندارد، در همین کار اضافه می‌شود (لیست کاریزها، ساخت، و دکمهٔ ادغام).
## API
### پیش‌نمایش
`GET /pipelines/:sourceId/merge-preview`
پاسخ نمونه:
```json
{
"source": { "id": "...", "name": "...", "isDefault": false },
"stages": [{ "id": "...", "name": "...", "isWon": false, "isLost": false, "dealCount": 12 }],
"dealCount": 42,
"leadForms": [{ "id": "...", "name": "...", "isActive": true }],
"targets": [{ "id": "...", "name": "...", "isDefault": true, "stages": [...] }]
}
```
### اجرا
`POST /pipelines/:sourceId/merge`
بدنه:
```json
{
"targetPipelineId": "...",
"stageMap": { "<sourceStageId>": "<targetStageId>" },
"leadFormMode": "retarget_all"
}
```
همه در یک تراکنش Prisma:
1. اعتبارسنجی مبدأ/مقصد، نگاشت کامل ستون‌ها، سازگاری برد/باخت.
2. به‌روزرسانی معاملات: `pipelineId` و `stageId` بر اساس `stageMap` (و در صورت نیاز `status` هم‌راستا با ستون مقصد).
3. فرم‌های سرنخ با `pipelineId = source` → `target` (حالت `retarget_all`).
4. اگر مبدأ پیش‌فرض بود: `isDefault` مقصد = true، مبدأ قبل از حذف false.
5. حذف کاریز مبدأ (ستون‌هایش cascade).
خطاها با پیام فارسی خوانا؛ در صورت خطا هیچ تغییر نیمه‌کاره‌ای نماند.
## مدل داده (موجود)
- `Pipeline` → `stages`, `deals`, `isDefault`
- `Deal.pipelineId` / `Deal.stageId` (`stage` با `onDelete: Restrict`)
- `LeadForm.pipelineId` (اختیاری، برای ساخت معامله از فرم)
حذف مستقیم کاریز بدون انتقال معامله خطرناک است؛ ادغام جایگزین حذف امن است.
## تست
- واحد API: نگاشت ناقص رد شود؛ برد→باز رد شود؛ تراکنش معامله + فرم + پیش‌فرض + حذف مبدأ.
- دستی: دو کاریز با چند معامله و یک فرم سرنخ؛ پس از ادغام فقط مقصد در سلکت دیده شود و فرم به مقصد اشاره کند.
## معیار پذیرش
- از تنظیمات مسیر فروش بتوان دو کاریز را ادغام کرد.
- همهٔ معاملات با نگاشت ستون منتقل شوند.
- فرم‌های سرنخ متصل به‌صورت پیش‌فرض به مقصد بروند.
- کاریز مبدأ حذف شود و اگر پیش‌فرض بود، مقصد پیش‌فرض شود.
- در خطا، دادهٔ قبلی حفظ شود.
+44
View File
@@ -996,6 +996,50 @@ export interface ReorderPipelineStagesRequest {
stageIds: string[];
}
export type PipelineMergeLeadFormMode = 'retarget_all';
export interface PipelineMergePreviewStageDto {
id: string;
name: string;
isWon: boolean;
isLost: boolean;
dealCount: number;
}
export interface PipelineMergePreviewTargetDto {
id: string;
name: string;
isDefault: boolean;
stages: Array<{
id: string;
name: string;
isWon: boolean;
isLost: boolean;
}>;
}
export interface PipelineMergePreviewDto {
source: { id: string; name: string; isDefault: boolean };
stages: PipelineMergePreviewStageDto[];
dealCount: number;
leadForms: Array<{ id: string; name: string; isActive: boolean }>;
targets: PipelineMergePreviewTargetDto[];
}
export interface MergePipelineRequest {
targetPipelineId: string;
stageMap: Record<string, string>;
leadFormMode?: PipelineMergeLeadFormMode;
}
export interface MergePipelineResultDto {
ok: true;
targetPipelineId: string;
movedDeals: number;
retargetedLeadForms: number;
deletedPipelineId: string;
}
export interface CreateDealRequest {
title: string;
pipelineId?: string;