Просмотр исходного кода

feat: migrate visual template administration

彭峰 1 месяц назад
Родитель
Сommit
072a34a553

+ 1 - 0
docs/migration/admin-migration-status.md

@@ -47,6 +47,7 @@
 - 旧 `User/Role` 的 9 个管理员角色、3 个用户角色与 `ARoleAuth` 权限记录已迁到 Angular“系统角色”页及 `roles/saveRole/roleAuthorization/saveRoleAuthorization/roleBatch`:支持角色类型切换、搜索、分页、名称防重、原子 `roleId`、12 个旧权限域完整编辑及权限码格式校验。角色类型创建后不得在 `admin/user` 之间迁移;删除前同时检查 `Manager.adminRole` 和 `_User.legacyUserData.UserRole`,无账号引用时才级联删除 `ARoleAuth`。Parse 原生 `_Role` 为空,`Permission` 是另一套网页设计师模型,二者都没有被误当作旧 `ZL_Role`。交付程序中 `B_ARoleAuth.Check/CheckEx/AuthCheckEx` 均固定返回 `true`,因此保留的旧权限码不用来绕过当前云函数的独立管理员会话与帐套校验。
 - `Extend/Safe` 的 15 个入口已完成数据与运行时审计:线上全部 Schema 仅命中不相关的 `SafeMobile`,没有旧 `Safe_IP`、非法词库、扫描结果或站点保护配置。旧聚合 `API` 还依赖服务器站点文件、五秒后返回的 Razor 局部页、`ContentWordHelper` 常驻线程与进度缓存;`SiteProtect_Submit` 只更新旧 `SiteConfig.Safe_ContentCheck_Models`,`ContentCheckConfig_Submit` 直接写 `IllegalWordsVerify.keywordsVPath` 服务器文件。当前内容写入链不消费这些配置,单纯存入 Parse Config 会伪造安全能力;因此 IP 三项按数据缺失、其余按基础设施缺失由 `legacySafeBlocker` 返回逐项 `migration_blocked`。
 - 旧 `Design/Scene` 的普通场景管理已迁到 Angular“可视化场景”页:`designScenes` 复刻 `ZType=0、TlpID=0` 及正常/回收站状态范围,提供帐套隔离、搜索和分页;`saveDesignScene` 只更新旧编辑页允许的标题、用户、积分、状态、搜索标记、预览图、缩略图、说明和 Meta,并从同帐套 `_User` 同步用户名。`designSceneBatch` 覆盖回收、恢复与彻底删除;`createDesignSceneTemplate` 完整复制布局/组件/资源数据,分别用 PostgreSQL advisory lock 原子分配 `DesignTlp.id` 和模板副本 `DesignScence.id`,任一步失败都会补偿清理。普通场景的新建仍依赖已丢失的可视化设计器初始化协议,因此专用保存接口只接受现有场景。
+- 旧 `Design/Template` 的模板列表、回收站、表单和生命周期已迁到 Angular“可视化模板”页:`designTemplates` 支持帐套、状态、原始 `classId` 和关键词筛选;`saveDesignTemplate` 白名单维护名称、分类编号、价格、预览图、积分、状态、来源和说明,新建时原子分配模板及空模板场景编号,失败会补偿清理;`designTemplateBatch` 覆盖回收、恢复及模板与关联场景的完整删除。目标没有 `DesignTlpClass`,因此页面保留历史 `classId` 数字而不伪造分类名称。`designTemplateEditorTarget` 可解析真实场景 GUID 与旧 `/design/default?id=...` 地址,但旧可视化编辑器的前端资产、布局交互和渲染运行时未交付,所以 `GoDesign` 保持明确的部分迁移状态。
 - 旧 `NodeAdd_Submit`、`Node_API` 与 `UnionNode_Move` 的核心栏目生命周期已迁为专用 `saveNode/nodeBatch`:新增栏目以临时来源键完成 Parse 初始写入,再使用 PostgreSQL 事务锁原子分配 `nodeId/orderId` 并替换为旧 `sourceKey`;保存会校验同级名称/目录重复、父栏目帐套和回收状态,移动会阻断自身/下级循环并递归修正所有后代深度。回收、恢复和每批 1–100 个栏目迁移已接入 Angular;永久删除仅在没有内容、下级栏目、节点权限和模型模板引用时开放,通用保存与删除不能绕过。
 - 旧 `SpecialAdd_Save` 与 `UnionSpecial_Move` 已迁为专用 `saveSpecial/specialBatch`:新增专题使用临时来源键和 PostgreSQL 事务锁原子分配 `specId/orderId`,保存时校验全帐套名称/目录唯一、父专题归属与层级循环;删除会拒绝仍有下级专题的记录。旧 `UnionSpecial_Merge` 被明确列为数据阻塞:`CommonModel.specialId` 只存在于 Parse Schema、PostgreSQL 物理列缺失,商品主表也未迁移,无法安全改写内容/商品专题关系。
 - 旧 `ModelManage/Field/Order_Submit` 的安全部分已迁为 `saveModelMetadata/saveModelFieldMetadata/modelFieldOrder`:现有模型可编辑名称、条目文案、图标、说明和内容模板元数据,现有字段可编辑别名、提示、显示/搜索配置,并可在同模型内批量排序;`modelId/modelType/tableName/fieldId/modelId/fieldName/fieldType/sourceKey` 等结构字段通用只读。新增、复制、删除模型或字段会显式返回 501,因为旧实现同时执行 PostgreSQL 建表/改列、标签生成和模板文件写入,目标托管环境没有该 DDL/旧模板运行时。

+ 32 - 2
scripts/deploy-admin-functions.mjs

@@ -20,7 +20,7 @@ const CLASS_LABELS = {
 const ALLOWED_CLASSES = new Set([
   'PageTemplate','PaperQuestions','PayPlat','Permission','PlatComp','App','DesignAnswer','DesignAsk','Attachment','DesignPage','DesignQuestion','DesignRes','Feedback','DesignScence','StudentAchieve','ContentArticle','DesignSiteInfo','Profile','AdInfo','AdZone','ARoleAuth','Baike','ExamSysQuestions','ContactInfo','VocabularyWord','AssessmentProfile','Agency','MemoryPracticeRecord','DeliveryCenter','CourseBinding','PracticeRecord','CourseAppointment','Account','SurveyItem','SurveyLog','LessonRecord','DailyStudyRecord','CommonModel','ContentPublish','Company','_Role','_User','CRMSAttr','Currency','Datadic','Datadiccategory','DesignTlp','DocModel','DocPermission','ExamClass','ExamSysPapers','ExamType','ExamPoint','ExTeacher','FontPicShape','FontPicShapeType','Grade','GradeCate','Group','GroupModel','GuestBar','Guestbook','Guestcate','MailTemp','Manager','MisProcedure','MisProLevel','MisSign','MisType','PageStyle','Model','ModelField','Node','NodeAuth','NodeModelTemplate','Product','PlatUserRole','Pub','PubTw','PubWTHD','PubZXDC','PublishNode','QuestionsKnowledge','Role','StoreProduct','SafeMobile','Search','SenTask','ServiceSeat','ShopFareTlp','ShopMoneyRegular','Special','StoreApplication','StoreStyle','SysCSSManage','SysHoliday','SysLog','Temp','ThirdPlatInfo','UserCredit','UserDummyPoint','UserFriendGroup','UserLevel','UserMoneyLog','UserPromotion','UserSIcon','UserUserPoint','UserExpDomP','UserExpHis'
 ]);
-const READ_ONLY_CLASSES = new Set(['_Role','Permission','ARoleAuth','DesignTlp','PayPlat','ThirdPlatInfo','GuestBar','DesignAnswer','Baike','ExamSysPapers','ExamSysQuestions','PaperQuestions','ExamType','ContentPublish','PublishNode','SysLog','Pub','PubTw','PubWTHD','PubZXDC']);
+const READ_ONLY_CLASSES = new Set(['_Role','Permission','ARoleAuth','PayPlat','ThirdPlatInfo','GuestBar','DesignAnswer','Baike','ExamSysPapers','ExamSysQuestions','PaperQuestions','ExamType','ContentPublish','PublishNode','SysLog','Pub','PubTw','PubWTHD','PubZXDC']);
 const SYSTEM_FIELDS = new Set(['objectId','createdAt','updatedAt','ACL','company','password','authData','sessionToken','legacyPasswordHash','legacyPasswordHashType','appPassword','newapiToken','fmodeApiToken','useMasterKey','adminPassword','randNumber','adminRoleKey','isAdmin','roles','role','isDisabled','legacyUserId','legacyGroupId','legacyUserData','legacyUserPlat','groupId']);
 const HIDDEN_FIELDS = new Set(['password','authData','sessionToken','legacyPasswordHash','legacyPasswordHashType','appPassword','newapiToken','fmodeApiToken','useMasterKey','adminPassword','randNumber','apiKey','appSecret','secret','token']);
 const GENERIC_WRITE_TYPES = new Set(['String','Number','Boolean','Date','Pointer','Object','Array']);
@@ -53,7 +53,7 @@ const CLASS_SYSTEM_FIELDS = {
   DesignAnswer: new Set(['id','askId','ip','cdate','userId','sourceKey']),
   DesignRes: new Set(['id','vpath','previewimg','cdate','userid','sourceKey']),
   DesignScence: new Set(['id','guid','comp','page','path','cdate','cuser','tlpId','ztype','scence','siteId','update','company','orderId','labelArr','resource','userName','accessPwd','sourceKey']),
-  DesignTlp: new Set(['id','cdate','defBy','isDef','price','score','ztype','classId','company','sourceKey']),
+  DesignTlp: new Set(['id','cdate','isDef','ztype','company','sourceKey']),
   Role: new Set(['roleId','ztype','zstatus','nodeId','auth','auth2','auth3','cadminId','cdate','sourceKey']),
   ARoleAuth: new Set(['id','rid','adminId','sourceKey']),
   ServiceSeat: new Set(['sId','sAdminId','sRemrk','sDateTime','sourceKey']),
@@ -1176,6 +1176,34 @@ async function handler(request, response) {
       } catch (error) { if (clone && clone.id) await clone.destroy({ useMasterKey: true }).catch(() => undefined); if (template.id) await template.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '场景复制为模板失败: ' + String(error && error.message || error)); }
       await Promise.all([template.fetch({ useMasterKey: true }), clone.fetch({ useMasterKey: true })]); await audit({ ...context, company }, 'create-template-from-design-scene', 'DesignScence', source.id); return response.json({ success: true, data: { template: serializeObject(template), scene: serializeObject(clone) } });
     }
