refactor(design-center): 编排壳/AI入口改用 amis 渲染(替手搓原生表单)

用户反馈手搓 input/select/嵌套弹窗又丑又不一致。改:
- NewFeatureShell → amis wizard(建实体 combo字段含引用列 → 选recipe → 发布),三步 api 直打后端、数据自动透传
- AiFeatureForm → amis form(api adaptor 包裹非标响应 + ARRAYFILTER 取草稿 targetId)
- 组件测试改为守 admin/容器(amis 内部交 Playwright);five-ring.spec 改驱动 amis wizard
与全站业务页同一套 AmisRenderer,外观一致。wizard e2e 1 passed / 72 vitest / build 绿。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-20 14:39:00 +08:00
parent a6482b112e
commit 71535929f7
5 changed files with 303 additions and 711 deletions

View File

@@ -1,361 +1,163 @@
// 人走五环 · 编排壳 —— 从零搭建一个新功能页。
// 步骤:① 选/建实体(元数据+表)→ ② 选 recipe + 填页面参数 → compileRecipe 写 standard 层拿 templateId
// → ③ 可选「进设计器微调」(editor.html 是 edit-only,模板已存在才允许) → ④ 发布(menu+5默认流)。
// 红线:发布恒人审;standard 写入恒走后端 PageSchemaWriter.upsertStandard(前端只调 compileRecipe)。
// §B.9-4:实体步内置 [+ 新建实体] Dialog,复用 ModelerFields(FieldTable)/ReferencePicker,
// 使「建含引用列的新实体」在编排流里可达;建成用返回 {entityId,tablename} 回填进入下一步。
import { useEffect, useState } from 'react';
// 人走五环 · 编排壳 —— 用 amis wizard 渲染(与全站业务页同一套 amis 渲染层,告别手搓原生表单)。
// 三步全在 amis 内:① 建实体(post /api/meta/entity) → ② 生成页(post /api/design/recipe/compile)
// → ③ 发布(post /api/design/publish)。amis wizard 把每步 api 的响应数据并入数据域,
// 故 entityId(步①返)、templateId(步②返) 在后续步骤经 ${} 直接可用,无需 React 中转。
// 红线:发布恒人审;standard 写入恒走后端 PageSchemaWriter(前端只调 /api/design/recipe/compile)。
// §B.9-4:步① 的「字段」用 combo 多行,含引用列(type=引用 → 选 referenceTable,源 /api/meta/entities)。
import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { getProfile } from '../auth/token';
import { listEntities, createEntity, type EntityAttr } from '../api/meta';
import { listRecipes, compileRecipe } from '../api/recipe';
import { publishFeature } from '../api/publish';
import { fetchMenu } from '../api/menu';
import { toast } from '../components/ui/Toast';
import { Dialog } from '../components/ui/Dialog';
import { FieldTable, buildAttribute, type FieldRow } from './ModelerFields';
import { validateTableName } from './ModelerPage';
import { AmisRenderer } from '../components/AmisRenderer';
interface EntityRow {
entityId: string;
tablename: string;
name: string;
const TYPE_OPTIONS = [
{ label: '文本', value: 'string' },
{ label: '整数', value: 'integer' },
{ label: '小数', value: 'number' },
{ label: '日期', value: 'date' },
{ label: '日期时间', value: 'datetime' },
{ label: '布尔', value: 'boolean' },
{ label: '引用(外键)', value: 'reference' },
];
const RECIPE_OPTIONS = [
{ label: '维护型 CRUD(列表 + 增删改)', value: 'maintenance-crud-v1' },
{ label: '树形 CRUD(自引用层级)', value: 'tree-crud-v1' },
];
/** 人走五环建新功能向导 amis schema。 */
function buildWizardSchema(): Record<string, unknown> {
return {
type: 'page',
className: 'h-full',
body: {
type: 'wizard',
mode: 'horizontal',
actionPrevLabel: '上一步',
actionNextLabel: '下一步',
actionNextSaveLabel: '保存并下一步',
actionFinishLabel: '完成',
renderStepIndicator: true,
steps: [
{
title: '① 建实体',
subTitle: '元数据 + 物理表',
hint: '标准列(主键/审计/版本)由后端自动补齐,无需在此添加。',
api: { method: 'post', url: '/api/meta/entity' },
body: [
{
type: 'input-text',
name: 'tablename',
label: '表名',
required: true,
placeholder: 'OA_DEMO',
description: '大写字母开头,仅大写字母/数字/下划线,3–41 位',
validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{2,40}$/' },
validationErrors: { matchRegexp: '表名格式不合法(大写字母开头,3–41 位)' },
},
{ type: 'input-text', name: 'name', label: '显示名', placeholder: '演示维护(可选)' },
{
type: 'combo',
name: 'attributes',
label: '字段',
multiple: true,
addable: true,
removable: true,
addButtonText: '加字段',
minLength: 1,
items: [
{
type: 'input-text', name: 'column', label: '列名', required: true,
placeholder: 'TITLE', columnClassName: 'w-sm',
validations: { matchRegexp: '/^[A-Z][A-Z0-9_]{0,40}$/' },
validationErrors: { matchRegexp: '大写字母开头' },
},
{ type: 'input-text', name: 'display', label: '显示名', placeholder: '标题' },
{ type: 'select', name: 'type', label: '类型', value: 'string', options: TYPE_OPTIONS, columnClassName: 'w-xs' },
{
type: 'select', name: 'referenceTable', label: '引用目标实体',
source: 'get:/api/meta/entities', labelField: 'tablename', valueField: 'tablename',
searchable: true, visibleOn: '${type === "reference"}',
description: '渲染时显该实体的显示列而非裸 id',
},
{ type: 'switch', name: 'mandatory', label: '必填', value: false },
],
},
],
},
{
title: '② 生成页面',
subTitle: '选 recipe → 落标准层',
api: {
method: 'post', url: '/api/design/recipe/compile',
data: {
tableName: '${tablename}', recipe: '${recipe}', title: '${title}',
displayField: '${displayField}', pageSize: '${pageSize}',
},
},
body: [
{ type: 'static', name: 'tablename', label: '实体表' },
{
type: 'radios', name: 'recipe', label: '页面模板 recipe',
value: 'maintenance-crud-v1', options: RECIPE_OPTIONS,
},
{ type: 'input-text', name: 'title', label: '页面标题', required: true, placeholder: '如:客户等级维护' },
{ type: 'input-text', name: 'displayField', label: '显示字段', placeholder: '可选,默认取实体显示列' },
{ type: 'input-number', name: 'pageSize', label: '每页条数', placeholder: '可选,默认 20', min: 1, max: 200 },
],
},
{
title: '③ 发布',
subTitle: '五流 + 菜单 + 部署包',
api: {
method: 'post', url: '/api/design/publish',
data: {
entityId: '${entityId}', tableName: '${tablename}', templateId: '${templateId}',
menuName: '${menuName}', generateDeploymentPackage: true,
},
},
body: [
{ type: 'static', name: 'templateId', label: '已生成模板' },
{ type: 'input-text', name: 'menuName', label: '菜单名', required: true, value: '${title}' },
{
type: 'button', label: '进设计器微调', level: 'enhance', className: 'mb-2',
actionType: 'url', url: '/editor.html?templateId=${templateId}', blank: true,
visibleOn: '${templateId}',
},
{
type: 'alert', level: 'info',
body: '发布 = 写标准页 + 触发 5 条默认服务流 + 注册菜单(当前环境立即可用),并生成生产部署包供人审上线(发布恒人审)。',
},
],
},
],
onEvent: {
finished: {
actions: [{ actionType: 'toast', args: { msgType: 'success', msg: '已发布:菜单已注册,可在左侧菜单查看新功能。' } }],
},
},
},
};
}
type Step = 'entity' | 'recipe';
const RECIPES = listRecipes(); // 静态清单(maintenance-crud-v1 / tree-crud-v1)
export function NewFeatureShell() {
const navigate = useNavigate();
const profile = getProfile();
const isAdmin = profile?.account === 'admin' || profile?.userId === 'ADMIN';
const [step, setStep] = useState<Step>('entity');
const [entities, setEntities] = useState<EntityRow[]>([]);
const [loadErr, setLoadErr] = useState('');
const [selectedEntity, setSelectedEntity] = useState<EntityRow | null>(null);
const [recipe, setRecipe] = useState<string>(RECIPES[0]?.id ?? 'maintenance-crud-v1');
const [title, setTitle] = useState('');
const [displayField, setDisplayField] = useState('');
const [pageSize, setPageSize] = useState<number | ''>('');
const [templateId, setTemplateId] = useState('');
const [compiling, setCompiling] = useState(false);
const [menuName, setMenuName] = useState('');
const [publishing, setPublishing] = useState(false);
// §B.9-4 新建实体 Dialog 态
const [createOpen, setCreateOpen] = useState(false);
const [newTable, setNewTable] = useState('');
const [newName, setNewName] = useState('');
const [newRows, setNewRows] = useState<FieldRow[]>([]);
const [creating, setCreating] = useState(false);
const [createErr, setCreateErr] = useState('');
useEffect(() => {
if (!isAdmin) return;
let alive = true;
listEntities()
.then((rows) => alive && setEntities(rows))
.catch((e: Error) => alive && setLoadErr(e.message ?? '实体加载失败'));
return () => {
alive = false;
};
}, [isAdmin]);
const schema = useMemo(buildWizardSchema, []);
if (!isAdmin) {
return <div style={{ padding: 24, color: 'var(--text-3)' }}>新建功能仅管理员可用。</div>;
}
const newTableValid = validateTableName(newTable);
const newRowsValid = newRows.every((r) => r.type !== '引用' || !!r.referenceTable);
const canCreate = newTableValid && newRowsValid && !creating;
function openCreate() {
setNewTable('');
setNewName('');
setNewRows([]);
setCreateErr('');
setCreateOpen(true);
}
async function doCreateEntity() {
setCreating(true);
setCreateErr('');
try {
const attributes: EntityAttr[] = newRows.map(buildAttribute);
const res = await createEntity({ tablename: newTable, name: newName || undefined, attributes });
// 用返回的 {entityId,tablename} 回填,并进入 recipe 步
const created: EntityRow = { entityId: res.entityId, tablename: res.tablename, name: newName || res.tablename };
setCreateOpen(false);
setSelectedEntity(created);
setStep('recipe');
// 刷新实体清单(后台异步,失败不阻塞)
listEntities()
.then((rows) => setEntities(rows))
.catch(() => undefined);
toast(`已新建实体 ${res.tablename}`, 'ok');
} catch (e) {
setCreateErr((e as Error).message ?? '建表失败');
} finally {
setCreating(false);
}
}
async function doCompile() {
if (!selectedEntity || !title.trim()) {
toast('请先选实体并填写页面标题', 'warn');
return;
}
setCompiling(true);
try {
const body: { tableName: string; recipe: string; title: string; displayField?: string; pageSize?: number } = {
tableName: selectedEntity.tablename,
recipe,
title: title.trim(),
};
if (displayField.trim()) body.displayField = displayField.trim();
if (pageSize !== '') body.pageSize = Number(pageSize);
const res = await compileRecipe(body as Parameters<typeof compileRecipe>[0]);
setTemplateId(res.templateId);
if (!menuName.trim()) setMenuName(title.trim());
toast('已生成页面,可进设计器微调或直接发布', 'ok');
} catch (e) {
toast((e as Error).message ?? '生成失败', 'err');
} finally {
setCompiling(false);
}
}
function openDesigner() {
if (!templateId) return;
window.open(`/editor.html?templateId=${encodeURIComponent(templateId)}`, '_blank');
}
async function doPublish() {
if (!selectedEntity || !templateId || !menuName.trim()) {
toast('发布需先生成页面并填写菜单名', 'warn');
return;
}
setPublishing(true);
try {
const res = await publishFeature({
entityId: selectedEntity.entityId,
tableName: selectedEntity.tablename,
templateId,
menuName: menuName.trim(),
generateDeploymentPackage: true,
});
await fetchMenu(); // 刷新左侧菜单缓存(新节点)
toast(`已发布:菜单 ${res.menuId},默认流 ${res.flows.join('、')}`, 'ok');
} catch (e) {
toast((e as Error).message ?? '发布失败', 'err');
} finally {
setPublishing(false);
}
}
return (
<div style={{ height: '100%', overflow: 'auto', padding: 'var(--pad-lg)' }} data-testid="new-feature-shell">
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
<button className="btn btn-sm" onClick={() => navigate('/design-center')}>
← 返回设计中心
</button>
<div style={{ height: '100%', display: 'flex', flexDirection: 'column' }} data-testid="new-feature-shell">
<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 'var(--pad-lg)', paddingBottom: 8 }}>
<button className="btn btn-sm" onClick={() => navigate('/design-center')}>← 返回设计中心</button>
<h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>新建功能 · 人走五环</h2>
</div>
{/* 步骤指示 */}
<div className="sub-text" style={{ marginBottom: 16 }}>
{step === 'entity' ? '步骤 1 / 2 :选择或新建实体(元数据+表)' : '步骤 2 / 2 :选 recipe、生成页面、发布'}
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: '0 var(--pad-lg) var(--pad-lg)' }}>
<AmisRenderer schema={schema} />
</div>
{loadErr ? <div style={{ padding: 12, color: 'var(--err)' }}>实体加载失败:{loadErr}</div> : null}
{step === 'entity' ? (
<div className="card" style={{ padding: 16 }}>
<div style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}>
<div style={{ flex: 1, fontWeight: 600 }}>选择已有实体</div>
<button className="btn btn-sm" data-testid="nf-new-entity" onClick={openCreate}>
+ 新建实体
</button>
</div>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr style={{ textAlign: 'left', color: 'var(--text-3)' }}>
<th style={{ padding: '6px 8px' }}>名称</th>
<th style={{ padding: '6px 8px' }}>表名</th>
<th style={{ padding: '6px 8px', width: 80 }} />
</tr>
</thead>
<tbody>
{entities.map((en) => (
<tr
key={en.entityId}
style={{
borderTop: '1px solid var(--line)',
background: selectedEntity?.entityId === en.entityId ? 'var(--hover)' : undefined,
}}
>
<td style={{ padding: '6px 8px' }}>{en.name}</td>
<td style={{ padding: '6px 8px' }} className="muted">{en.tablename}</td>
<td style={{ padding: '6px 8px' }}>
<button
className="btn btn-sm"
data-testid={`nf-entity-${en.tablename}`}
onClick={() => setSelectedEntity(en)}
>
{selectedEntity?.entityId === en.entityId ? '已选' : '选择'}
</button>
</td>
</tr>
))}
</tbody>
</table>
<div style={{ marginTop: 16, display: 'flex', gap: 8 }}>
<button
className="btn"
data-testid="nf-next-entity"
disabled={!selectedEntity}
onClick={() => setStep('recipe')}
>
下一步:选 recipe
</button>
</div>
</div>
) : (
<div className="card" style={{ padding: 16 }}>
<div style={{ marginBottom: 10 }}>
实体:<b>{selectedEntity?.name}</b>{' '}
<span className="muted">({selectedEntity?.tablename})</span>{' '}
<span className="link" onClick={() => setStep('entity')}>更换</span>
</div>
<div style={{ marginBottom: 12 }}>
<div style={{ marginBottom: 6, fontWeight: 600 }}>页面模板 recipe</div>
{RECIPES.map((r) => (
<label key={r.id} style={{ marginRight: 16, cursor: 'pointer' }} data-testid={`nf-recipe-${r.id}`}>
<input
type="radio"
name="recipe"
checked={recipe === r.id}
onChange={() => setRecipe(r.id)}
/>{' '}
{r.label}
</label>
))}
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, marginBottom: 12 }}>
<label>
<div className="muted">页面标题 *</div>
<input data-testid="nf-title" value={title} onChange={(e) => setTitle(e.target.value)} />
</label>
<label>
<div className="muted">显示字段(可选)</div>
<input
data-testid="nf-display-field"
value={displayField}
onChange={(e) => setDisplayField(e.target.value)}
/>
</label>
<label>
<div className="muted">页大小(可选)</div>
<input
data-testid="nf-page-size"
type="number"
value={pageSize}
onChange={(e) => setPageSize(e.target.value === '' ? '' : Number(e.target.value))}
/>
</label>
</div>
<div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
<button className="btn" data-testid="nf-compile" disabled={compiling || !title.trim()} onClick={doCompile}>
{compiling ? '生成中…' : templateId ? '重新生成页面' : '生成页面'}
</button>
<button
className="btn"
data-testid="nf-open-designer"
disabled={!templateId}
onClick={openDesigner}
title={templateId ? '在新标签页打开设计器微调' : '先生成页面才能进设计器'}
>
进设计器微调
</button>
</div>
{templateId ? (
<div className="card" style={{ padding: 12, background: 'var(--surface-2)' }}>
<div style={{ marginBottom: 8 }}>
已生成模板:<code data-testid="nf-template-id">{templateId}</code>
</div>
<div style={{ display: 'flex', alignItems: 'flex-end', gap: 8 }}>
<label>
<div className="muted">菜单名 *</div>
<input data-testid="nf-menu-name" value={menuName} onChange={(e) => setMenuName(e.target.value)} />
</label>
<button
className="btn btn-primary"
data-testid="nf-publish"
disabled={publishing || !menuName.trim()}
onClick={doPublish}
>
{publishing ? '发布中…' : '发布'}
</button>
</div>
<div className="sub-text" style={{ marginTop: 8 }}>
发布 = 写标准页 + 触发 5 条默认流 + 注册菜单(当前后端立即可用);并生成生产部署包供人审上线。
</div>
</div>
) : null}
</div>
)}
{createOpen ? (
<Dialog
title="新建实体(含引用列)"
width={720}
onClose={() => setCreateOpen(false)}
foot={
<>
<button className="btn" onClick={() => setCreateOpen(false)}>取消</button>
<button
className="btn btn-primary"
data-testid="nf-create-submit"
disabled={!canCreate}
onClick={doCreateEntity}
>
{creating ? '建表中…' : '建表并使用'}
</button>
</>
}
>
<div style={{ display: 'grid', gap: 12 }}>
<label style={{ display: 'grid', gap: 4 }}>
<span className="sub-text">表名(大写字母开头,仅大写字母/数字/下划线,3–41 位)</span>
<input
data-testid="nf-create-tablename"
value={newTable}
onChange={(ev) => setNewTable(ev.target.value.toUpperCase())}
placeholder="OA_DEMO"
/>
{newTable && !newTableValid ? (
<span style={{ color: 'var(--err)', fontSize: 11 }}>表名格式不合法</span>
) : null}
</label>
<label style={{ display: 'grid', gap: 4 }}>
<span className="sub-text">显示名(可选)</span>
<input value={newName} onChange={(ev) => setNewName(ev.target.value)} placeholder="演示维护" />
</label>
<FieldTable rows={newRows} onChange={setNewRows} />
{createErr ? <div style={{ color: 'var(--err)', fontSize: 12 }}>{createErr}</div> : null}
</div>
</Dialog>
) : null}
</div>
);
}