unis-oa/frontend/src/views/oa/design/ProcessDesignerView.vue

2067 lines
85 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<template>
<div v-if="process" class="flex h-[calc(100vh-8rem-var(--app-tabbar-h,0px))] min-h-[560px] flex-col gap-3">
<!-- 工具栏 -->
<div class="card flex flex-wrap items-center justify-between gap-3 px-3 py-2.5">
<div class="flex min-w-0 items-center gap-3">
<BackButton compact fallback="design-processes" :guard="confirmLeave" />
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<h2 class="max-w-[42vw] truncate text-base font-semibold text-gray-900 dark:text-white">{{ process.name }}</h2>
<span :class="process.published ? 'badge badge-success' : 'badge badge-gray'">
{{ process.published ? t('process.published') : t('process.draftState') }}
</span>
<span class="badge badge-primary cursor-help" :title="versionPinTitle">v{{ process.version }}</span>
<span class="inline-flex items-center gap-1 text-[11px]" :class="saveStateClass" :title="saveStateTitle">
<span v-if="saveState === 'pending'" class="h-1.5 w-1.5 rounded-full bg-amber-500"></span>
<Icon v-else :name="saveStateIcon" class="h-3.5 w-3.5" />
{{ saveStateText }}
</span>
</div>
<p class="mt-0.5 hidden truncate text-[11px] text-gray-400 sm:block">{{ t('process.canvasTip') }}</p>
</div>
</div>
<div class="flex flex-wrap items-center gap-1.5">
<div class="flex items-center gap-0.5 rounded-xl border border-gray-200 p-0.5 dark:border-dark-600">
<button type="button" class="tool-btn" :disabled="!undoStack.length" :title="t('process.undo')" @click="undo">
<Icon name="undo" class="h-4 w-4" />
</button>
<button type="button" class="tool-btn" :disabled="!redoStack.length" :title="t('process.redo')" @click="redo">
<Icon name="redo" class="h-4 w-4" />
</button>
<span class="mx-0.5 h-4 w-px bg-gray-200 dark:bg-dark-600"></span>
<button
type="button"
class="tool-btn"
:class="[snap ? 'text-indigo-600 dark:text-indigo-300' : '']"
:title="t('process.snap')"
@click="snap = !snap"
>
<Icon name="grid" class="h-4 w-4" />
</button>
<button type="button" class="tool-btn" :title="t('process.autoLayout')" @click="tidy">
<Icon name="sparkles" class="h-4 w-4" />
</button>
</div>
<div class="flex items-center gap-0.5 rounded-xl border border-gray-200 p-0.5 dark:border-dark-600" :title="t('process.edgeStyle')">
<button
v-for="style in EDGE_STYLES"
:key="style"
type="button"
class="tool-btn text-[11px] font-medium"
:class="[edgeStyle === style ? 'text-indigo-600 dark:text-indigo-300' : '']"
@click="setEdgeStyle(style)"
>
{{ edgeStyleLabel(style) }}
</button>
<span class="mx-0.5 h-4 w-px bg-gray-200 dark:bg-dark-600"></span>
<button
type="button"
class="tool-btn"
:class="[edgeRadius > 0 ? 'text-indigo-600 dark:text-indigo-300' : '']"
:title="t('process.edgeCorner')"
@click="toggleEdgeRadius"
>
<Icon name="gitBranch" class="h-4 w-4" />
</button>
<span class="mx-0.5 h-4 w-px bg-gray-200 dark:bg-dark-600"></span>
<button
type="button"
class="tool-btn"
:class="[showAllLabels ? 'text-indigo-600 dark:text-indigo-300' : '']"
:title="t('process.edgeLabelsTip')"
@click="showAllLabels = !showAllLabels"
>
<Icon name="tag" class="h-4 w-4" />
</button>
</div>
<button type="button" class="btn btn-ghost btn-sm" :title="t('process.guideTitle')" @click="openGuide('choice')">
<Icon name="questionCircle" class="mr-1 h-4 w-4" />
{{ t('process.guideButton') }}
</button>
<button
type="button"
class="btn btn-ghost btn-sm"
:disabled="busy"
:title="t('process.dedupAuditTip')"
@click="openDedupAudit"
>
<Icon name="shield" class="mr-1 h-4 w-4" />
{{ t('process.dedupAudit') }}
<span v-if="dedupBadge" class="badge badge-danger ml-1">{{ dedupBadge }}</span>
</button>
<button type="button" class="btn btn-ghost btn-sm" :disabled="busy" @click="validate">
<Icon name="checkCircle" class="mr-1 h-4 w-4" />
{{ t('process.validate') }}
</button>
<button
type="button"
class="btn btn-ghost btn-sm"
:title="t('process.simulateTip')"
@click="simulateOpen = true"
>
<Icon name="beaker" class="mr-1 h-4 w-4" />
{{ t('process.simulate') }}
</button>
<button
type="button"
class="btn btn-sm"
:class="dirty ? 'btn-primary' : 'btn-secondary'"
:disabled="busy"
:title="dirty ? t('process.saveNowHint', { count: pendingTotal }) : t('process.saveCleanHint')"
@click="flushSave"
>
<Icon name="save" class="mr-1 h-4 w-4" />
{{ t('process.saveDesign') }}
</button>
<button
type="button"
class="tool-btn"
:class="autosaveOn ? 'text-indigo-600 dark:text-indigo-300' : ''"
:title="autosaveOn ? t('process.autosaveOnHint') : t('process.autosaveOffHint')"
@click="setAutosave(!autosaveOn)"
>
<Icon name="cloud" class="h-4 w-4" />
</button>
<button type="button" class="btn btn-primary btn-sm" :disabled="busy" @click="publish">
<Icon name="upload" class="mr-1 h-4 w-4" />
{{ t('process.publish') }}
</button>
<button type="button" class="btn btn-ghost btn-sm" :title="t('process.metaPanel')" @click="inspectorOpen = !inspectorOpen">
<Icon :name="inspectorOpen ? 'chevronRight' : 'chevronLeft'" class="h-4 w-4" />
</button>
</div>
</div>
<div class="flex min-h-0 flex-1 overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm dark:border-dark-700 dark:bg-dark-800">
<FlowPalette :taken-types="takenTypes" :issues="paletteIssues" @add="addNode" @focus="focusNode" @help="openGuide" />
<div class="relative min-w-0 flex-1">
<FlowCanvas
ref="canvasRef"
:activities="activities"
:routes="routes"
:summaries="summaries"
:issues="issues.nodes"
:hints="canvasHints"
:pair-hint="pairHint"
:selected-ids="selectedIds"
:active-route-id="activeRouteId"
:show-grid="showGrid"
:snap="snap"
:edge-style="edgeStyle"
:edge-radius="edgeRadius"
:show-all-labels="showAllLabels"
:empty-hint="t('process.canvasEmpty')"
:connect-hint="t('process.connectHint')"
:delete-label="t('common.delete')"
:duplicate-label="t('form.duplicate')"
:delete-edge-label="t('process.deleteRoute')"
:fields="conditionFields"
@select="onSelect"
@move-end="pushHistory"
@connect="connect"
@delete-route="removeRoute"
@delete-nodes="removeNodes"
@duplicate-node="duplicateNode"
@edit-node="editNodeFromCanvas"
@open-route="openRoute"
@add-node="(type, at) => addNode(type, at)"
/>
<div
v-if="selectedIds.length > 1"
class="pointer-events-none absolute left-1/2 top-3 -translate-x-1/2 rounded-full bg-gray-900/85 px-3 py-1 text-[11px] font-medium text-white shadow-md"
>
{{ t('process.selectedCount', { count: selectedIds.length }) }}
</div>
</div>
<!-- 属性面板 -->
<aside
v-if="inspectorOpen"
class="flex w-[352px] flex-shrink-0 flex-col border-l border-gray-200 bg-white dark:border-dark-700 dark:bg-dark-800"
>
<div class="tabs border-b border-gray-100 px-3 pt-2 dark:border-dark-700">
<button type="button" class="tab" :class="{ 'tab-active': panel === 'node' }" @click="panel = 'node'">
{{ t('process.nodeConfig') }}
</button>
<button type="button" class="tab" :class="{ 'tab-active': panel === 'route' }" @click="panel = 'route'">
{{ t('process.routeConfig') }}
</button>
<button type="button" class="tab" :class="{ 'tab-active': panel === 'meta' }" @click="panel = 'meta'">
{{ t('process.metaPanel') }}
</button>
<button type="button" class="tab" :class="{ 'tab-active': panel === 'dedup' }" @click="openDedupAudit">
{{ t('process.dedupAudit') }}
</button>
</div>
<div class="min-h-0 flex-1 overflow-y-auto p-4">
<NodeInspector
v-if="panel === 'node' && selectedNode && !nodeConfigOpen"
:key="selectedNode.id"
v-bind="{ ...nodeInspectorProps, variant: 'rail' }"
@remove="(id) => removeNodes([id])"
@help="openGuide"
@focus-route="openRoute"
@open-form="openFormDesigner"
@open-default-form="panel = 'meta'"
@fix="onGatewayFix"
@configure="openNodeConfig"
/>
<RouteInspector
v-else-if="panel === 'route'"
:routes="routes"
:nodes="nodeOptions"
:editing-id="activeRouteId"
:default-from="selectedNode?.id ?? ''"
:fields="conditionFields"
@apply="upsertRoute"
@remove="removeRoute"
@focus="openRoute"
@cancel="activeRouteId = ''"
@invalid="appStore.warning(t('process.routeIncomplete'))"
/>
<div v-else-if="panel === 'meta'" class="space-y-3.5">
<Input v-model="meta.name" :label="t('process.name')" />
<Input v-model="meta.alias" label="Alias" />
<TextArea v-model="meta.description" :label="t('common.description')" :rows="3" />
<div>
<label class="input-label">{{ t('process.category') }}</label>
<Select v-model="meta.category" :options="categoryOptions" />
</div>
<div>
<div class="flex items-center justify-between gap-2">
<label class="input-label !mb-0">{{ t('process.defaultForm') }}</label>
<div class="flex items-center gap-0.5">
<button type="button" class="tool-btn" :title="t('form.newForm')" :disabled="formBusy" @click="createForm">
<Icon name="plus" class="h-4 w-4" />
</button>
<button type="button" class="tool-btn" :title="t('form.reloadForms')" :disabled="formBusy" @click="reloadForms">
<Icon name="refresh" class="h-4 w-4" />
</button>
<button
type="button"
class="tool-btn"
:title="t('form.openDesigner')"
:disabled="!latestForm"
@click="openFormDesigner(latestForm)"
>
<Icon name="edit" class="h-4 w-4" />
</button>
</div>
</div>
<Select v-model="latestForm" :options="formOptions" :placeholder="t('common.none')" class="mt-1.5" />
<p class="input-hint">{{ t('process.defaultFormHint') }}</p>
<!-- 谁在沿用、谁单独指定,一句话说清;只有真需要时才动环节 -->
<div v-if="manualNodes.length" class="mt-2 rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
<p class="text-xs text-gray-600 dark:text-dark-300">
{{ t('process.formUsage', { inherit: inheritCount, own: ownFormCount }) }}
</p>
<p v-if="redundantCount" class="mt-1 text-xs text-amber-600 dark:text-amber-400">
{{ t('process.formRedundant', { count: redundantCount }) }}
</p>
<button
v-if="ownFormCount"
type="button"
class="btn btn-secondary btn-sm mt-2 w-full"
@click="unifyForms"
>
<Icon name="undo" class="mr-1 h-3.5 w-3.5" />
{{ t('process.unifyForms', { count: ownFormCount }) }}
</button>
</div>
</div>
<StartScopeEditor
v-model:open="meta.open_create"
v-model:selectors="meta.start_identity_list"
:directory="approverDirectory"
/>
<div class="space-y-2.5 border-t border-gray-100 pt-3.5 dark:border-dark-700">
<p class="text-xs font-semibold uppercase tracking-wide text-gray-400">{{ t('process.approvalRules') }}</p>
<div>
<div class="flex items-center justify-between gap-2">
<span class="text-sm text-gray-700 dark:text-dark-200">{{ t('process.skipStarterAll') }}</span>
<Toggle v-model="approval.skipStarter" />
</div>
<p class="input-hint">{{ t('process.skipStarterAllHint') }}</p>
</div>
<div>
<label class="input-label">{{ t('process.repeatApprover') }}</label>
<Select v-model="repeatPolicy" :options="repeatPolicyOptions" />
<p class="input-hint">{{ t(`process.repeatPolicyHint.${repeatPolicy}`) }}</p>
</div>
<div v-if="lookaheadUsed">
<label class="input-label">{{ t('process.dedupAheadScope') }}</label>
<Select v-model="aheadScope" :options="aheadScopeOptions" />
<p class="input-hint">{{ t(`process.dedupAheadScopeHint.${aheadScope}`) }}</p>
</div>
<div v-if="lookaheadUsed" class="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
<div class="flex items-center justify-between gap-2">
<span class="text-sm text-gray-700 dark:text-dark-200">{{ t('process.dedupAheadKeepOne') }}</span>
<Toggle v-model="approval.dedupAheadKeepOne" />
</div>
<p class="input-hint">{{ t('process.dedupAheadKeepOneHint') }}</p>
</div>
</div>
<div class="space-y-2.5 border-t border-gray-100 pt-3.5 dark:border-dark-700">
<p class="text-xs font-semibold uppercase tracking-wide text-gray-400">{{ t('process.serialGroup') }}</p>
<div>
<label class="input-label">{{ t('process.serialTiming') }}</label>
<Select v-model="serialTimingMode" :options="serialTimingOptions" />
<p class="input-hint">{{ t(`process.serialTimingHint.${serial.at}`) }}</p>
</div>
<div v-if="serial.at === 'activity'" class="space-y-2.5 rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
<div>
<label class="input-label">{{ t('process.serialTimingNode') }}</label>
<Select v-model="serial.activity" :options="serialNodeOptions" :placeholder="t('process.serialTimingNodePlaceholder')" />
</div>
<div>
<label class="input-label">{{ t('process.serialTimingWhen') }}</label>
<div class="flex gap-1.5">
<button
v-for="option in serialWhenOptions"
:key="option.value"
type="button"
class="btn btn-sm flex-1"
:class="serial.when === option.value ? 'btn-primary' : 'btn-secondary'"
@click="serial.when = option.value"
>
{{ option.label }}
</button>
</div>
<p class="input-hint">{{ t(`process.serialTimingWhenHint.${serial.when}`) }}</p>
</div>
</div>
<p v-if="serialTimingWarning" class="input-hint text-amber-600 dark:text-amber-400">{{ serialTimingWarning }}</p>
<div v-if="serialPreview" class="rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
<p class="text-xs text-gray-500 dark:text-dark-300">
{{ t('process.serialTimingNext') }}
<span class="ml-1 font-mono text-gray-800 dark:text-dark-100">{{ serialPreview.sample }}</span>
</p>
<p class="mt-1 text-[11px] leading-relaxed text-gray-400 dark:text-dark-400">
{{ t(serialPreview.bound ? 'process.serialTimingNextBound' : 'process.serialTimingNextUnbound', { used: serialPreview.used }) }}
</p>
</div>
</div>
<div class="space-y-2.5 border-t border-gray-100 pt-3.5 dark:border-dark-700">
<p class="text-xs font-semibold uppercase tracking-wide text-gray-400">{{ t('process.terminateGroup') }}</p>
<div>
<div class="flex items-center justify-between gap-2">
<span class="text-sm text-gray-700 dark:text-dark-200">{{ t('process.terminateStarter') }}</span>
<Toggle v-model="terminate.allowStarter" />
</div>
<p class="input-hint">{{ t(terminate.allowStarter ? 'process.terminateStarterOnHint' : 'process.terminateStarterOffHint') }}</p>
</div>
<div v-if="terminate.allowStarter">
<label class="input-label">{{ t('process.terminateWindow') }}</label>
<Select v-model="terminateWindowMode" :options="terminateWindowOptions" />
<p class="input-hint">{{ t(`process.terminateWindowHint.${terminate.until}`) }}</p>
</div>
<div
v-if="terminate.allowStarter && terminate.until === 'beforeActivity'"
class="space-y-2.5 rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600"
>
<div>
<label class="input-label">{{ t('process.terminateNode') }}</label>
<Select
v-model="terminate.untilActivity"
:options="terminateNodeOptions"
:placeholder="t('process.terminateNodePlaceholder')"
/>
<p class="input-hint">{{ t('process.terminateNodeHint') }}</p>
</div>
</div>
<div
v-if="terminate.allowStarter && terminate.until === 'withinHours'"
class="space-y-2.5 rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600"
>
<div>
<label class="input-label">{{ t('process.terminateHours') }}({{ t('process.hoursUnit') }})</label>
<Input v-model="terminateHours" type="number" :placeholder="t('process.terminateHoursPlaceholder')" />
<p class="input-hint">{{ t('process.terminateHoursHint', { min: TERMINATE_HOURS_MIN, max: TERMINATE_HOURS_MAX }) }}</p>
</div>
</div>
<!-- 写回那一格不受上面那颗开关影响:关掉的是「发起人能不能终止」,
管理员照样终止得动,那一刻该通知上游的还是得通知。 -->
<div class="space-y-2.5 rounded-xl border border-gray-200 px-3 py-2.5 dark:border-dark-600">
<div>
<label class="input-label">{{ t('process.terminateWriteback') }}</label>
<Select
v-model="terminateCodes"
:options="terminateTemplateOptions"
multiple
:placeholder="t('process.terminateWritebackPlaceholder')"
:searchable="true"
/>
<p class="input-hint">{{ t('process.terminateWritebackHint') }}</p>
<p
v-for="line in terminateMountNotes"
:key="line"
class="input-hint text-amber-600 dark:text-amber-400"
>
{{ line }}
</p>
</div>
</div>
<p v-if="terminateWarning" class="input-hint text-amber-600 dark:text-amber-400">{{ terminateWarning }}</p>
</div>
<button type="button" class="btn btn-secondary btn-sm w-full" :disabled="busy" @click="flushSave">
<Icon name="save" class="mr-1 h-3.5 w-3.5" />
{{ t('process.saveEverything') }}
</button>
<p class="input-hint">{{ t('process.saveEverythingHint') }}</p>
</div>
<DedupAuditPanel
v-else-if="panel === 'dedup'"
:result="dedup.result.value"
:running="dedup.running.value"
:failed="dedup.failed.value"
:ran-at="dedup.ranAt.value"
:stale="dedup.stale.value"
:fix="dedupFix"
@run="dedup.run"
@focus="focusNode"
@apply-fix="applyDedupFix"
@open-meta="panel = 'meta'"
/>
<div v-else class="flex h-full flex-col items-center justify-center gap-2 py-14 text-center">
<Icon name="mousePointer" class="h-6 w-6 text-gray-300 dark:text-dark-500" />
<p class="text-sm text-gray-400">{{ t('process.pickNodeHint') }}</p>
</div>
</div>
</aside>
</div>
<BaseDialog :show="guideOpen" :title="t('process.guideTitle')" width="wide" @close="guideOpen = false">
<GatewayGuide :focus="guideFocus" />
</BaseDialog>
<!-- 试跑:选个发起人、把表单填全,先看看这一单会落在谁手上、走哪条分支 -->
<ProcessSimulateDialog
v-if="process"
:show="simulateOpen"
:process-id="processId"
:process-name="process.name"
:schema="simulateSchema"
:activities="activities"
:routes="routes"
:approval="approval"
:default-identity="authStore.user?.identity ?? ''"
@close="simulateOpen = false"
@focus="focusNode"
/>
<!-- 环节配置弹窗:右栏那一窄列装不下人工环节的全部配置,点某一格就在这儿配 -->
<NodeConfigDialog
v-if="selectedNode"
:show="nodeConfigOpen"
:activity="selectedNode"
:group="nodeConfigGroup"
:inspector="nodeInspectorProps"
:save-hint="saveHintText"
:save-hint-tone="saveHintTone"
@close="nodeConfigOpen = false"
@remove="(id) => removeNodes([id])"
@help="openGuide"
@focus-route="openRoute"
@open-form="openFormDesigner"
@open-default-form="openDefaultFormFromDialog"
@fix="onGatewayFix"
/>
</div>
<div v-else-if="loading" class="empty-state">
<LoadingSpinner />
</div>
<div v-else class="card">
<!-- 流程没加载出来,这里要的只是「回列表」,用公共那颗返回按钮 -->
<EmptyState icon="sync" :title="t('common.noData')">
<template #action>
<BackButton fallback="design-processes" />
</template>
</EmptyState>
</div>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDebounceFn } from '@vueuse/core'
import { useI18n } from 'vue-i18n'
import BackButton from '@/components/common/BackButton.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import { useDesignAutosave } from '@/composables/useDesignAutosave'
import Input from '@/components/common/Input.vue'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
import Select from '@/components/common/Select.vue'
import TextArea from '@/components/common/TextArea.vue'
import Toggle from '@/components/common/Toggle.vue'
import Icon from '@/components/icons/Icon.vue'
import BaseDialog from '@/components/common/BaseDialog.vue'
import FlowCanvas from '@/components/oa/design/FlowCanvas.vue'
import FlowPalette from '@/components/oa/design/FlowPalette.vue'
import GatewayGuide from '@/components/oa/design/GatewayGuide.vue'
import NodeInspector from '@/components/oa/design/NodeInspector.vue'
import NodeConfigDialog from '@/components/oa/design/NodeConfigDialog.vue'
import type { NodeGroupKey } from '@/utils/nodeConfig'
import RouteInspector from '@/components/oa/design/RouteInspector.vue'
import StartScopeEditor from '@/components/oa/design/StartScopeEditor.vue'
import DedupAuditPanel from '@/components/oa/design/DedupAuditPanel.vue'
import ProcessSimulateDialog from '@/components/oa/design/ProcessSimulateDialog.vue'
import { useDedupAudit } from '@/composables/useDedupAudit'
import { useGoBackTargets } from '@/composables/useGoBackTargets'
import {
SERIAL_TIMING_MODES,
SERIAL_TIMING_WHENS,
normaliseSerialTiming,
serialTimingProblemKey,
serialTimingSummaryKey
} from '@/utils/serialTiming'
import {
TERMINATE_HOURS_MAX,
TERMINATE_HOURS_MIN,
TERMINATE_UNTILS,
defaultTerminateConfig,
normaliseTerminateConfig,
terminateProblemKey,
terminateMountCodes,
terminateMountWarnings,
terminateMountWithCodes,
terminateSummaryKey
} from '@/utils/terminateConfig'
import { designAPI, integrationAPI } from '@/api'
import { isFillable } from '@/utils/formLayout'
import { formPickerOptions, usedFormIds, type FormPickerGroup } from '@/utils/formPicker'
import { formBoundNodes, formUsage, unifyForms as unifyActivityForms } from '@/utils/formBinding'
import { useAppStore } from '@/stores/app'
import { useAuthStore } from '@/stores/auth'
import { errorMessage, runAction } from '@/utils/oa'
import { formatTime } from '@/utils/format'
import { diffDesign, type DesignDiffKey, type DesignSnapshotLike } from '@/utils/designDiff'
import {
autoLayout,
DEFAULT_EDGE_STYLE,
EDGE_CORNER_RADIUS,
EDGE_STYLES,
freePosition,
defaultRouteFix,
forkFixPlan,
gatewayInfo,
graphIssues,
isGateway,
insertPointFor,
isStarterStep,
nodeSummary,
pairGateways,
NODE_W,
NODE_H,
snapPosition,
type EdgeStyle,
type GatewayInfo,
type GatewayPairHint,
type PaletteIssue,
type Point,
type SummaryLine
} from '@/utils/flowGraph'
import type { SerialPreview } from '@/api/design'
import { approverKindLabels } from '@/utils/approverTargets'
import {
DEDUP_POLICIES,
DEDUP_POLICY_KEYS,
aheadScopeOf,
dedupPolicyOf,
dedupPolicyWrite,
nodeDedupPolicyWrite,
usesLookahead,
type AheadScope,
type DedupPolicy
} from '@/utils/approvalDedup'
import { dedupFindings, dedupNodeMarks, dedupRecommendation, type DedupFix } from '@/utils/dedupAudit'
import type {
Activity,
ActivityType,
ApproverOptions,
ConditionField,
Category,
FormDef,
FormFieldDef,
FormSchema,
ProcessApproval,
ProcessDef,
ProcessSerialTiming,
ProcessTerminateConfig,
ProcessTerminateUntil,
IntegrationTemplate,
SelectOption,
SerialTimingMode,
RouteDef
} from '@/types'
const HISTORY_LIMIT = 60
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const authStore = useAuthStore()
const process = ref<ProcessDef | null>(null)
const activities = ref<Activity[]>([])
const routes = ref<RouteDef[]>([])
const forms = ref<FormDef[]>([])
const categories = ref<Category[]>([])
const siblings = ref<ProcessDef[]>([])
const approverDirectory = ref<ApproverOptions | null>(null)
const loading = ref(true)
const busy = ref(false)
const dirty = ref(false)
const canvasRef = ref<InstanceType<typeof FlowCanvas> | null>(null)
const panel = ref<'node' | 'route' | 'meta' | 'dedup'>('node')
const inspectorOpen = ref(true)
const showGrid = ref(true)
const snap = ref(true)
const edgeStyle = ref<EdgeStyle>(DEFAULT_EDGE_STYLE)
const edgeRadius = ref(EDGE_CORNER_RADIUS)
const showAllLabels = ref(true)
const selectedIds = ref<string[]>([])
const activeRouteId = ref('')
const simulateOpen = ref(false)
const guideOpen = ref(false)
const guideFocus = ref('choice')
const latestForm = ref('')
/** 流程信息;``open_create`` + ``start_identity_list`` 合起来就是「谁能发起」,
* 口径与后端 service/starters.py 一致:开放发起人人能发,限定范围按名单算。 */
const meta = reactive<{
name: string
alias: string
description: string
category: string
open_create: boolean
start_identity_list: string[]
}>({ name: '', alias: '', description: '', category: '', open_create: true, start_identity_list: [] })
/** 流程级审批规则;环节上的显式配置比这里优先。
* 默认关:开着 skipStarter 会把「填写申请」连同发起人的待办一起吞掉。 */
const approval = reactive<Required<ProcessApproval>>({
skipStarter: false,
dedup: 'none',
dedupAhead: 'none',
dedupAheadKeepOne: false
})
/** 重复审批人:界面上是一档策略,存储仍是那两个方向相反的开关(读写都过 utils/approvalDedup)。 */
const repeatPolicy = computed<DedupPolicy>({
get: () => dedupPolicyOf(approval),
set: (value) => Object.assign(approval, dedupPolicyWrite(value, aheadScopeOf(approval)))
})
const lookaheadUsed = computed(() => usesLookahead(repeatPolicy.value))
// ---------------------------------------------------------------- 流程编号
// 编号「长什么样」写在表单那一格上(field.autoRule),这里只管「什么时候排出来」:
// 出厂是发起那一刻,也可以改成存草稿就占号、走到某一环才排、或压根不自动排。
// 口径在后端 service/numbering.py + engine,这里只收配置、给摘要、保存前把关。
/** 界面上这份编号时机配置;at=activity 时 activity 指画布上某个环节的 id。 */
const serial = reactive<Required<ProcessSerialTiming>>({ at: 'start', activity: '', when: 'leave' })
const serialTimingMode = computed<SerialTimingMode>({
get: () => serial.at,
set: (value) => {
serial.at = value
}
})
const serialTimingOptions = computed(() =>
SERIAL_TIMING_MODES.map((value) => ({ value, label: t(`process.serialTimingMode.${value}`) }))
)
const serialWhenOptions = computed(() =>
SERIAL_TIMING_WHENS.map((value) => ({ value, label: t(`process.serialTimingWhen.${value}`) }))
)
/** 能被点名的环节:环节名后面带上类型,同名环节(好几个「审批」)才分得开。 */
const serialNodeOptions = computed(() =>
activities.value.map((item) => ({ value: item.id, label: `${item.name}(${typeLabel(item.type)})` }))
)
/** 指到不在画布上的环节(删过环节、从别处抄来的配置)时当场说,别等单子办完才发现没号。 */
const serialTimingWarning = computed(() => {
const key = serialTimingProblemKey(serial, activities.value.map((item) => item.id))
return key ? t(key) : ''
})
/** 「下一个编号会长成什么样」:只读计数器,不占号;规则本身仍写在表单那一格。 */
const serialPreview = ref<SerialPreview | null>(null)
async function loadSerialPreview() {
if (!latestForm.value) {
serialPreview.value = null
return
}
try {
serialPreview.value = await designAPI.formPreviewSerial({ form: latestForm.value })
} catch {
// 预览只是给人看的,接口此刻不给算就先空着,别拿报错打断配规则
serialPreview.value = null
}
}
// ------------------------------------------------------------------ 流程终止
// 「终止」这一格管三件事:发起人还能不能按那颗钮、到什么时候算过线、终止那一刻再发
// 哪几个写回模板。判据在后端 service/terminate.py 与引擎 terminate_blocker,这里只收
// 配置、给摘要、保存前把关——两边一把尺子,界面才不会写着「能终止」而引擎抛一句没见过的话。
/** 界面上这份终止配置;until=beforeActivity 时 untilActivity 指画布上某个环节的 id。 */
const terminate = reactive<Required<ProcessTerminateConfig>>(defaultTerminateConfig())
const terminateWindowMode = computed<ProcessTerminateUntil>({
get: () => terminate.until,
set: (value) => {
// 换档先过一次归一:从「按环节挡」切回「随时都能」要连着把那个环节 id 收掉,
// 留着它就是一格看上去还在挡、其实早不生效的孤儿配置
Object.assign(terminate, normaliseTerminateConfig({ ...terminate, until: value }))
}
})
const terminateWindowOptions = computed(() =>
TERMINATE_UNTILS.map((value) => ({ value, label: t(`process.terminateWindowMode.${value}`) }))
)
/** 能被点名的环节沿用编号那一列的说法:名字后面带上类型,好几个同名环节才分得开。 */
const terminateNodeOptions = serialNodeOptions
const terminateHours = computed<string>({
get: () => (terminate.untilHours ? String(terminate.untilHours) : ''),
set: (value) => {
const hours = Number(String(value).trim())
terminate.untilHours = Number.isFinite(hours) && hours > 0 ? Math.floor(hours) : 0
}
})
/** 终止那一刻点名的模板。模板本体(发什么、怎么发)仍在「集成写回」页配,这里只挂时刻。 */
const terminateTemplates = ref<IntegrationTemplate[]>([])
const terminateTemplateOptions = ref<SelectOption[]>([])
const terminateCodes = computed<string[]>({
get: () => terminateMountCodes(terminate.writeback),
set: (value) => {
terminate.writeback = terminateMountWithCodes(terminate.writeback, value ?? []) ?? {}
}
})
const terminateWarning = computed(() => {
const key = terminateProblemKey(terminate, activities.value.map((item) => item.id))
return key ? t(key) : ''
})
/** 三种「配了不响」当场点名:模板自己已勾终止、已停用、绑的是另一张表单。 */
const terminateMountNotes = computed(() =>
terminateMountWarnings(terminateCodes.value, terminateTemplates.value, latestForm.value).map((item) =>
t(item.key, item.params)
)
)
async function loadTerminateTemplates() {
let list: IntegrationTemplate[] = []
try {
list = await integrationAPI.listTemplatesCached()
} catch {
// 拉不到清单不该打断那两档窗口配置:格子空着,人照样能设「什么时候不许终止」
list = []
}
terminateTemplates.value = list
const options: SelectOption[] = list
.filter((item) => item.enabled !== false)
.map((item) => ({ value: item.code, label: `${item.name}(${item.code})` }))
// 已经挂在格子上的模板可能不在清单里(被停用),补一项编码,别让框子里显示空白
const shown = new Set(options.map((item) => String(item.value)))
terminateCodes.value.forEach((code) => {
if (!shown.has(code)) options.push({ value: code, label: code })
})
terminateTemplateOptions.value = options
}
const aheadScope = computed<AheadScope>({
get: () => aheadScopeOf(approval),
// 只在用得上前瞻的两档里生效;其余档由 repeatPolicy 自己把口径收回去
set: (value) => {
if (lookaheadUsed.value) Object.assign(approval, dedupPolicyWrite(repeatPolicy.value, value))
}
})
const repeatPolicyOptions = computed(() =>
DEDUP_POLICIES.map((item) => ({ value: item, label: t(`process.${DEDUP_POLICY_KEYS[item]}`) }))
)
// 往回看那档不关心这一项:它看的是已办,不是预测
const aheadScopeOptions = computed(() => [
{ value: 'all', label: t('process.dedupAheadScopeAll') },
{ value: 'any', label: t('process.dedupAheadScopeAny') }
])
const processId = computed(() => String(route.params.id ?? ''))
const TYPE_LABEL_KEYS: Record<string, string> = {
begin: 'process.typeBegin',
manual: 'process.typeManual',
choice: 'process.typeChoice',
parallel: 'process.typeParallel',
merge: 'process.typeMerge',
split: 'process.typeSplit',
script: 'process.typeScript',
invoke: 'process.typeInvoke',
embed: 'process.typeEmbed',
delay: 'process.typeDelay',
end: 'process.typeEnd',
cancel: 'process.typeCancel'
}
/** Label bag for the pure helpers in flowGraph, which cannot call `t` themselves. */
const graphLabels = computed(() => {
const bag: Record<string, string> = {}
Object.entries(TYPE_LABEL_KEYS).forEach(([type, key]) => {
bag[type] = t(key)
})
;[
'summaryApprover', 'summaryForm', 'summaryBranches',
'summaryScript', 'summaryWait', 'summaryChild', 'summaryEffect', 'summaryStarter', 'summaryUnset',
'summaryNoTimer', 'summaryInheritForm', 'summaryFormMissing', 'summaryStarterValue',
'summaryCancelValue', 'summaryEndValue', 'modeAny', 'modeAll', 'issueNoBegin', 'issueMultiBegin',
'issueNoEnd', 'issueNoInbound', 'issueManualNoOut', 'issueNoApprover', 'issueNoForm',
'issueEndHasOut', 'issueChoiceRoutes', 'issueChoiceDefault', 'issueParallelRoutes',
'issueMergeInbound', 'issueSplitPath', 'issueScriptEmpty', 'issueInvokeUrl', 'issueEmbedProcess',
'issueNoName', 'issueRouteDecisionConflict', 'issueRouteAmbiguous', 'issueRouteBackUnmarked',
'issueRouteBackMisleading', 'issueDanglingRoute', 'issueUnreachable', 'issueCcNoTarget',
'issueNoPairedMerge', 'issueSplitSingleRoute', 'issueMergeNoGateway', 'issueMergeQuotaOver',
'issueStarterRouteVote', 'issueStarterRouteVoteDraft'
].forEach((key) => {
bag[key] = t(`process.${key}`)
})
// 带 {n} 占位符的几句走 fmt 现算,袋子里再留一份是给纯函数的兜底路径。
;['summaryTakeOne', 'summaryDefaultRoute', 'summaryDefaultReady', 'summaryDefaultMissing',
'summaryTakeAll', 'summaryCloseAt', 'summaryNoClose', 'summaryMergeWait', 'summaryFedBy', 'summaryNoFork',
'summaryWaitAll', 'summaryWaitCount', 'summaryWaitRatio'
].forEach((key) => {
bag[key] = t(`process.${key}`)
})
// 审批人来源的显示名跟着 utils/approverTargets 那张表取,口径与设计器面板同一份
Object.assign(bag, approverKindLabels(t))
return bag
})
function typeLabel(type: string): string {
const key = TYPE_LABEL_KEYS[type]
return key ? t(key) : type
}
const selectedNode = computed(() => activities.value.find((item) => item.id === selectedIds.value[0]) ?? null)
// ------------------------------------------------------------- 环节配置弹窗
// 右栏那一窄列过去把一个环节的全部配置摊成一长条,找一个开关要滚好几屏。
// 现在右栏只留「每格现状 + 入口」,配置本体在弹窗里;双击画布上的环节同样开弹窗。
const nodeConfigOpen = ref(false)
const nodeConfigGroup = ref<NodeGroupKey | ''>('')
/** 没选中环节时的占位入参:弹窗只在选中环节时才渲染,这份不会被谁改到。 */
const BLANK_ACTIVITY: Activity = {
id: '', process: '', type: 'manual', name: '', alias: '', description: '',
x: 0, y: 0, form: '', order_number: 0, config: {}
}
/** 右栏与弹窗共用一份入参:prop 少传只会发生在这一处,不会两边各漏一半。 */
const nodeInspectorProps = computed(() => {
const node = selectedNode.value ?? BLANK_ACTIVITY
return {
activity: node,
typeLabel: typeLabel(node.type),
locked: node.type === 'begin' || node.type === 'end',
formOptions: formOptions.value,
formPlaceholder: activityFormPlaceholder.value,
defaultForm: latestForm.value,
defaultFormName: defaultFormName.value,
formEditLabel: t('form.openDesigner'),
processOptions: processOptions.value,
approverDirectory: approverDirectory.value,
issues: issues.value.nodes[node.id] ?? [],
fields: activityFields(node),
routeOptions: nodeRouteOptions(node.id),
routeTargets: nodeRouteTargets(node.id),
inbound: inboundCount(node.id),
gateway: gatewayInfoOf(node),
conditionFields: conditionFields.value,
hints: issues.value.warn[node.id] ?? [],
// 环节上没显式配的那个方向按这里的流程默认算,显示才是真正生效的那一档
dedupDefault: approval,
// 「退回到哪些环节才发」那一格:候选清单与待办页那颗「退回」同一份判据,问后端要
gobackLands: goBackTargets.landsOf(node.id),
gobackOptions: goBackTargets.optionsOf(node.id),
gobackActivityNames: goBackTargets.names.value
}
})
/** 右栏点了某一格:弹窗就停在这一格上。 */
function openNodeConfig(group: NodeGroupKey | '' = '') {
if (!selectedNode.value) return
nodeConfigGroup.value = group
nodeConfigOpen.value = true
}
/** 双击画布上的环节:先选中,再开弹窗(与双击连线直接开连线编辑一个手感)。 */
function editNodeFromCanvas(id: string) {
editNode(id)
openNodeConfig('')
}
/** 流程还没定默认表单:弹窗里点「去选表单」要回右栏那一处,别让弹窗挡着正主。 */
function openDefaultFormFromDialog() {
nodeConfigOpen.value = false
panel.value = 'meta'
}
const takenTypes = computed(() => activities.value.map((item) => item.type))
const issues = computed(() =>
graphIssues(activities.value, routes.value, graphLabels.value, {
defaultForm: latestForm.value,
formFields: (formId) => (forms.value.find((item) => item.id === formId)?.content?.fields ?? []) as FormFieldDef[]
})
)
const paletteIssues = computed<PaletteIssue[]>(() => {
const list: PaletteIssue[] = issues.value.global.map((text, index) => ({ key: `g-${index}`, text }))
Object.entries(issues.value.nodes).forEach(([id, problems]) => {
const node = activities.value.find((item) => item.id === id)
problems.forEach((text, index) => list.push({ key: `${id}-${index}`, nodeId: id, nodeName: node?.name ?? id, text }))
})
Object.entries(issues.value.warn ?? {}).forEach(([id, problems]) => {
const node = activities.value.find((item) => item.id === id)
problems.forEach((text, index) =>
list.push({ key: `w-${id}-${index}`, nodeId: id, nodeName: node?.name ?? id, text, level: 'warn' })
)
})
return list
})
/** 每个并行网关 / 数据拆分对应的汇总网关,和引擎同一套配对规则。 */
const gatewayPairs = computed(() => pairGateways(activities.value, routes.value))
function gatewayInfoOf(node: Activity | null): GatewayInfo | null {
if (!node) return null
return gatewayInfo(node, { activities: activities.value, routes: routes.value, pairs: gatewayPairs.value })
}
/** 选中一头网关时,把配对的另一个用虚线牵出来;两头都没配就什么都不画。 */
const pairHint = computed<GatewayPairHint | null>(() => {
const selected = selectedIds.value.length === 1 ? activities.value.find((item) => item.id === selectedIds.value[0]) : null
const info = gatewayInfoOf(selected ?? null)
if (!info || !selected) return null
const nameOf = (id: string) => activities.value.find((item) => item.id === id)?.name ?? id
if (info.pairedMerge) return { a: selected.id, b: info.pairedMerge, label: t('process.pairToMerge', { name: nameOf(info.pairedMerge) }) }
if (info.pairedGateway) return { a: info.pairedGateway, b: selected.id, label: t('process.pairFromGateway', { name: nameOf(info.pairedGateway) }) }
return null
})
/**
* 编号在哪一环落地,就在画布那一环的卡片上写一句。
*
* 这一档配置藏在「流程信息」面板里,流程图上不给记号的话,半年后没人记得
* 这条流程的号是走到「文控登记」才有的——退回重走会不会重复占号、结束环节为什么
* 不能选「批完之后」,都得先找得到那一环。
*/
function serialLine(id: string): SummaryLine | null {
if (serial.at !== 'activity' || serial.activity !== id) return null
return { label: t('process.serialGroup'), value: t(serialTimingSummaryKey(serial)) }
}
/**
* 这一环是不是「发起人过了这儿就不能终止」的那一环。
*
* 这一句比编号那一行更要紧:管着它的人多半是**事后**才发现按不动终止钮,
* 而不是配的时候 —— 卡片上留个记号,找得到是哪一环在挡,就不必去翻流程信息面板。
*/
function terminateLine(id: string): SummaryLine | null {
const config = normaliseTerminateConfig(terminate)
if (config.until !== 'beforeActivity' || config.untilActivity !== id) return null
return { label: t('process.terminateGroup'), value: t(terminateSummaryKey(config)) }
}
const summaries = computed<Record<string, SummaryLine[]>>(() => {
const inbound = new Map<string, number>()
routes.value.forEach((item) => inbound.set(item.to_activity, (inbound.get(item.to_activity) ?? 0) + 1))
const map: Record<string, SummaryLine[]> = {}
activities.value.forEach((node) => {
map[node.id] = nodeSummary(node, {
routes: routes.value,
activities: activities.value,
labels: graphLabels.value,
formName: (id) => forms.value.find((form) => form.id === id)?.name ?? '',
defaultFormName: latestForm.value ? forms.value.find((form) => form.id === latestForm.value)?.name ?? '' : '',
inboundCount: inbound.get(node.id) ?? 0,
serialHere: serialLine(node.id),
terminateHere: terminateLine(node.id),
pairs: gatewayPairs.value,
fmt: (key, params) => t(`process.${key}`, params ?? {})
})
})
return map
})
const nodeOptions = computed(() => activities.value.map((item) => ({ value: item.id, label: item.name })))
// ---------------------------------------------------------------- 表单:一次定,处处沿用
// 表单只在「默认表单」这一处定;环节要么沿用(form 为空),要么真有一张不一样的。
// 这三行统计是给设计器一眼看清现状用的,unifyForms 是收口的地方。
const manualNodes = computed(() => formBoundNodes(activities.value))
const defaultFormName = computed(() => forms.value.find((item) => item.id === latestForm.value)?.name ?? '')
const formUsageStats = computed(() => formUsage(activities.value, latestForm.value))
const inheritCount = computed(() => formUsageStats.value.inherit)
// 「单独指定」把与默认表单重复的那几个也算进来:它们确实被点过一遍,收口时要一起清掉
const ownFormCount = computed(() => formUsageStats.value.own + formUsageStats.value.redundant)
const redundantCount = computed(() => formUsageStats.value.redundant)
/** 让所有环节回到沿用默认表单:与默认表单相同的绑定本来就是噪音,真正换过表单的也一并收回,人点了才动。 */
function unifyForms() {
const touched = ownFormCount.value
if (!touched) return
unifyActivityForms(activities.value)
flushHistory()
appStore.success(t('process.unifyFormsDone', { count: touched }))
}
/**
* 表单下拉:表单库里的任何一张都列出来,按「本流程的 / 通用 / 别家流程的」分组。
* 分组只是把人往对的地方引,谁都能直接选中,不必先回表单页挂流程。
*/
const FORM_GROUP_LABELS: Record<FormPickerGroup, string> = {
own: 'form.groupThisProcess',
shared: 'form.groupShared',
other: 'form.groupOtherProcess'
}
const formOptions = computed<SelectOption[]>(() =>
formPickerOptions(forms.value, {
processId: processId.value,
latestForm: latestForm.value,
processName: (id) => siblings.value.find((item) => item.id === id)?.name ?? '',
groupLabel: (group) => t(FORM_GROUP_LABELS[group]),
ownedLabel: (name, owner) => t('form.labelOwnedBy', { name, owner }),
sharedLabel: (name, count) => t('form.labelUsedBy', { name, count })
})
)
/** 这套设计真正用到的表单:默认表单 + 各环节自己的,条件字段只从这些里面取。 */
const designForms = computed<FormDef[]>(() => {
const ids = usedFormIds(latestForm.value, activities.value.map((item) => item.form))
return forms.value.filter((form) => ids.has(form.id))
})
/** 试跑摆出来的那张表 = 流程的默认表单;没绑定时弹窗只按画布结构预测。 */
const simulateSchema = computed<FormSchema | null>(
() => forms.value.find((item) => item.id === latestForm.value)?.content ?? null
)
/** 条件里能引用的字段:把这套设计用到的表单字段并进来,同名只留第一个。 */
const conditionFields = computed<ConditionField[]>(() => {
const out: ConditionField[] = []
const seen = new Set<string>()
designForms.value.forEach((form) => {
const fields = form.content?.fields ?? []
fields.forEach((field) => {
if (!field.key || seen.has(field.key) || !isFillable(field)) return
seen.add(field.key)
out.push({
value: field.key,
// 只给中文名:连线标签和分支摘要要用它,key 由搭建器自己露(见 ConditionRuleEditor)
label: field.label || field.key,
type: field.type,
options: field.options?.map((option) => ({ value: option.value, label: option.label || String(option.value) })),
dictCode: field.dictCode || undefined,
// 条件比的是存进去的那一列:这一格配过「显示 / 存值」就得带过来,否则候选挑得再对也判不中
optionMap: field.optionMap
})
})
})
return out
})
/** 环节的属性面板要按字段展开权限:环节绑了自己的表单就用它,否则沿用流程默认表单。
* 开始环节自己不绑表单——它用的就是流程默认表单(发起页那张),外部审批的可写
* 白名单与查找字段从那里挑,所以不能像结束环节那样直接回空表。 */
function activityFields(node: Activity | null): FormFieldDef[] {
if (!node || node.type === 'end') return []
const formId = node.type === 'begin' ? latestForm.value : (node.form || latestForm.value)
const form = forms.value.find((item) => item.id === formId)
return (form?.content?.fields ?? []) as FormFieldDef[]
}
const categoryOptions = computed(() => categories.value.map((item) => ({ value: item.id, label: item.name })))
const processOptions = computed(() =>
siblings.value.filter((item) => item.id !== processId.value).map((item) => ({ value: item.id, label: item.name }))
)
/** A step with no form of its own falls back to the process default, so say so. */
/** 环节出口路由,超时自动流转按名字指定其中一条。 */
/** 汇聚环节要知道自己有几条入口支线,配放行票数时才看得见上限。 */
function inboundCount(id: string): number {
return routes.value.filter((item) => item.to_activity === id).length
}
function nodeRouteOptions(id: string) {
return routes.value
.filter((item) => item.from_activity === id)
.map((item) => ({ value: item.name, label: item.alias || item.name }))
}
/** 出口名 → 那条线指到的环节名:外部审批钉配旁边那句「→ 发起填写」读这里。 */
function nodeRouteTargets(id: string): Record<string, string> {
const names: Record<string, string> = {}
for (const item of routes.value) {
if (item.from_activity !== id) continue
const target = activities.value.find((node) => node.id === item.to_activity)
names[item.name] = target?.name || item.to_activity
}
return names
}
const activityFormPlaceholder = computed(() =>
latestForm.value ? `${t('common.none')} · ${t('process.inheritDefaultForm')}` : t('common.none')
)
// ---------------------------------------------------------------- history
const undoStack = ref<string[]>([])
const redoStack = ref<string[]>([])
/** 已经落到服务器上的那一份;改动跟它比才算「没保存」。写成响应式是给下面那笔账用的。 */
const savedSnapshot = ref('')
const savedMeta = ref('')
let pendingUndo: string | null = null
let applyingHistory = false
function snapshot(): string {
return JSON.stringify({
activities: activities.value,
routes: routes.value,
latestForm: latestForm.value,
edgeStyle: edgeStyle.value,
edgeRadius: edgeRadius.value,
approval: { ...approval },
serial: { ...serial },
terminate: { ...terminate }
})
}
/**
* 流程信息那一栏(名称 / 别名 / 说明 / 分类 / 允许发起)不进撤销栈:画布和它是两回事,
* Ctrl+Z 把流程名一起回退掉反而更吓人。这里只留一份「已经落库的那一份」,
* 用来判断有没有还留在浏览器里的改动。
*/
function metaSnapshot(): string {
return JSON.stringify({ ...meta })
}
/** 画布或流程信息,任一处还没到服务器上,就算「有未保存的修改」。 */
function syncDirty(): boolean {
dirty.value = snapshot() !== savedSnapshot.value || metaSnapshot() !== savedMeta.value
// 每改一笔都把自动保存那一拍往后推:dirty 只在第一次变真,拖框的后几十步得靠这里续
if (dirty.value) noteChange()
return dirty.value
}
function applySnapshot(raw: string) {
const parsed = JSON.parse(raw) as {
activities: Activity[]
routes: RouteDef[]
latestForm: string
edgeStyle?: EdgeStyle
edgeRadius?: number
approval?: ProcessApproval
serial?: ProcessSerialTiming
}
activities.value = parsed.activities ?? []
routes.value = parsed.routes ?? []
latestForm.value = parsed.latestForm ?? ''
if (parsed.edgeStyle) edgeStyle.value = parsed.edgeStyle
if (typeof parsed.edgeRadius === 'number') edgeRadius.value = parsed.edgeRadius
if (parsed.approval) Object.assign(approval, parsed.approval)
// 撤销/重做也要带着编号时机:它是跟着这张设计稿一起改的,不是流程信息那一栏的顺手改动
if (parsed.serial) Object.assign(serial, normaliseSerialTiming(parsed.serial))
selectedIds.value = selectedIds.value.filter((id) => activities.value.some((item) => item.id === id))
if (activeRouteId.value && !routes.value.some((item) => item.id === activeRouteId.value)) activeRouteId.value = ''
}
const flushHistory = useDebounceFn(() => {
if (pendingUndo === null) return
undoStack.value = [...undoStack.value.slice(-(HISTORY_LIMIT - 1)), pendingUndo]
pendingUndo = null
}, 450)
watch(
() => snapshot(),
(_next, prev) => {
if (applyingHistory || prev === undefined) return
if (pendingUndo === null) pendingUndo = prev
syncDirty()
redoStack.value = []
flushHistory()
}
)
// 流程信息不进撤销栈,所以它自己那一路只负责把「有未保存的修改」这个提示点起来
watch(meta, () => syncDirty(), { deep: true })
function pushHistory() {
flushHistory()
}
/**
* Drop the history that accumulated while the detail request was in flight.
* Without this the empty pre-load state sits at the bottom of the undo stack
* and one extra Ctrl+Z wipes a freshly opened design.
*/
function resetHistory() {
undoStack.value = []
redoStack.value = []
pendingUndo = null
}
async function undo() {
if (!undoStack.value.length) return
applyingHistory = true
redoStack.value = [...redoStack.value, snapshot()]
applySnapshot(undoStack.value[undoStack.value.length - 1])
undoStack.value = undoStack.value.slice(0, -1)
await nextTick()
applyingHistory = false
syncDirty()
}
async function redo() {
if (!redoStack.value.length) return
applyingHistory = true
undoStack.value = [...undoStack.value, snapshot()]
applySnapshot(redoStack.value[redoStack.value.length - 1])
redoStack.value = redoStack.value.slice(0, -1)
await nextTick()
applyingHistory = false
syncDirty()
}
// ---------------------------------------------------------------- graph edits
function onSelect(ids: string[], routeId: string) {
selectedIds.value = ids
activeRouteId.value = routeId
if (routeId) panel.value = 'route'
else if (ids.length) panel.value = 'node'
}
function editNode(id: string) {
selectedIds.value = [id]
activeRouteId.value = ''
panel.value = 'node'
}
function focusNode(id: string) {
editNode(id)
canvasRef.value?.centerOn(id)
}
/** 图文说明:从哪儿点进来就定位到哪一种环节。 */
function openGuide(kind = 'choice') {
guideFocus.value = kind
guideOpen.value = true
}
function openRoute(id: string) {
activeRouteId.value = id
const routeItem = routes.value.find((item) => item.id === id)
selectedIds.value = routeItem ? [routeItem.from_activity] : []
panel.value = 'route'
}
function nextNodeId(type: string): string {
return `${type}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 5)}`
}
function blankActivity(type: ActivityType, at: Point): Activity {
const count = activities.value.filter((item) => item.type === type).length + 1
return {
id: nextNodeId(type),
process: processId.value,
type,
name: `${typeLabel(type)}${count > 1 ? count : ''}`.trim(),
alias: '',
description: '',
x: Math.max(0, Math.round(at.x)),
y: Math.max(0, Math.round(at.y)),
form: '',
order_number: activities.value.length,
config: type === 'manual' ? { mode: 'any', taskValues: [] } : {}
}
}
/**
* 新环节该插进哪条线。
*
* 选中了一条线,或者选中的环节只有一条出口,就当成「想在这条线中间加一步」。
* 分支与网关几乎都是这么用的,比把光秃秃的网关丢在空白处好懂太多:线从哪儿来、
* 到哪儿去,一眼就对上了。
*/
function spliceTarget(): RouteDef | null {
const active = routes.value.find((item) => item.id === activeRouteId.value)
if (active) return active
const only = selectedIds.value.length === 1 ? activities.value.find((item) => item.id === selectedIds.value[0]) : null
if (!only) return null
const outs = routes.value.filter((item) => item.from_activity === only.id)
return outs.length === 1 ? outs[0] : null
}
/**
* 加完环节立刻说一句接下来该干什么。
*
* 没人会在动手前把四种网关的规则背下来,但动手那一下就知道下一步,画两回自然会了。
*/
function announceAdded(node: Activity, spliced: RouteDef | null) {
if (!isGateway(node.type)) return
const nameOf = (id: string) => activities.value.find((item) => item.id === id)?.name ?? ''
const parts: string[] = []
if (spliced) {
parts.push(t('process.insertedIntoLine', { from: nameOf(spliced.from_activity), to: nameOf(spliced.to_activity) }))
}
parts.push(t(`process.nextStep${node.type.charAt(0).toUpperCase()}${node.type.slice(1)}`))
appStore.info(parts.join(' · '), 7000)
}
function addNode(type: string, at?: Point) {
const activityType = type as ActivityType
if (['begin', 'end'].includes(activityType) && activities.value.some((item) => item.type === activityType)) {
appStore.warning(t('process.onlyOnce'))
return
}
// 手动拖到画布上就按落点走;点面板上的按钮时,优先插进当前选中的那条线。
const splice = at ? null : spliceTarget()
const wanted: Point = at
? { x: at.x - NODE_W / 2, y: at.y - NODE_H / 2 }
: splice
? insertPointFor(activities.value, routes.value, splice) ?? emptySpotAt(centerOfViewport())
: emptySpotAt(centerOfViewport())
const node = blankActivity(activityType, wanted)
activities.value = [...activities.value, node]
if (splice) {
// 原来的线挪到新环节身上(条件和名字都跟着走),再补一条新环节到原去向。
// 按对象本身比对而不是按 id:草稿态的路由 id 可能是空串。
routes.value = [
...routes.value.map((item) => (item === splice ? { ...item, to_activity: node.id } : item)),
newRoute(node.id, splice.to_activity)
]
}
editNode(node.id)
announceAdded(node, splice)
}
function centerOfViewport(): Point {
return canvasRef.value?.centerPoint() ?? { x: 320, y: 220 }
}
/** 以某个视口点为中心找个不压住别人的空位。 */
function emptySpotAt(focus: Point): Point {
return freePosition(activities.value, { x: focus.x - NODE_W / 2, y: focus.y - NODE_H / 2 })
}
function duplicateNode(id: string) {
const source = activities.value.find((item) => item.id === id)
if (!source) return
const copy: Activity = {
...JSON.parse(JSON.stringify(source)),
id: nextNodeId(source.type),
name: `${source.name} 2`,
x: source.x + 40,
y: source.y + 40
}
activities.value = [...activities.value, copy]
editNode(copy.id)
}
function removeNodes(ids: string[]) {
const removable = ids.filter((id) => {
const node = activities.value.find((item) => item.id === id)
return node && node.type !== 'begin' && node.type !== 'end'
})
if (!removable.length) {
appStore.warning(t('process.cannotDeleteLocked'))
return
}
activities.value = activities.value.filter((item) => !removable.includes(item.id))
routes.value = routes.value.filter((item) => !removable.includes(item.from_activity) && !removable.includes(item.to_activity))
selectedIds.value = selectedIds.value.filter((id) => !removable.includes(id))
if (activeRouteId.value && !routes.value.some((item) => item.id === activeRouteId.value)) activeRouteId.value = ''
}
/** Route names must be unique per source node, hence the numbering. */
function nextRouteName(fromId: string): string {
// 发起人那一环的第一条出口默认叫「提交」:这一环的出口名会变成待办上那颗钮的候选说法,
// 起成「下一步」就已经够含糊,起成「同意」更是把交单说成表态(判据见 utils/taskAction)。
const from = activities.value.find((item) => item.id === fromId)
if (from && isStarterStep(from) && !routes.value.some((item) => item.from_activity === fromId)) {
return t('process.starterRouteName')
}
const count = routes.value.filter((item) => item.from_activity === fromId).length
if (!count) return t('process.nextStep')
return `${t('process.routePrefix')}${count + 1}`
}
function connect(fromId: string, toId: string) {
if (fromId === toId) return
const from = activities.value.find((item) => item.id === fromId)
if (from && (from.type === 'end' || from.type === 'cancel')) {
appStore.warning(t('process.endHasNoOut'))
return
}
if (routes.value.some((item) => item.from_activity === fromId && item.to_activity === toId)) {
appStore.warning(t('process.routeExists'))
return
}
const routeItem = newRoute(fromId, toId)
routes.value = [...routes.value, routeItem]
openRoute(routeItem.id)
}
/** 建一条出口路由;名字按「同一环节下不重名」往后排。 */
function newRoute(fromId: string, toId: string, name?: string): RouteDef {
return {
id: nextNodeId('route'),
process: processId.value,
name: name ?? nextRouteName(fromId),
alias: '',
from_activity: fromId,
to_activity: toId,
decision: '',
expression: '',
order_number: routes.value.length
}
}
// ---------------------------------------------------------------- 一键补齐
const FIX_MERGE_MESSAGES: Record<'paired' | 'deadBranch' | 'fewTips', string> = {
paired: 'process.fixMergePaired',
deadBranch: 'process.fixMergeDeadBranch',
fewTips: 'process.fixMergeFewTips'
}
/**
* 「补一个汇总网关」:沿每条支线走到头,把这些线头统一接到新汇总上。
*
* 并行网关后面漏掉汇总,是这张图上最常见、后果又最隐蔽的错误(支线各走各的,
* 谁先办完谁先往下走),所以在提醒旁边直接给一个按钮,点一下就连好了。
*/
function fixMissingMerge(nodeId: string) {
const plan = forkFixPlan(activities.value, routes.value, nodeId)
if (!plan.ok) {
appStore.warning(t(FIX_MERGE_MESSAGES[plan.reason]))
return
}
const merge = blankActivity('merge', snapPosition(plan.x, plan.y))
activities.value = [...activities.value, merge]
routes.value = [...routes.value, ...plan.tips.map((tip) => newRoute(tip, merge.id))]
editNode(merge.id)
canvasRef.value?.centerOn(merge.id)
appStore.success(t('process.fixMergeDone', { name: merge.name, count: plan.tips.length }), 7000)
}
/** 「补一条默认出口」:条件都不成立时最常见的意思就是「那就到此为止」,连到结束环节。 */
function fixMissingDefault(nodeId: string) {
const plan = defaultRouteFix(activities.value, routes.value, nodeId)
if (!plan) {
appStore.warning(t('process.fixDefaultBlocked'))
return
}
const created = newRoute(nodeId, plan.to, t('process.defaultRouteName'))
routes.value = [...routes.value, created]
openRoute(created.id)
appStore.success(t('process.fixDefaultDone', { name: created.name }), 7000)
}
/** 右侧说明里的补齐按钮都从这里走。 */
function onGatewayFix(kind: 'merge' | 'default') {
const node = selectedNode.value
if (!node) return
if (kind === 'merge') fixMissingMerge(node.id)
else fixMissingDefault(node.id)
}
function upsertRoute(draft: RouteDef & { id: string }) {
if (draft.id) {
routes.value = routes.value.map((item) => (item.id === draft.id ? { ...item, ...draft, process: processId.value } : item))
appStore.success(t('process.routeApplied'))
return
}
if (routes.value.some((item) => item.from_activity === draft.from_activity && item.to_activity === draft.to_activity)) {
appStore.warning(t('process.routeExists'))
return
}
const created: RouteDef = { ...draft, id: nextNodeId('route'), process: processId.value, order_number: routes.value.length }
routes.value = [...routes.value, created]
openRoute(created.id)
appStore.success(t('process.routeAdded'))
}
function removeRoute(id: string) {
routes.value = routes.value.filter((item) => item.id !== id)
if (activeRouteId.value === id) activeRouteId.value = ''
}
function tidy() {
activities.value = autoLayout(activities.value, routes.value)
nextTick(() => canvasRef.value?.fit())
}
// ---------------------------------------------------------------- persistence
const EDGE_STYLE_KEYS: Record<EdgeStyle, string> = {
orthogonal: 'process.edgeOrthogonal',
straight: 'process.edgeStraight',
curve: 'process.edgeCurve'
}
function edgeStyleLabel(style: EdgeStyle): string {
return t(EDGE_STYLE_KEYS[style])
}
function setEdgeStyle(style: EdgeStyle) {
if (edgeStyle.value === style) return
edgeStyle.value = style
pushHistory()
}
function toggleEdgeRadius() {
edgeRadius.value = edgeRadius.value > 0 ? 0 : EDGE_CORNER_RADIUS
pushHistory()
}
function canvasPayload() {
return { edge_style: edgeStyle.value, edge_radius: edgeRadius.value }
}
function approvalPayload() {
return {
skipStarter: approval.skipStarter,
dedup: approval.dedup,
dedupAhead: approval.dedupAhead,
dedupAheadKeepOne: approval.dedupAheadKeepOne
}
}
function payloadActivities(): Activity[] {
return activities.value.map((item, index) => ({ ...item, order_number: index }))
}
/**
* 整张图落库只有这一条路:环节 + 路由 + 默认表单 + 流程级审批规则 + 流程信息。
* 工具栏那颗「保存设计」、⌘/Ctrl+S、后台自动保存、校验和发布前那一次静默保存,
* 走的都是它 —— 以前"保存"分两套口径(画布一套、流程信息一套、连线面板嘴里还有一套),
* 用户点了叫保存的东西却没存上,就是这么来的。
*
* explicit 是"用户亲手点的":自动保存成功不叮一声,工具栏上一直写着状态。
*/
async function save(explicit = true): Promise<boolean> {
// 自动保存和用户点击撞上同一拍时,共用这一次请求:两条并发写同一张图,
// 后回来的那份会把先回来的那份盖掉。
if (inflightSave) return inflightSave
inflightSave = writeDesign(explicit).finally(() => {
inflightSave = null
})
return inflightSave
}
async function writeDesign(explicit: boolean): Promise<boolean> {
busy.value = true
const saved = await designAPI
.saveDesign(processId.value, {
activities: payloadActivities(),
routes: routes.value,
latest_form: latestForm.value,
canvas: canvasPayload(),
approval_config: approvalPayload(),
serial_config: { ...serial },
// 终止那一格跟着设计一起走:它跟编号时机一样是整条流程的行文规矩,不是画布上的
// 一个环节,落库走的是同一条 save-design 接口
terminate_config: { ...terminate }
})
.catch((error: unknown) => {
noteSaveFailure(errorMessage(error))
return null
})
if (!saved) {
busy.value = false
return false
}
// 「保存设计」以前只送画布那一份:流程信息(名称、分类、允许发起……)得回右侧面板
// 点它自己的那颗保存才落库。在那里改完直接按工具栏,改动会被悄悄丢掉,刷新就回旧值,
// 而且连「有未保存的修改」都不会亮。口径对齐表单设计器:一次保存把两处都送走。
let finished = saved
if (metaSnapshot() !== savedMeta.value) {
const stored = await designAPI.updateProcess(processId.value, { ...meta }).catch((error: unknown) => {
noteSaveFailure(errorMessage(error))
return null
})
if (!stored) {
busy.value = false
return false
}
// 流程信息接口回的是光一条流程(不带环节和连线),并回去才不冲掉刚存下的那份设计
finished = { ...saved, ...stored }
}
busy.value = false
process.value = finished
savedSnapshot.value = snapshot()
savedMeta.value = metaSnapshot()
dirty.value = false
lastSaveError.value = ''
toastedFailure = ''
if (explicit) appStore.success(t('common.saveSuccess'))
return true
}
/** 上一次落库失败的原文,用来把工具栏那句「没存上」讲清楚。 */
const lastSaveError = ref('')
let toastedFailure = ''
let inflightSave: Promise<boolean> | null = null
/**
* 同一句失败原因只播报一次。自动保存会在用户每次停顿时重试,写回挂载还没配好的设计
* 就能连着撞四五次同一条错误 —— 刷屏的同一条等于没有,说一次就够,红字一直挂在工具栏上。
*/
function noteSaveFailure(message: string) {
lastSaveError.value = message
if (message && message !== toastedFailure) {
toastedFailure = message
appStore.error(message)
}
}
const {
autosave: autosaveOn,
state: saveState,
savedAt,
error: autosaveError,
flush: flushPending,
noteChange,
setAutosave
} = useDesignAutosave({
dirty,
busy,
save: (explicit) => save(explicit),
lastError: () => lastSaveError.value
})
/** 两颗保存按钮和 ⌘/Ctrl+S 都走这里:不等自动保存那一下,现在就送。 */
async function flushSave() {
await flushPending()
}
/** 落库基线存的是 JSON 字符串(撤销栈用的就是它),比对前先摊开来。 */
function parseBaseline(raw: string): DesignSnapshotLike & Record<string, unknown> {
if (!raw) return {}
try {
return JSON.parse(raw) as DesignSnapshotLike & Record<string, unknown>
} catch {
return {}
}
}
/** 还留在浏览器里的那几处改动,按环节 / 路由 / 表单 / 审批规则 / 流程信息分开数。 */
const pending = computed(() =>
diffDesign(
{ ...parseBaseline(savedSnapshot.value), meta: parseBaseline(savedMeta.value) },
{
activities: activities.value,
routes: routes.value,
latestForm: latestForm.value,
approval: { ...approval },
edgeStyle: edgeStyle.value,
edgeRadius: edgeRadius.value,
meta: { ...meta }
}
)
)
const pendingTotal = computed(() => pending.value.total)
function pendingLabel(key: DesignDiffKey, count: number): string {
if (key === 'nodes') return t('process.pendingNodes', { count })
if (key === 'routes') return t('process.pendingRoutes', { count })
if (key === 'form') return t('process.pendingForm')
if (key === 'approval') return t('process.pendingApproval')
if (key === 'display') return t('process.pendingDisplay')
return t('process.pendingMeta', { count })
}
const saveStateText = computed(() => {
if (saveState.value === 'saving') return t('process.saveStateSaving')
if (saveState.value === 'error') return t('process.saveStateError')
if (saveState.value === 'pending') return t('process.saveStatePending', { count: pendingTotal.value })
return savedAt.value
? t('process.saveStateSaved', { time: formatTime(new Date(savedAt.value)) })
: t('process.saveStateClean')
})
const saveStateClass = computed(() => ({
'text-amber-600 dark:text-amber-400': saveState.value === 'pending',
'text-red-600 dark:text-red-400': saveState.value === 'error',
'text-primary-600 dark:text-primary-300': saveState.value === 'saving',
'text-gray-400 dark:text-dark-400': saveState.value === 'saved'
}))
const saveStateIcon = computed(() => {
if (saveState.value === 'saving') return 'sync'
if (saveState.value === 'error') return 'exclamationTriangle'
return 'checkCircle'
})
const saveStateTitle = computed(() => {
const reason = autosaveError.value.trim()
if (saveState.value === 'error') {
return t('process.saveStateErrorHint', { reason: reason || t('process.saveStateError') })
}
if (saveState.value === 'saving') return t('process.saveStateSavingHint')
if (saveState.value === 'pending') {
return `${pending.value.groups.map((group) => pendingLabel(group.key, group.count)).join(' · ')}${
autosaveOn.value ? ` · ${t('process.autosaveWillSend')}` : ` · ${t('process.autosaveIsOff')}`
}`
}
return autosaveOn.value ? t('process.autosaveOnHint') : t('process.autosaveOffHint')
})
/**
* 版本号徽标上那句落款:自动保存下去的改动只对新发起的单生效,
* 在途的、以及已经办结归档的单都停在各自出发那一刻那一版设计上。
*/
const versionPinTitle = computed(() =>
[t('process.versionPinTip'), t('process.versionPinTipDone'), t('process.versionPinTipMobile')].join('\n')
)
/** 环节配置弹窗的落款:关掉弹窗前,这一环节的改动到底在不在服务器上。 */
const saveHintText = computed(() => {
const reason = autosaveError.value.trim()
if (saveState.value === 'error') {
return t('process.saveHintError', { reason: reason || t('process.saveStateError') })
}
if (saveState.value === 'saving') return t('process.saveStateSaving')
if (saveState.value === 'saved') {
return savedAt.value ? t('process.saveHintSaved', { time: formatTime(new Date(savedAt.value)) }) : ''
}
return autosaveOn.value ? t('process.saveHintAuto') : t('process.saveHintManual')
})
const saveHintTone = computed(() => {
if (saveState.value === 'error') return 'error' as const
if (saveState.value === 'saved') return 'ok' as const
return 'warn' as const
})
// --------------------------------------------------- 设计期「重复审批人」体检
// 运行时早就有免重复签字的规矩,但设计器里看不见结果:画完得发一单才知道谁被跳过了。
// 这里拿画布上这份设计(含没保存的改动)先算一遍,右栏给结论、画布上挂角标、发布前拦一句。
const dedup = useDedupAudit({
processId,
// 只把结论用得到的部分送过去:拖一下位置没必要重算一遍
draft: () => ({
activities: activities.value.map((item) => ({ ...item, x: 0, y: 0 })),
routes: routes.value,
approval: { ...approval }
})
})
// 写回那一格「退回到哪些环节才发」的候选清单:判据在引擎那一份里,前端不再算一遍图。
const goBackTargets = useGoBackTargets({
processId,
enabled: computed(() => panel.value === 'node' || nodeConfigOpen.value),
draft: () => ({
// 位置不参与落点,跟着体检那份一起抹掉,免得挪一下格子就重问一次
activities: activities.value.map((item) => ({ ...item, x: 0, y: 0 })),
routes: routes.value
})
})
const dedupFix = computed(() => dedupRecommendation(dedup.result.value))
const dedupBadge = computed(() => {
const found = dedupFindings(dedup.result.value)
return found.open + found.watch
})
/** 体检结论摊到环节上:谁在这一环会被自动跳过、谁照旧要签两次。 */
const canvasHints = computed<Record<string, string[]>>(() => {
const base = issues.value.warn ?? {}
const marks = dedupNodeMarks(dedup.result.value)
if (!Object.keys(marks).length) return base
const next: Record<string, string[]> = { ...base }
Object.entries(marks).forEach(([id, mark]) => {
const lines: string[] = []
if (mark.skip.length) lines.push(t('process.dedupCanvasSkip', { names: mark.skip.join('、') }))
if (mark.double.length) lines.push(t('process.dedupCanvasDouble', { names: mark.double.join('、') }))
if (mark.watch.length) lines.push(t('process.dedupCanvasWatch', { names: mark.watch.join('、') }))
next[id] = [...(next[id] ?? []), ...lines]
})
return next
})
function openDedupAudit() {
inspectorOpen.value = true
panel.value = 'dedup'
dedup.refresh()
}
/** 一键按下去:要么改流程默认那一档,要么把挡路的几环退回「跟随流程设置」。 */
function applyDedupFix(fix: DedupFix) {
if (fix.kind === 'flow') {
Object.assign(approval, dedupPolicyWrite(fix.policy, aheadScopeOf(approval)))
} else {
fix.nodeIds.forEach((id) => {
const node = activities.value.find((item) => item.id === id)
if (!node) return
const patch = nodeDedupPolicyWrite('')
const config = node.config as unknown as Record<string, unknown>
Object.entries(patch).forEach(([key, value]) => {
if (value === undefined) delete config[key]
else config[key] = value
})
})
}
appStore.success(t('process.dedupFixApplied'))
}
// 离开体检页签就别再为每次拖拽打后端了
watch(panel, (value) => {
if (value !== 'dedup') dedup.stop()
// 编号那一组摊在「流程信息」页里,切过来才问一次「下一个编号」(只读,不占号)
if (value === 'meta') {
void loadSerialPreview()
// 模板清单只在要摆那一格时才拉:listTemplatesCached 有进程内缓存,切回来不重复请求
void loadTerminateTemplates()
}
})
async function validate() {
const savedOk = await save(false)
if (!savedOk) return
const result = await runAction(() => designAPI.validateProcess(processId.value))
if (!result) return
if (result.valid) {
const hints =
issues.value.global.length + Object.keys(issues.value.nodes).length + Object.keys(issues.value.warn ?? {}).length
appStore.success(hints ? t('process.validateOkHints', { count: hints }) : t('process.validateOk'))
}
else appStore.error(result.problems?.[0] ?? t('process.validate'))
}
async function publish() {
const savedOk = await save(false)
if (!savedOk) return
const check = await runAction(() => designAPI.validateProcess(processId.value))
if (check && !check.valid) {
appStore.error(check.problems?.[0] ?? t('process.validate'))
return
}
// 已经算过还有「会签两次」的,发布前问一句:这可能是漏配,也可能是故意让两个人各签一道
const found = dedupFindings(dedup.result.value)
if (dedup.result.value && found.open && !window.confirm(t('process.dedupPublishConfirm', { count: found.open }))) return
const published = await runAction(() => designAPI.publishProcess(processId.value), { success: t('process.publishSuccess') })
if (published) process.value = published
}
/** 画布上有没保存的改动时先问一句,别让人白画。 */
function confirmLeave() {
return !dirty.value || window.confirm(t('process.leaveConfirm'))
}
// ------------------------------------------------------------ 表单就地关联
const formBusy = ref(false)
/** 就地新建的起步表单:跟后端建流程自带的那张同一副样子,只有一个申请事由。 */
function starterSchema(): FormSchema {
const field: FormFieldDef = {
key: 'reason', label: t('form.defaultReason'), type: 'textarea', required: true, span: 24
}
return { fields: [field], layout: { columns: 2 } }
}
function nextFormName(): string {
const base = meta.name.trim() || t('form.newForm')
const taken = new Set(forms.value.map((item) => item.name))
if (!taken.has(base)) return base
let index = 2
while (taken.has(`${base} ${index}`)) index += 1
return `${base} ${index}`
}
/** 新建一张独立表单并选成默认表单:表单不挑流程,挂上就算关联,画布照常要点保存。 */
async function createForm() {
formBusy.value = true
const saved = await runAction(
() => designAPI.createForm({ name: nextFormName(), description: meta.description, content: starterSchema() }),
{ success: t('form.createdPickHint') }
)
formBusy.value = false
if (!saved) return
forms.value = [saved, ...forms.value]
latestForm.value = saved.id
}
/** 在别的标签页改过表单时拉一下,不必回来回回跳转。 */
async function reloadForms() {
formBusy.value = true
const list = await runAction(() => designAPI.listForms(processId.value))
formBusy.value = false
if (list) forms.value = list
}
/** 跳到表单设计页改这张表单;画布还没保存时先问一句,回来时靠返回按钮原路返回。 */
function openFormDesigner(formId: string) {
if (!formId || !confirmLeave()) return
router.push({ name: 'design-form-editor', params: { id: formId } })
}
// ---------------------------------------------------------------- shortcuts
function onKeydown(event: KeyboardEvent) {
const target = event.target as HTMLElement | null
const typing = Boolean(target?.closest('input, textarea, select, [contenteditable="true"]'))
const held = event.ctrlKey || event.metaKey
if (held && event.key.toLowerCase() === 'z') {
if (typing) return
event.preventDefault()
if (event.shiftKey) redo()
else undo()
return
}
if (held && event.key.toLowerCase() === 's') {
event.preventDefault()
flushSave()
return
}
if (typing) return
if ((event.key === 'Delete' || event.key === 'Backspace') && selectedIds.value.length) {
event.preventDefault()
removeNodes(selectedIds.value)
return
}
if (event.key === 'Escape') {
selectedIds.value = []
activeRouteId.value = ''
return
}
if (held && event.key.toLowerCase() === 'd' && selectedNode.value) {
event.preventDefault()
duplicateNode(selectedNode.value.id)
return
}
if (event.key.toLowerCase() === 'f') {
canvasRef.value?.fit()
return
}
// Arrow keys nudge the selection by one grid step.
const nudges: Record<string, Point> = {
ArrowLeft: { x: -8, y: 0 },
ArrowRight: { x: 8, y: 0 },
ArrowUp: { x: 0, y: -8 },
ArrowDown: { x: 0, y: 8 }
}
const nudge = nudges[event.key]
if (nudge && selectedIds.value.length) {
event.preventDefault()
const step = event.shiftKey ? 4 : 1
selectedIds.value.forEach((id) => {
const node = activities.value.find((item) => item.id === id)
if (!node) return
node.x = Math.max(0, node.x + nudge.x * step)
node.y = Math.max(0, node.y + nudge.y * step)
})
pushHistory()
}
}
/**
* 刷新和关标签页不走前端路由,confirmLeave 那道守卫拦不到它们:以前画了半天按一次 F5
* 就全没了,一声都不吭。有未保存改动期间挂上 beforeunload,让浏览器自己出来问一句。
*/
function warnOnUnload(event: BeforeUnloadEvent) {
event.preventDefault()
// 还不认 preventDefault 的浏览器靠这个字段判断要不要弹
event.returnValue = ''
}
watch(dirty, (value) => {
if (value) window.addEventListener('beforeunload', warnOnUnload)
else window.removeEventListener('beforeunload', warnOnUnload)
})
onMounted(async () => {
window.addEventListener('keydown', onKeydown)
await load()
})
onBeforeUnmount(() => {
window.removeEventListener('keydown', onKeydown)
window.removeEventListener('beforeunload', warnOnUnload)
})
async function load() {
loading.value = true
const detail = await runAction<ProcessDef | null>(() => designAPI.getProcess(processId.value))
loading.value = false
if (!detail) return
process.value = detail
activities.value = detail.activities ?? []
routes.value = detail.routes ?? []
latestForm.value = detail.latest_form ?? ''
edgeStyle.value = (detail.canvas?.edge_style as EdgeStyle) ?? DEFAULT_EDGE_STYLE
edgeRadius.value = detail.canvas?.edge_radius ?? EDGE_CORNER_RADIUS
// 没写过的流程读成默认值,不能把它顺手提交成另一个值
Object.assign(approval, {
skipStarter: detail.approval_config?.skipStarter === true,
// 读回来先折成一档策略再写回两个键:不认识的值一律当没配过,不会顺手提交成新值
...dedupPolicyWrite(dedupPolicyOf(detail.approval_config), aheadScopeOf(detail.approval_config)),
dedupAheadKeepOne: detail.approval_config?.dedupAheadKeepOne === true
})
Object.assign(serial, normaliseSerialTiming(detail.serial_config))
Object.assign(terminate, normaliseTerminateConfig(detail.terminate_config))
Object.assign(meta, {
name: detail.name,
alias: detail.alias,
description: detail.description,
category: detail.category,
open_create: detail.open_create,
start_identity_list: [...(detail.start_identity_list ?? [])]
})
savedSnapshot.value = snapshot()
savedMeta.value = metaSnapshot()
resetHistory()
syncDirty()
const first = activities.value.find((item) => item.type === 'manual') ?? activities.value[0]
selectedIds.value = first ? [first.id] : []
const [formList, categoryList, directory, processList] = await Promise.all([
runAction(() => designAPI.listForms(processId.value)),
runAction(() => designAPI.listCategories()),
runAction(() => designAPI.approverOptions()),
runAction(() => designAPI.listProcesses())
])
forms.value = formList ?? []
categories.value = categoryList ?? []
approverDirectory.value = directory
siblings.value = processList ?? []
nextTick(() => canvasRef.value?.fit())
// 别处送人过来时带的那一环(写回模板页的「去这个环节」):选中并挪到画布正中,
// 省得人在几十个工作区里自己找。不在图上就当作没带,不报错。
const focus = String(route.query.focus ?? '').trim()
if (focus && activities.value.some((item) => item.id === focus)) {
selectedIds.value = [focus]
nextTick(() => canvasRef.value?.centerOn(focus))
}
}
</script>
<style scoped>
.tool-btn {
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 9px;
padding: 5px 7px;
color: #4b5563;
}
.tool-btn:hover:not(:disabled) {
background: rgba(100, 116, 139, 0.14);
}
.tool-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.dark .tool-btn {
color: #cbd5e1;
}
</style>