+    if (operation === 'designTemplates') {
+      const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const status = Number(input.status == null ? -100 : input.status); const classId = Number(input.classId == null ? -100 : input.classId); const search = String(input.search || '').trim().toLowerCase(); if (![-100,-2].includes(status) || !Number.isInteger(classId) || classId < -100 || search.length > 100) fail(400, '模板状态、分类编号或搜索词无效');
+      const fields = await schemaFor('DesignTlp'); const query = new Parse.Query('DesignTlp'); applyTenant(query, fields, context, input.companyId); if (status === -2) query.equalTo('zstatus', -2); else query.notEqualTo('zstatus', -2); if (classId !== -100) query.equalTo('classId', classId); query.limit(1000); let results = await query.find({ useMasterKey: true }); if (results.length >= 1000) fail(409, '模板数量超过安全分页上限,请缩小帐套或分类范围'); results = results.filter((entry) => !search || [entry.get('tlpName'),entry.get('remind'),entry.get('defBy'),entry.get('previewImg')].some((value) => String(value || '').toLowerCase().includes(search))); results.sort((left, right) => Number(right.get('zstatus') || 0) - Number(left.get('zstatus') || 0) || Number(right.get('id') || 0) - Number(left.get('id') || 0)); const total = results.length; results = results.slice((page - 1) * pageSize, page * pageSize);
+      return response.json({ success: true, data: { className: 'DesignTlp', page, pageSize, total, status, classId, results: results.map(serializeObject) } });
+    }
+    if (operation === 'designTemplate') {
+      const objectId = String(input.objectId || ''); if (!objectId) fail(400, '缺少模板 objectId'); const fields = await schemaFor('DesignTlp'); const query = new Parse.Query('DesignTlp'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true }); const templateId = Number(target.get('id')) || 0; const sceneFields = await schemaFor('DesignScence'); const sceneQuery = new Parse.Query('DesignScence'); applyTenant(sceneQuery, sceneFields, { ...context, company: target.get('company') || context.company }, pointerId(target.get('company'))); sceneQuery.equalTo('tlpId', templateId); sceneQuery.equalTo('ztype', 1); sceneQuery.ascending('id'); sceneQuery.limit(1); const scene = templateId ? await sceneQuery.first({ useMasterKey: true }) : null;
+      return response.json({ success: true, data: { ...serializeObject(target), designScene: scene ? serializeObject(scene) : null } });
+    }
+    if (operation === 'designTemplateEditorTarget') {
+      const objectId = String(input.objectId || ''); if (!objectId) fail(400, '缺少模板 objectId'); const fields = await schemaFor('DesignTlp'); const query = new Parse.Query('DesignTlp'); applyTenant(query, fields, context, input.companyId); const target = await query.get(objectId, { useMasterKey: true }); const templateId = Number(target.get('id')) || 0; if (!templateId) fail(409, '模板缺少旧数字 ID'); const sceneFields = await schemaFor('DesignScence'); const sceneQuery = new Parse.Query('DesignScence'); applyTenant(sceneQuery, sceneFields, { ...context, company: target.get('company') || context.company }, pointerId(target.get('company'))); sceneQuery.equalTo('tlpId', templateId); sceneQuery.equalTo('ztype', 1); sceneQuery.ascending('id'); sceneQuery.limit(1); const scene = await sceneQuery.first({ useMasterKey: true }); const guid = String(scene && scene.get('guid') || ''); if (!scene || !guid) fail(409, '模板没有可定位的设计场景 GUID');
+      return response.json({ success: true, data: { templateObjectId: target.id, templateId, sceneObjectId: scene.id, guid, legacyPath: '/design/default?id=' + encodeURIComponent(guid), available: false, reason: '旧可视化设计器前端资产、布局交互和渲染运行时未迁入 Angular' } });
+    }
+    if (operation === 'saveDesignTemplate') {
+      const objectId = String(input.objectId || ''); const payload = input.fields && typeof input.fields === 'object' ? input.fields : {}; const tlpName = String(payload.tlpName || '').trim(); const previewImg = String(payload.previewImg || '').trim(); const remind = String(payload.remind || '').trim(); const defBy = String(payload.defBy || '').trim(); const classId = Number(payload.classId == null || payload.classId === '' ? 0 : payload.classId); const price = Number(payload.price == null || payload.price === '' ? 0 : payload.price); const score = Number(payload.score == null || payload.score === '' ? 0 : payload.score); const zstatus = Number(payload.zstatus == null || payload.zstatus === '' ? 0 : payload.zstatus);
+      if (!tlpName || tlpName.length > 200 || previewImg.length > 1000 || remind.length > 2000 || defBy.length > 100 || !Number.isInteger(classId) || classId < 0 || classId > 1000000000 || !Number.isFinite(price) || price < 0 || price > 1000000000 || !Number.isFinite(score) || Math.abs(score) > 1000000000 || !Number.isInteger(zstatus) || zstatus < -2 || zstatus > 999) fail(400, '模板名称、分类、价格、积分、状态或说明字段无效');
+      let companyId = pointerId(context.company); if (context.isSuperAdmin && input.companyId) companyId = String(input.companyId); if (!companyId) fail(400, '模板必须指定帐套'); const company = await new Parse.Query('Company').get(companyId, { useMasterKey: true }); const fields = await schemaFor('DesignTlp'); let target; let scene = null; const created = !objectId;
+      if (objectId) { const query = new Parse.Query('DesignTlp'); applyTenant(query, fields, context, input.companyId); target = await query.get(objectId, { useMasterKey: true }); companyId = pointerId(target.get('company')) || companyId; } else { target = new Parse.Object('DesignTlp'); target.set('company', company); target.set('sourceKey', 'cloud:design-template:' + companyId + ':' + Date.now() + ':' + Math.random().toString(36).slice(2,10)); target.set('cdate', new Date()); target.set('isDef', 0); }
+      target.set('tlpName', tlpName); target.set('classId', classId); target.set('ztype', 1); target.set('price', price); target.set('previewImg', previewImg); target.set('score', score); target.set('zstatus', zstatus); target.set('defBy', defBy); target.set('remind', remind);
+      try {
+        await target.save(null, { useMasterKey: true }); if (created) { const templateRows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-design-template-id:\'||$1))),next_id AS MATERIALIZED (SELECT COALESCE(MAX("id"),0)+1 AS id FROM "DesignTlp",lock_row WHERE "company"=$1) UPDATE "DesignTlp" SET "id"=next_id.id,"sourceKey"=\'[["ID",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id', [companyId, target.id]); const templateId = Number(templateRows[0] && templateRows[0].id); if (!templateId) throw new Error('无法分配模板编号'); const now = new Date(); const hex = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).slice(1); scene = new Parse.Object('DesignScence'); scene.set('company', target.get('company') || company); scene.set('sourceKey', 'cloud:design-template-scene:' + companyId + ':' + templateId + ':' + Date.now()); scene.set('tlpId', templateId); scene.set('ztype', 1); scene.set('status', 0); scene.set('previewImg', previewImg); scene.set('guid', hex()+hex()+'-'+hex()+'-4'+hex().slice(1)+'-'+hex()+'-'+hex()+hex()+hex()); scene.set('cdate', now); scene.set('update', now); scene.set('score', 0); scene.set('userId', 0); scene.set('userName', ''); await scene.save(null, { useMasterKey: true }); const sceneRows = await Psql.query('WITH lock_row AS MATERIALIZED (SELECT pg_advisory_xact_lock(hashtext(\'xiaoshu-design-scene-id:\'||$1))),next_id AS MATERIALIZED (SELECT COALESCE(MAX("id"),0)+1 AS id FROM "DesignScence",lock_row WHERE "company"=$1) UPDATE "DesignScence" SET "id"=next_id.id,"sourceKey"=\'[["ID",\'||next_id.id::text||\']]\',"updatedAt"=NOW() FROM next_id WHERE "objectId"=$2 RETURNING next_id.id', [companyId, scene.id]); if (!Number(sceneRows[0] && sceneRows[0].id)) throw new Error('无法分配模板场景编号'); } }
+      catch (error) { if (created && scene && scene.id) await scene.destroy({ useMasterKey: true }).catch(() => undefined); if (created && target.id) await target.destroy({ useMasterKey: true }).catch(() => undefined); fail(422, '模板保存失败: ' + String(error && error.message || error)); }
+      await target.fetch({ useMasterKey: true }); if (scene) await scene.fetch({ useMasterKey: true }); await audit({ ...context, company: target.get('company') || company }, created ? 'create-design-template' : 'update-design-template', 'DesignTlp', target.id); return response.json({ success: true, data: { ...serializeObject(target), designScene: scene ? serializeObject(scene) : null } });
+    }
+    if (operation === 'designTemplateBatch') {
+      if (String(input.className || '') !== 'DesignTlp') fail(400, '模板批量操作的数据类无效'); const action = String(input.action || ''); if (!['recycle','restore','delete'].includes(action)) fail(400, '不支持的模板批量操作'); const objectIds = [...new Set((Array.isArray(input.objectIds) ? input.objectIds : [input.objectId]).map((value) => String(value || '').trim()).filter(Boolean))]; if (!objectIds.length || objectIds.length > 100) fail(400, '每次请选择 1 至 100 个模板'); const fields = await schemaFor('DesignTlp'); const query = new Parse.Query('DesignTlp'); applyTenant(query, fields, context, input.companyId); query.containedIn('objectId', objectIds); query.limit(objectIds.length); const targets = await query.find({ useMasterKey: true }); if (targets.length !== objectIds.length) fail(404, '部分模板不存在或不属于当前帐套'); let deletedScenes = 0;
+      if (action === 'delete') { const sceneFields = await schemaFor('DesignScence'); const scenes = []; for (const target of targets) { const templateId = Number(target.get('id')) || 0; if (!templateId) fail(409, '模板缺少旧数字 ID'); const sceneQuery = new Parse.Query('DesignScence'); applyTenant(sceneQuery, sceneFields, { ...context, company: target.get('company') || context.company }, pointerId(target.get('company'))); sceneQuery.equalTo('tlpId', templateId); sceneQuery.equalTo('ztype', 1); sceneQuery.limit(1000); const linked = await sceneQuery.find({ useMasterKey: true }); if (linked.length >= 1000) fail(409, '模板关联场景超过安全删除上限'); scenes.push(...linked); } if (scenes.length) { await Parse.Object.destroyAll(scenes, { useMasterKey: true }); deletedScenes = scenes.length; } await Parse.Object.destroyAll(targets, { useMasterKey: true }); } else { for (const target of targets) target.set('zstatus', action === 'recycle' ? -2 : 0); await Parse.Object.saveAll(targets, { useMasterKey: true }); } for (const target of targets) await audit({ ...context, company: target.get('company') || context.company }, 'design-template-' + action, 'DesignTlp', target.id); return response.json({ success: true, data: { action, updated: targets.length, deletedScenes, results: action === 'delete' ? [] : targets.map(serializeObject) } });
+    }
     if (operation === 'roles') {
       const page = Math.max(1, Number(input.page) || 1); const pageSize = Math.min(100, Math.max(1, Number(input.pageSize) || 20)); const type = String(input.type || 'admin').trim().toLowerCase(); const search = String(input.search || '').trim().toLowerCase(); if (!['admin','user','-100'].includes(type) || search.length > 100) fail(400, '角色类型或搜索词无效');
       const fields = await schemaFor('Role'); const query = new Parse.Query('Role'); applyTenant(query, fields, context, input.companyId); query.limit(1000); let results = await query.find({ useMasterKey: true }); results = results.filter((entry) => (type === '-100' || String(entry.get('ztype') || 'admin').toLowerCase() === type) && (!search || [entry.get('roleName'),entry.get('description')].some((value) => String(value || '').toLowerCase().includes(search)))); results.sort((left, right) => Number(left.get('roleId') || 0) - Number(right.get('roleId') || 0)); const total = results.length; results = results.slice((page - 1) * pageSize, page * pageSize);
@@ -2069,6 +2097,7 @@ async function handler(request, response) {
       if (className === 'PlatComp') fail(400, '协同办公企业必须走专用保存流程');
       if (className === 'DesignRes') fail(400, '设计资源必须走专用保存流程');
       if (className === 'DesignScence') fail(400, '可视化场景必须走专用保存流程');
+      if (className === 'DesignTlp') fail(400, '可视化模板必须走专用保存流程');
       if (className === 'Role') fail(400, '系统角色必须走专用保存流程');
       if (className === 'CommonModel' && !objectId) fail(400, '内容新增必须同时写入模型附表,不能走通用保存');
       let object;
@@ -2094,6 +2123,7 @@ async function handler(request, response) {
       if (className === 'PlatComp') fail(400, '协同办公企业必须走专用批量流程');
       if (className === 'DesignRes') fail(400, '设计资源必须走专用批量流程');
       if (className === 'DesignScence') fail(400, '可视化场景必须走专用批量流程');
+      if (className === 'DesignTlp') fail(400, '可视化模板必须走专用批量流程');
       if (className === 'Role') fail(400, '系统角色必须走专用批量流程');
       if (className === 'Guestcate') { const cateid = Number(object.get('cateid')) || 0; const companyId = pointerId(object.get('company')); const refs = await Psql.one('SELECT (SELECT COUNT(*)::int FROM "Guestcate" WHERE "company"=$1 AND "parentId"=$2) AS children,(SELECT COUNT(*)::int FROM "Guestbook" WHERE "company"=$1 AND "cateid"=$2) AS messages,(SELECT COUNT(*)::int FROM "GuestBar" WHERE "company"=$1 AND "cateId"=$2) AS posts', [companyId, cateid]); if (Number(refs.children) || Number(refs.messages) || Number(refs.posts)) fail(409, '分类仍被下级分类、留言或帖子引用,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-guest-category', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }
       if (className === 'ExamClass') { const classId = Number(object.get('cId')) || 0; const companyId = pointerId(object.get('company')); const refs = await Psql.one('SELECT (SELECT COUNT(*)::int FROM "ExamClass" WHERE "company"=$1 AND "cClassid"=$2) AS children,(SELECT COUNT(*)::int FROM "ExamSysQuestions" WHERE "company"=$1 AND "pClass"=$2) AS questions', [companyId, classId]); if (Number(refs.children) || Number(refs.questions)) fail(409, '试题分类仍被下级分类或试题引用,不能删除'); await object.destroy({ useMasterKey: true }); await audit(context, 'delete-exam-class', className, objectId); return response.json({ success: true, data: { objectId, softDeleted: false } }); }

+ 6 - 0
scripts/generate-admin-coverage.mjs

@@ -318,6 +318,12 @@ const explicit = new Map([
   ['Design / Scene/SceneAdd', ['implemented', '已由 Angular 现有场景编辑抽屉替代,并将布局、组件、资源、路径、编号和模板关系锁为只读']],
   ['Design / Scene/SceneAdd_Submit', ['implemented', 'saveDesignScene 白名单更新旧页 9 个字段、校验帐套用户并同步 UserName 与更新时间']],
   ['Design / Scene/Scene_API', ['implemented', 'designSceneBatch 覆盖回收、恢复、彻底删除;createDesignSceneTemplate 原子分配模板与副本场景编号并提供失败补偿']],
+  ['Design / Template/GoDesign', ['partial', 'designTemplateEditorTarget 可按模板解析真实场景 GUID 与旧跳转路径;旧 /design/default 可视化编辑器资产及运行时未迁入']],
+  ['Design / Template/TlpList', ['implemented', 'designTemplates 提供帐套隔离、名称搜索、classId 筛选和正常模板分页']],
+  ['Design / Template/TlpListRecycle', ['implemented', 'Angular 模板页可切换回收站,designTemplates 严格筛选 ZStatus=-2']],
+  ['Design / Template/TemlateAdd', ['implemented', '已由 Angular 可视化模板新建/编辑抽屉替代,并明确保留丢失分类的原始 classId']],
+  ['Design / Template/TemlateAdd_Submit', ['implemented', 'saveDesignTemplate 覆盖旧表单字段;新增时原子创建模板与空模板场景并提供失败补偿']],
+  ['Design / Template/Temlate_API', ['implemented', 'designTemplateBatch 覆盖回收、恢复和彻底删除,并在永久删除时清理关联模板场景']],
   ['User / Role/UserRole', ['implemented', '已由 roles 用户角色列表覆盖帐套隔离、搜索和分页']],
   ['User / Role/UserRoleAdd', ['implemented', '已由 Angular 用户角色新建/编辑抽屉替代']],
   ['User / Role/UserRoleAdd_Submit', ['implemented', 'saveRole 已覆盖用户角色名称防重、原子旧编号和白名单保存']],

Разница между файлами не показана из-за своего большого размера
+ 6 - 1
scripts/smoke-admin-functions.mjs


+ 1 - 0
src/app/admin/admin.constants.ts

@@ -41,6 +41,7 @@ export const ADMIN_NAVIGATION = [
   { label: '字体图形分类', icon: 'tags', route: '/admin/resources/FontPicShapeType' },
   { label: '可视化设计资源', icon: 'image', route: '/admin/resources/DesignRes' },
   { label: '可视化场景', icon: 'panels-top-left', route: '/admin/resources/DesignScence' },
+  { label: '可视化模板', icon: 'layout-template', route: '/admin/resources/DesignTlp' },
   { label: '系统角色', icon: 'shield-check', route: '/admin/resources/Role' },
   { label: '问卷调查', icon: 'clipboard-list', route: '/admin/resources/DesignAsk' },
   { label: '问卷题目', icon: 'list-todo', route: '/admin/resources/DesignQuestion' },

+ 12 - 12
src/app/admin/legacy-admin-coverage.generated.ts

@@ -6299,43 +6299,43 @@ export const LEGACY_ADMIN_COVERAGE: readonly LegacyAdminCoverageEntry[] = [
     "module": "Design / Template",
     "action": "GoDesign",
     "occurrence": 1,
-    "status": "pending",
-    "reason": "尚未逐项迁移或完成等价性核验"
+    "status": "partial",
+    "reason": "designTemplateEditorTarget 可按模板解析真实场景 GUID 与旧跳转路径;旧 /design/default 可视化编辑器资产及运行时未迁入"
   },
   {
     "module": "Design / Template",
     "action": "TlpList",
     "occurrence": 1,
-    "status": "pending",
-    "reason": "尚未逐项迁移或完成等价性核验"
+    "status": "implemented",
+    "reason": "designTemplates 提供帐套隔离、名称搜索、classId 筛选和正常模板分页"
   },
   {
     "module": "Design / Template",
     "action": "TlpListRecycle",
     "occurrence": 1,
-    "status": "pending",
-    "reason": "尚未逐项迁移或完成等价性核验"
+    "status": "implemented",
+    "reason": "Angular 模板页可切换回收站,designTemplates 严格筛选 ZStatus=-2"
   },
   {
     "module": "Design / Template",
     "action": "TemlateAdd",
     "occurrence": 1,
-    "status": "pending",
-    "reason": "尚未逐项迁移或完成等价性核验"
+    "status": "implemented",
+    "reason": "已由 Angular 可视化模板新建/编辑抽屉替代,并明确保留丢失分类的原始 classId"
   },
   {
     "module": "Design / Template",
     "action": "TemlateAdd_Submit",
     "occurrence": 1,
-    "status": "pending",
-    "reason": "尚未逐项迁移或完成等价性核验"
+    "status": "implemented",
+    "reason": "saveDesignTemplate 覆盖旧表单字段;新增时原子创建模板与空模板场景并提供失败补偿"
   },
   {
     "module": "Design / Template",
     "action": "Temlate_API",
     "occurrence": 1,
-    "status": "pending",
-    "reason": "尚未逐项迁移或完成等价性核验"
+    "status": "implemented",
+    "reason": "designTemplateBatch 覆盖回收、恢复和彻底删除,并在永久删除时清理关联模板场景"
   },
   {
     "module": "User",

+ 11 - 1
src/app/admin/pages/admin-resource.component.html

@@ -26,6 +26,9 @@
   @if (className() === 'DesignScence') {
     <div class="bulk-toolbar"><strong>场景范围</strong><select [ngModel]="filterDesignSceneStatus()" (ngModelChange)="filterDesignSceneStatus.set(+$event); load(1)"><option [ngValue]="-100">正常场景</option><option [ngValue]="-2">回收站</option></select></div>
   }
+  @if (className() === 'DesignTlp') {
+    <div class="bulk-toolbar"><strong>模板范围</strong><select [ngModel]="filterDesignTemplateStatus()" (ngModelChange)="filterDesignTemplateStatus.set(+$event); load(1)"><option [ngValue]="-100">正常模板</option><option [ngValue]="-2">回收站</option></select><input class="bulk-node" type="number" min="-100" [ngModel]="filterDesignTemplateClassId()" (ngModelChange)="filterDesignTemplateClassId.set(+$event)" placeholder="分类 ID;-100 为全部" /><button type="button" (click)="load(1)">筛选</button></div>
+  }
   @if (className() === 'Role') {
     <div class="bulk-toolbar"><strong>角色类型</strong><select [ngModel]="filterRoleType()" (ngModelChange)="filterRoleType.set($event); load(1)"><option value="admin">管理员角色</option><option value="user">用户角色</option></select></div>
   }
@@ -91,6 +94,9 @@
       } @else if (className() === 'DesignScence') {
         @if (filterDesignSceneStatus() === -2) { <button type="button" [disabled]="updatingDesignScene()" (click)="applyBulkDesignSceneAction('restore')">恢复场景</button><button class="danger-action" type="button" [disabled]="updatingDesignScene()" (click)="applyBulkDesignSceneAction('delete')">彻底删除</button> }
         @else { <button class="danger-action" type="button" [disabled]="updatingDesignScene()" (click)="applyBulkDesignSceneAction('recycle')">移入回收站</button> }
+      } @else if (className() === 'DesignTlp') {
+        @if (filterDesignTemplateStatus() === -2) { <button type="button" [disabled]="updatingDesignTemplate()" (click)="applyBulkDesignTemplateAction('restore')">恢复模板</button><button class="danger-action" type="button" [disabled]="updatingDesignTemplate()" (click)="applyBulkDesignTemplateAction('delete')">彻底删除</button> }
+        @else { <button class="danger-action" type="button" [disabled]="updatingDesignTemplate()" (click)="applyBulkDesignTemplateAction('recycle')">移入回收站</button> }
       } @else if (className() === 'Role') {
         <button class="danger-action" type="button" [disabled]="savingRoleAuthorization()" (click)="applyBulkRoleDelete()">删除角色</button>
       } @else if (className() === 'DesignAsk') {
@@ -133,7 +139,7 @@
   } @else {
     <div class="table-scroll"><table><thead><tr>@if (bulkEnabled()) { <th class="select-col"><input type="checkbox" aria-label="全选当前页" [checked]="allPageSelected()" (change)="togglePageSelection($any($event.target).checked)" /></th> }@for (field of columns(); track field.name) { <th>{{ field.name }}</th> }<th class="actions">操作</th></tr></thead><tbody>
       @for (row of page()?.results || []; track row['objectId']) {
-        <tr>@if (bulkEnabled()) { <td class="select-col"><input type="checkbox" [attr.aria-label]="'选择 ' + row['objectId']" [checked]="isSelected(row['objectId'])" (change)="toggleSelection('' + row['objectId'], $any($event.target).checked)" /></td> }@for (field of columns(); track field.name) { <td [title]="display(row[field.name])">{{ display(row[field.name]) }}</td> }<td class="actions"><button type="button" [attr.aria-label]="schema()?.writable ? '编辑' : '查看'" (click)="openEdit(row)"><lucide-icon [img]="schema()?.writable ? icons.Pencil : icons.Eye" [size]="16" /></button>@if (schema()?.writable && !['Model', 'ModelField', 'StoreApplication', 'ContentTagKey'].includes(className())) { <button class="danger" type="button" [attr.aria-label]="className() === 'DesignScence' && filterDesignSceneStatus() === -2 ? '彻底删除' : ['CommonModel', 'Node', 'Guestbook', 'DesignScence'].includes(className()) ? '移入回收站' : '删除'" (click)="remove(row)"><lucide-icon [img]="icons.Trash2" [size]="16" /></button> }</td></tr>
+        <tr>@if (bulkEnabled()) { <td class="select-col"><input type="checkbox" [attr.aria-label]="'选择 ' + row['objectId']" [checked]="isSelected(row['objectId'])" (change)="toggleSelection('' + row['objectId'], $any($event.target).checked)" /></td> }@for (field of columns(); track field.name) { <td [title]="display(row[field.name])">{{ display(row[field.name]) }}</td> }<td class="actions"><button type="button" [attr.aria-label]="schema()?.writable ? '编辑' : '查看'" (click)="openEdit(row)"><lucide-icon [img]="schema()?.writable ? icons.Pencil : icons.Eye" [size]="16" /></button>@if (schema()?.writable && !['Model', 'ModelField', 'StoreApplication', 'ContentTagKey'].includes(className())) { <button class="danger" type="button" [attr.aria-label]="(className() === 'DesignScence' && filterDesignSceneStatus() === -2) || (className() === 'DesignTlp' && filterDesignTemplateStatus() === -2) ? '彻底删除' : ['CommonModel', 'Node', 'Guestbook', 'DesignScence', 'DesignTlp'].includes(className()) ? '移入回收站' : '删除'" (click)="remove(row)"><lucide-icon [img]="icons.Trash2" [size]="16" /></button> }</td></tr>
       } @empty { <tr><td class="empty-cell" [attr.colspan]="columns().length + (bulkEnabled() ? 2 : 1)">没有符合条件的数据</td></tr> }
     </tbody></table></div>
     <footer class="pagination"><span>第 {{ page()?.page || 1 }} 页,共 {{ pageCount() }} 页</span><div><button type="button" [disabled]="(page()?.page || 1) <= 1 || loading()" (click)="load((page()?.page || 1) - 1)"><lucide-icon [img]="icons.ChevronLeft" [size]="17" />上一页</button><button type="button" [disabled]="(page()?.page || 1) * (page()?.pageSize || 20) >= (page()?.total || 0) || loading()" (click)="load((page()?.page || 1) + 1)">下一页<lucide-icon [img]="icons.ChevronRight" [size]="17" /></button></div></footer>
@@ -229,6 +235,10 @@
           <section class="account-create-note"><strong>普通可视化场景</strong><span>仅编辑旧 SceneAdd 允许的标题、所属用户、积分、状态、搜索标记、预览图、缩略图、说明和 Meta;页面、组件、资源 JSON、路径、旧编号和模板关系保持只读。</span><code>场景 ID {{ draft()['id'] }} · 用户 {{ draft()['userName'] || '—' }}({{ draft()['userId'] || '—' }})</code></section>
           @if (draftId()) { <section class="content-controls"><header><div><strong>复制为模板</strong><span>完整复制现有布局与组件数据,并原子分配新的模板 ID 和模板场景 ID;失败时自动清理半成品。</span></div></header><button type="button" [disabled]="updatingDesignScene()" (click)="createDesignSceneTemplate()">{{ updatingDesignScene() ? '正在复制…' : '创建可视化模板' }}</button>@if (designSceneActionError()) { <div class="content-action-status error">{{ designSceneActionError() }}</div> }@if (designSceneActionMessage()) { <div class="content-action-status success">{{ designSceneActionMessage() }}</div> }</section> }
         }
+        @if (className() === 'DesignTlp') {
+          <section class="account-create-note"><strong>可视化模板与模板场景</strong><span>新增模板时同步创建一个空模板场景;模板编号和场景编号均由云函数原子分配。分类主表已经丢失,因此只保留并编辑原始 classId 数字,不伪造分类名称。</span>@if (draftId()) { <code>模板 ID {{ draft()['id'] }} · 场景 GUID {{ $any(draft()['designScene'])?.['guid'] || '缺失' }}</code> }</section>
+          @if (draftId()) { <section class="content-controls"><header><div><strong>旧可视化设计入口</strong><span>可定位模板场景 GUID;旧 /design/default 编辑器资产和运行时未迁入,当前不能安全打开。</span></div></header><button type="button" [disabled]="updatingDesignTemplate()" (click)="inspectDesignTemplateEditorTarget()">{{ updatingDesignTemplate() ? '正在定位…' : '检查设计入口' }}</button>@if (designTemplateActionError()) { <div class="content-action-status error">{{ designTemplateActionError() }}</div> }@if (designTemplateActionMessage()) { <div class="content-action-status">{{ designTemplateActionMessage() }}</div> }</section> }
+        }
         @if (className() === 'Role') {
           <section class="account-create-note"><strong>{{ (draft()['ztype'] || filterRoleType()) === 'user' ? '用户角色' : '管理员角色' }}</strong><span>角色编号、类型、状态和创建人由云函数维护;类型创建后不可迁移。旧 B_ARoleAuth 权限校验在交付程序中固定返回 true,下方完整保留旧权限码,但不用它绕过新云函数的管理员校验。</span>@if (draftId()) { <code>角色 ID {{ draft()['roleId'] }} · {{ draft()['ztype'] }}</code> }</section>
           @if (draftId()) {

+ 49 - 0
src/app/admin/pages/admin-resource.component.spec.ts

@@ -728,6 +728,55 @@ describe('AdminResourceComponent', () => {
     expect(component.designSceneActionMessage()).toContain('副本场景 ID 10');
   });
 
+  it('loads visual templates through status and retained class-id filters', async () => {
+    component.className.set('DesignTlp');
+    component.schema.set({ className: 'DesignTlp', label: '可视化模板', writable: true, creatable: true, supportsSoftDelete: false, fields: [] });
+    component.filterDesignTemplateStatus.set(-2); component.filterDesignTemplateClassId.set(6); component.search.set('首页');
+    functions.admin.and.resolveTo({ className: 'DesignTlp', page: 2, pageSize: 20, total: 2, results: [] });
+
+    await component.load(2);
+
+    expect(functions.admin.calls.first().args).toEqual(['designTemplates', { className: 'DesignTlp', page: 2, pageSize: 20, search: '首页', status: -2, classId: 6 }]);
+  });
+
+  it('loads and saves visual-template details through dedicated operations', async () => {
+    component.className.set('DesignTlp');
+    component.schema.set({ className: 'DesignTlp', label: '可视化模板', writable: true, creatable: true, supportsSoftDelete: false, fields: [] });
+    functions.admin.and.resolveTo({ objectId: 'template-object', id: 3, tlpName: '首页模板', classId: 6, designScene: { guid: 'scene-guid' } });
+    await component.openEdit({ objectId: 'template-object' });
+    expect(functions.admin).toHaveBeenCalledWith('designTemplate', { className: 'DesignTlp', objectId: 'template-object' });
+
+    functions.admin.calls.reset(); component.draft.set({ objectId: 'template-object', id: 3, tlpName: '首页模板', classId: 6, designScene: { guid: 'scene-guid' } });
+    functions.admin.and.callFake(async (operation: string) => operation === 'saveDesignTemplate'
+      ? { objectId: 'template-object', id: 3 }
+      : { className: 'DesignTlp', page: 1, pageSize: 20, total: 1, results: [] });
+    await component.save();
+    expect(functions.admin.calls.first().args).toEqual(['saveDesignTemplate', { className: 'DesignTlp', objectId: 'template-object', fields: { objectId: 'template-object', id: 3, tlpName: '首页模板', classId: 6, designScene: { guid: 'scene-guid' } } }]);
+  });
+
+  it('resolves the old visual-template editor target without pretending the editor exists', async () => {
+    component.className.set('DesignTlp'); component.draftId.set('template-object');
+    functions.admin.and.resolveTo({ guid: 'scene-guid', legacyPath: '/design/default?id=scene-guid', available: false, reason: '旧可视化设计器未迁入' });
+
+    await component.inspectDesignTemplateEditorTarget();
+
+    expect(functions.admin).toHaveBeenCalledWith('designTemplateEditorTarget', { className: 'DesignTlp', objectId: 'template-object' });
+    expect(component.designTemplateActionMessage()).toContain('scene-guid');
+    expect(component.designTemplateActionMessage()).toContain('当前不可打开');
+  });
+
+  it('permanently deletes recycled templates and their linked scenes', async () => {
+    component.className.set('DesignTlp'); component.filterDesignTemplateStatus.set(-2); component.selectedIds.set(['template-a']); spyOn(window, 'confirm').and.returnValue(true);
+    functions.admin.and.callFake(async (operation: string) => operation === 'designTemplateBatch'
+      ? { action: 'delete', updated: 1, deletedScenes: 1 }
+      : { className: 'DesignTlp', page: 1, pageSize: 20, total: 0, results: [] });
+
+    await component.applyBulkDesignTemplateAction('delete');
+
+    expect(functions.admin.calls.first().args).toEqual(['designTemplateBatch', { className: 'DesignTlp', action: 'delete', objectIds: ['template-a'] }]);
+    expect(component.bulkMessage()).toContain('1 个关联场景');
+  });
+
   it('loads legacy roles through the dedicated role-type filter', async () => {
     component.className.set('Role');
     component.schema.set({ className: 'Role', label: '系统角色', writable: true, creatable: true, supportsSoftDelete: false, fields: [] });

+ 33 - 6
src/app/admin/pages/admin-resource.component.ts

@@ -134,6 +134,11 @@ export class AdminResourceComponent implements OnInit {
   readonly updatingDesignScene = signal(false);
   readonly designSceneActionError = signal('');
   readonly designSceneActionMessage = signal('');
+  readonly filterDesignTemplateStatus = signal(-100);
+  readonly filterDesignTemplateClassId = signal(-100);
+  readonly updatingDesignTemplate = signal(false);
+  readonly designTemplateActionError = signal('');
+  readonly designTemplateActionMessage = signal('');
   readonly filterRoleType = signal<'admin' | 'user'>('admin');
   readonly roleAuthorization = signal<Record<string, string>>({});
   readonly savingRoleAuthorization = signal(false);
@@ -195,7 +200,7 @@ export class AdminResourceComponent implements OnInit {
     return fields.map((field, index) => ({ field, index })).sort((a, b) => rank(a.field.name) - rank(b.field.name) || a.index - b.index).map(({ field }) => field).slice(0, 7);
   });
   readonly pageCount = computed(() => Math.max(1, Math.ceil((this.page()?.total ?? 0) / (this.page()?.pageSize || 20))));
-  readonly bulkEnabled = computed(() => ['_User', 'CommonModel', 'Node', 'Special', 'Guestbook', 'GuestBar', 'Datadiccategory', 'Datadic', 'GradeCate', 'Grade', 'Currency', 'SysHoliday', 'Search', 'Role', 'AdZone', 'AdInfo', 'FontPicShape', 'FontPicShapeType', 'DesignAsk', 'DesignQuestion', 'DesignAnswer', 'DesignRes', 'DesignScence', 'ServiceSeat', 'Temp', 'StoreApplication', 'StoreStyle', 'UserLevel', 'Baike', 'CRMSAttr', 'ShopFareTlp', 'MisType', 'PageStyle', 'PlatComp'].includes(this.className()));
+  readonly bulkEnabled = computed(() => ['_User', 'CommonModel', 'Node', 'Special', 'Guestbook', 'GuestBar', 'Datadiccategory', 'Datadic', 'GradeCate', 'Grade', 'Currency', 'SysHoliday', 'Search', 'Role', 'AdZone', 'AdInfo', 'FontPicShape', 'FontPicShapeType', 'DesignAsk', 'DesignQuestion', 'DesignAnswer', 'DesignRes', 'DesignScence', 'DesignTlp', 'ServiceSeat', 'Temp', 'StoreApplication', 'StoreStyle', 'UserLevel', 'Baike', 'CRMSAttr', 'ShopFareTlp', 'MisType', 'PageStyle', 'PlatComp'].includes(this.className()));
   readonly allPageSelected = computed(() => {
     const ids = (this.page()?.results || []).map((row) => String(row['objectId'] || '')).filter(Boolean);
     return Boolean(ids.length) && ids.every((id) => this.selectedIds().includes(id));
@@ -214,6 +219,7 @@ export class AdminResourceComponent implements OnInit {
       this.filterFontShapeTypeId.set(0); this.resetFontShapeActions();
       this.filterDesignResourceType.set('');
       this.filterDesignSceneStatus.set(-100); this.resetDesignSceneActions();
+      this.filterDesignTemplateStatus.set(-100); this.filterDesignTemplateClassId.set(-100); this.resetDesignTemplateActions();
       this.filterRoleType.set('admin'); this.resetRoleActions();
       this.filterSurveyStatus.set(-100); this.filterSurveyId.set(0); this.resetSurveyActions();
       this.resetServiceActions();
@@ -236,7 +242,7 @@ export class AdminResourceComponent implements OnInit {
       if (this.className() === 'FontPicShape' && reloadSchema) await this.loadFontShapeTypes();
       if (['DesignQuestion', 'DesignAnswer'].includes(this.className()) && reloadSchema) { await this.loadSurveys(); if (!this.filterSurveyId() && this.surveys().length) this.filterSurveyId.set(this.surveyIdOf(this.surveys()[0])); }
       if (this.className() === 'StoreApplication' && reloadSchema) await this.loadStoreStyles();
-      const pageOperation = this.className() === 'Grade' && this.filterGradeCategoryId() > 0 ? 'gradeOptions' : this.className() === 'Search' ? 'searchNavigations' : this.className() === 'Role' ? 'roles' : this.className() === 'AdZone' ? 'adZones' : this.className() === 'AdInfo' ? 'adInfos' : this.className() === 'FontPicShape' ? 'fontShapes' : this.className() === 'FontPicShapeType' ? 'fontShapeTypes' : this.className() === 'DesignRes' ? 'designResources' : this.className() === 'DesignScence' ? 'designScenes' : this.className() === 'DesignAsk' ? 'surveys' : this.className() === 'DesignQuestion' ? 'surveyQuestions' : this.className() === 'DesignAnswer' ? 'surveyResults' : this.className() === 'ServiceSeat' ? 'serviceSeats' : this.className() === 'Temp' ? 'serviceCodes' : this.className() === 'StoreApplication' ? 'storeApplications' : this.className() === 'StoreStyle' ? 'storeStyles' : this.className() === 'ContentTagKey' ? 'contentTagKeys' : this.className() === 'UserLevel' ? 'userLevels' : this.className() === 'UserMoneyLog' ? 'userMoneyLogs' : this.className() === 'UserPromotion' ? 'userPromotions' : this.className() === 'Baike' ? 'baikeEntries' : this.className() === 'CRMSAttr' ? 'crmClientTypes' : this.className() === 'ShopFareTlp' ? 'shopFareTemplates' : this.className() === 'SysLog' ? 'systemLogs' : this.className() === 'MisType' ? 'misTypes' : this.className() === 'PageStyle' ? 'pageStyles' : this.className() === 'PlatComp' ? 'platformCompanies' : 'list';
+      const pageOperation = this.className() === 'Grade' && this.filterGradeCategoryId() > 0 ? 'gradeOptions' : this.className() === 'Search' ? 'searchNavigations' : this.className() === 'Role' ? 'roles' : this.className() === 'AdZone' ? 'adZones' : this.className() === 'AdInfo' ? 'adInfos' : this.className() === 'FontPicShape' ? 'fontShapes' : this.className() === 'FontPicShapeType' ? 'fontShapeTypes' : this.className() === 'DesignRes' ? 'designResources' : this.className() === 'DesignScence' ? 'designScenes' : this.className() === 'DesignTlp' ? 'designTemplates' : this.className() === 'DesignAsk' ? 'surveys' : this.className() === 'DesignQuestion' ? 'surveyQuestions' : this.className() === 'DesignAnswer' ? 'surveyResults' : this.className() === 'ServiceSeat' ? 'serviceSeats' : this.className() === 'Temp' ? 'serviceCodes' : this.className() === 'StoreApplication' ? 'storeApplications' : this.className() === 'StoreStyle' ? 'storeStyles' : this.className() === 'ContentTagKey' ? 'contentTagKeys' : this.className() === 'UserLevel' ? 'userLevels' : this.className() === 'UserMoneyLog' ? 'userMoneyLogs' : this.className() === 'UserPromotion' ? 'userPromotions' : this.className() === 'Baike' ? 'baikeEntries' : this.className() === 'CRMSAttr' ? 'crmClientTypes' : this.className() === 'ShopFareTlp' ? 'shopFareTemplates' : this.className() === 'SysLog' ? 'systemLogs' : this.className() === 'MisType' ? 'misTypes' : this.className() === 'PageStyle' ? 'pageStyles' : this.className() === 'PlatComp' ? 'platformCompanies' : 'list';
       const pagePayload: Record<string, unknown> = { className: this.className(), page: pageNumber, pageSize: 20, search: this.search().trim() };
       if (pageOperation === 'gradeOptions') { pagePayload['categoryId'] = this.filterGradeCategoryId(); pagePayload['parentId'] = this.filterGradeParentId(); }
       if (pageOperation === 'searchNavigations') { pagePayload['type'] = this.filterSearchNavigationType(); pagePayload['state'] = this.filterSearchNavigationState(); pagePayload['elite'] = this.filterSearchNavigationElite(); }
@@ -245,6 +251,7 @@ export class AdminResourceComponent implements OnInit {
       if (pageOperation === 'fontShapes') pagePayload['typeId'] = this.filterFontShapeTypeId();
       if (pageOperation === 'designResources') pagePayload['type'] = this.filterDesignResourceType().trim();
       if (pageOperation === 'designScenes') pagePayload['status'] = this.filterDesignSceneStatus();
+      if (pageOperation === 'designTemplates') { pagePayload['status'] = this.filterDesignTemplateStatus(); pagePayload['classId'] = this.filterDesignTemplateClassId(); }
       if (pageOperation === 'roles') pagePayload['type'] = this.filterRoleType();
       if (pageOperation === 'surveys') pagePayload['status'] = this.filterSurveyStatus();
       if (pageOperation === 'surveyQuestions' || pageOperation === 'surveyResults') pagePayload['askId'] = this.filterSurveyId();
@@ -260,14 +267,14 @@ export class AdminResourceComponent implements OnInit {
     finally { this.loading.set(false); }
   }
 
-  openCreate(): void { this.draftId.set(''); this.draft.set({}); this.fieldErrors.set({}); this.fieldInputs.set({}); this.resetPasswordFields(); this.resetCreateUserFields(); this.resetUserActions(); this.resetContentActions(); this.resetNodeActions(); this.resetSpecialActions(); this.resetGuestbookActions(); this.resetGuestCategoryActions(); this.resetBarActions(); this.resetExamClassActions(); this.resetExamPointActions(); this.resetKnowledgeActions(); this.resetTeacherActions(); this.resetDictionaryActions(); this.resetGradeActions(); this.resetAdActions(); this.resetFontShapeActions(); this.resetDesignSceneActions(); this.resetRoleActions(); this.resetSurveyActions(); this.resetServiceActions(); this.resetStoreActions(); this.resetTagKeyActions(); this.resetPlatformCompanyActions(); this.editorOpen.set(true); }
+  openCreate(): void { this.draftId.set(''); this.draft.set({}); this.fieldErrors.set({}); this.fieldInputs.set({}); this.resetPasswordFields(); this.resetCreateUserFields(); this.resetUserActions(); this.resetContentActions(); this.resetNodeActions(); this.resetSpecialActions(); this.resetGuestbookActions(); this.resetGuestCategoryActions(); this.resetBarActions(); this.resetExamClassActions(); this.resetExamPointActions(); this.resetKnowledgeActions(); this.resetTeacherActions(); this.resetDictionaryActions(); this.resetGradeActions(); this.resetAdActions(); this.resetFontShapeActions(); this.resetDesignSceneActions(); this.resetDesignTemplateActions(); this.resetRoleActions(); this.resetSurveyActions(); this.resetServiceActions(); this.resetStoreActions(); this.resetTagKeyActions(); this.resetPlatformCompanyActions(); this.editorOpen.set(true); }
   async openEdit(row: Record<string, unknown>): Promise<void> {
     const objectId = String(row['objectId'] ?? '');
     this.error.set('');
     try {
-      const detailOperation = this.className() === 'ContentTagKey' ? 'getContentTagKeys' : this.className() === 'UserMoneyLog' ? 'getUserMoneyLog' : this.className() === 'UserPromotion' ? 'getUserPromotion' : this.className() === 'Role' ? 'roleAuthorization' : 'get';
+      const detailOperation = this.className() === 'ContentTagKey' ? 'getContentTagKeys' : this.className() === 'UserMoneyLog' ? 'getUserMoneyLog' : this.className() === 'UserPromotion' ? 'getUserPromotion' : this.className() === 'Role' ? 'roleAuthorization' : this.className() === 'DesignTlp' ? 'designTemplate' : 'get';
       const detail = await this.functions.admin<Record<string, unknown>>(detailOperation, { className: this.className(), objectId });
-      this.draftId.set(objectId); this.draft.set(detail); this.fieldErrors.set({}); this.fieldInputs.set({}); this.resetPasswordFields(); this.resetCreateUserFields(); this.resetUserActions(detail); this.resetContentActions(detail); this.resetNodeActions(detail); this.resetSpecialActions(detail); this.resetGuestbookActions(detail); this.resetGuestCategoryActions(detail); this.resetBarActions(detail); this.resetExamClassActions(detail); this.resetExamPointActions(detail); this.resetKnowledgeActions(detail); this.resetTeacherActions(detail); this.resetDictionaryActions(detail); this.resetGradeActions(detail); this.resetAdActions(detail); this.resetFontShapeActions(detail); this.resetDesignSceneActions(); this.resetRoleActions(detail); this.resetSurveyActions(); this.resetServiceActions(detail); this.resetStoreActions(detail); this.resetTagKeyActions(detail); this.resetPlatformCompanyActions(detail); this.editorOpen.set(true);
+      this.draftId.set(objectId); this.draft.set(detail); this.fieldErrors.set({}); this.fieldInputs.set({}); this.resetPasswordFields(); this.resetCreateUserFields(); this.resetUserActions(detail); this.resetContentActions(detail); this.resetNodeActions(detail); this.resetSpecialActions(detail); this.resetGuestbookActions(detail); this.resetGuestCategoryActions(detail); this.resetBarActions(detail); this.resetExamClassActions(detail); this.resetExamPointActions(detail); this.resetKnowledgeActions(detail); this.resetTeacherActions(detail); this.resetDictionaryActions(detail); this.resetGradeActions(detail); this.resetAdActions(detail); this.resetFontShapeActions(detail); this.resetDesignSceneActions(); this.resetDesignTemplateActions(); this.resetRoleActions(detail); this.resetSurveyActions(); this.resetServiceActions(detail); this.resetStoreActions(detail); this.resetTagKeyActions(detail); this.resetPlatformCompanyActions(detail); this.editorOpen.set(true);
       if (this.className() === '_User') await this.loadUserGroups();
       if (this.className() === 'AdInfo' && !this.adZones().length) await this.loadAdZones();
       if (this.className() === 'AdZone') await this.loadAdPreview();
@@ -330,6 +337,7 @@ export class AdminResourceComponent implements OnInit {
                                                 : this.className() === 'FontPicShapeType' ? 'saveFontShapeType'
                                                   : this.className() === 'DesignRes' ? 'saveDesignResource'
                                                     : this.className() === 'DesignScence' ? 'saveDesignScene'
+                                                      : this.className() === 'DesignTlp' ? 'saveDesignTemplate'
                                                     : this.className() === 'Role' ? 'saveRole'
                                                   : this.className() === 'DesignAsk' ? 'saveSurvey'
                                                     : this.className() === 'DesignQuestion' ? 'saveSurveyQuestion'
@@ -772,6 +780,23 @@ export class AdminResourceComponent implements OnInit {
     } catch (error) { this.designSceneActionError.set(error instanceof Error ? error.message : '场景复制为模板失败'); }
     finally { this.updatingDesignScene.set(false); }
   }
+  async applyBulkDesignTemplateAction(action: 'recycle' | 'restore' | 'delete'): Promise<void> {
+    const objectIds = this.selectedIds(); this.bulkError.set(''); this.bulkMessage.set('');
+    if (this.className() !== 'DesignTlp' || !objectIds.length) { this.bulkError.set('请先选择可视化模板'); return; }
+    if ((action === 'recycle' || action === 'delete') && !confirm(action === 'delete' ? `确认彻底删除选中的 ${objectIds.length} 个模板及其模板场景?此操作不可恢复。` : `确认将选中的 ${objectIds.length} 个模板移入回收站?`)) return;
+    this.updatingDesignTemplate.set(true);
+    try { const result = await this.functions.admin<{ updated: number; deletedScenes?: number }>('designTemplateBatch', { className: 'DesignTlp', action, objectIds }); await this.load(); this.bulkMessage.set(action === 'recycle' ? `已回收 ${result.updated} 个模板` : action === 'restore' ? `已恢复 ${result.updated} 个模板` : `已彻底删除 ${result.updated} 个模板及 ${result.deletedScenes || 0} 个关联场景`); }
+    catch (error) { this.bulkError.set(error instanceof Error ? error.message : '模板批量操作失败'); }
+    finally { this.updatingDesignTemplate.set(false); }
+  }
+  async inspectDesignTemplateEditorTarget(): Promise<void> {
+    this.designTemplateActionError.set(''); this.designTemplateActionMessage.set('');
+    if (this.className() !== 'DesignTlp' || !this.draftId()) { this.designTemplateActionError.set('请先保存并打开现有模板'); return; }
+    this.updatingDesignTemplate.set(true);
+    try { const result = await this.functions.admin<{ guid: string; legacyPath: string; reason: string }>('designTemplateEditorTarget', { className: 'DesignTlp', objectId: this.draftId() }); this.designTemplateActionMessage.set(`已定位模板场景 ${result.guid};旧入口 ${result.legacyPath} 当前不可打开:${result.reason}`); }
+    catch (error) { this.designTemplateActionError.set(error instanceof Error ? error.message : '模板设计入口定位失败'); }
+    finally { this.updatingDesignTemplate.set(false); }
+  }
   setRoleAuthorizationField(name: string, value: string): void {
     this.roleAuthorization.update((current) => ({ ...current, [name]: value }));
   }
@@ -923,7 +948,7 @@ export class AdminResourceComponent implements OnInit {
   }
   async remove(row: Record<string, unknown>): Promise<void> {
     const objectId = String(row['objectId'] ?? '');
-    const verb = this.className() === 'DesignScence' && this.filterDesignSceneStatus() === -2 ? '彻底删除' : ['CommonModel', 'Node', 'Guestbook', 'DesignScence'].includes(this.className()) ? '移入回收站' : '删除';
+    const verb = (this.className() === 'DesignScence' && this.filterDesignSceneStatus() === -2) || (this.className() === 'DesignTlp' && this.filterDesignTemplateStatus() === -2) ? '彻底删除' : ['CommonModel', 'Node', 'Guestbook', 'DesignScence', 'DesignTlp'].includes(this.className()) ? '移入回收站' : '删除';
     if (!objectId || !confirm(`确认${verb} ${this.className()} / ${objectId}?`)) return;
     try {
       if (this.className() === 'Search') await this.functions.admin('searchNavigationBatch', { className: 'Search', action: 'delete', objectIds: [objectId] });
@@ -933,6 +958,7 @@ export class AdminResourceComponent implements OnInit {
       else if (this.className() === 'FontPicShapeType') await this.functions.admin('fontShapeTypeBatch', { className: 'FontPicShapeType', action: 'delete', objectIds: [objectId] });
       else if (this.className() === 'DesignRes') await this.functions.admin('designResourceBatch', { className: 'DesignRes', action: 'delete', objectIds: [objectId] });
       else if (this.className() === 'DesignScence') await this.functions.admin('designSceneBatch', { className: 'DesignScence', action: this.filterDesignSceneStatus() === -2 ? 'delete' : 'recycle', objectIds: [objectId] });
+      else if (this.className() === 'DesignTlp') await this.functions.admin('designTemplateBatch', { className: 'DesignTlp', action: this.filterDesignTemplateStatus() === -2 ? 'delete' : 'recycle', objectIds: [objectId] });
       else if (this.className() === 'Role') await this.functions.admin('roleBatch', { className: 'Role', action: 'delete', objectIds: [objectId] });
       else if (['DesignAsk', 'DesignQuestion', 'DesignAnswer'].includes(this.className())) await this.functions.admin('surveyBatch', { className: this.className(), action: 'delete', objectIds: [objectId] });
       else if (['ServiceSeat', 'Temp'].includes(this.className())) await this.functions.admin('serviceBatch', { className: this.className(), action: 'delete', objectIds: [objectId] });
@@ -1021,6 +1047,7 @@ export class AdminResourceComponent implements OnInit {
   private resetAdActions(detail: Record<string, unknown> = {}): void { this.targetAdZoneId.set(String(detail['zoneId'] || this.filterAdInfoZoneId() || '')); this.adPreview.set([]); this.adPreviewError.set(''); this.adPreviewLoading.set(false); }
   private resetFontShapeActions(detail: Record<string, unknown> = {}): void { this.targetFontShapeTypeId.set(Number(detail['typeId']) || this.filterFontShapeTypeId()); this.fontShapePreview.set(String(detail['shape'] || '')); }
   private resetDesignSceneActions(): void { this.designSceneActionError.set(''); this.designSceneActionMessage.set(''); this.updatingDesignScene.set(false); }
+  private resetDesignTemplateActions(): void { this.designTemplateActionError.set(''); this.designTemplateActionMessage.set(''); this.updatingDesignTemplate.set(false); }
   private resetRoleActions(detail: Record<string, unknown> = {}): void { const authorization = detail['authorization'] && typeof detail['authorization'] === 'object' ? detail['authorization'] as Record<string, unknown> : {}; this.roleAuthorization.set(Object.fromEntries(this.roleAuthorizationFields.map(([name]) => [name, String(authorization[name] || '')]))); this.roleAuthorizationError.set(''); this.roleAuthorizationMessage.set(''); this.savingRoleAuthorization.set(false); }
   private resetSurveyActions(): void { this.surveyOrderStart.set(1); this.surveyChart.set(null); this.surveyChartError.set(''); this.surveyChartLoading.set(false); }
   private resetServiceActions(detail: Record<string, unknown> = {}): void { this.targetServiceSeatUsername.set(String(detail['sRemrk'] || '')); }

Некоторые файлы не были показаны из-за большого количества измененных файлов