@qingflow-tech/qingflow-cli 1.1.61 → 1.1.62-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +3 -3
  2. package/package.json +2 -1
  3. package/pyproject.toml +4 -1
  4. package/skills/qingflow-cli/SKILL.md +112 -3
  5. package/skills/qingflow-cli/reference/QINGFLOW_CLI_BUILDER_CHARTS_WORKFLOW.md +1 -1
  6. package/skills/qingflow-cli/reference/QINGFLOW_CLI_BUILDER_PORTAL_WORKFLOW.md +6 -258
  7. package/skills/qingflow-cli/reference/builder/20-build-complete-system.md +2 -2
  8. package/skills/qingflow-cli/reference/builder/30-schema-fields.md +22 -5
  9. package/skills/qingflow-cli/reference/builder/70-portal.md +111 -36
  10. package/skills/qingflow-cli/reference/builder/reference/app-delivery-sop.md +3 -3
  11. package/skills/qingflow-cli/reference/examples/portal/portal_apply_v1alpha1.example.json +100 -0
  12. package/skills/qingflow-cli/reference/examples/portal/portal_sections_all_types.example.json +22 -6
  13. package/src/qingflow_mcp/app_form_compat.py +3 -0
  14. package/src/qingflow_mcp/app_form_validator.py +89 -20
  15. package/src/qingflow_mcp/builder_facade/app_form.py +629 -112
  16. package/src/qingflow_mcp/builder_facade/models.py +213 -15
  17. package/src/qingflow_mcp/builder_facade/portals_schema.py +397 -0
  18. package/src/qingflow_mcp/builder_facade/schemas/app_form/manifest.json +15 -1
  19. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/complete.json +112 -38
  20. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/address.json +31 -8
  21. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_content_classification.json +146 -0
  22. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_content_extraction.json +146 -0
  23. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_content_generation.json +146 -0
  24. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_document_parsing.json +146 -0
  25. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_image_generation.json +146 -0
  26. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_image_recognition.json +146 -0
  27. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_machine_translation.json +146 -0
  28. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ai_text_summary.json +146 -0
  29. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/amount.json +6 -10
  30. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/attachment.json +33 -10
  31. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/code_block.json +6 -10
  32. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/data_relation.json +11 -18
  33. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/date.json +4 -8
  34. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/date_duration.json +146 -0
  35. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/datetime.json +4 -8
  36. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/department.json +6 -10
  37. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/email.json +4 -8
  38. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/embed_field.json +146 -0
  39. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/image_select.json +146 -0
  40. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/link.json +4 -8
  41. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/location.json +146 -0
  42. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/long_text.json +4 -8
  43. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/member.json +6 -10
  44. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/multi_select.json +4 -8
  45. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/number.json +6 -10
  46. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/ocr.json +146 -0
  47. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/phone.json +4 -8
  48. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/q_linker.json +8 -12
  49. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/relation.json +73 -15
  50. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/rich_text.json +146 -0
  51. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/single_choice.json +4 -8
  52. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/single_select.json +4 -8
  53. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/subtable.json +90 -29
  54. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/fields/text.json +4 -8
  55. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/formula.json +43 -0
  56. package/src/qingflow_mcp/builder_facade/schemas/app_form/v1alpha1/summary.json +27 -19
  57. package/src/qingflow_mcp/builder_facade/schemas/portals/manifest.json +59 -0
  58. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/complete.json +1397 -0
  59. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/carousel.json +193 -0
  60. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/chart.json +643 -0
  61. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/favourite.json +203 -0
  62. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/filter.json +331 -0
  63. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/grid.json +265 -0
  64. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/link.json +131 -0
  65. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/task.json +199 -0
  66. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/text.json +123 -0
  67. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/components/view.json +196 -0
  68. package/src/qingflow_mcp/builder_facade/schemas/portals/v1alpha1/summary.json +800 -0
  69. package/src/qingflow_mcp/builder_facade/schemas/views/v1alpha1/complete.json +1 -1
  70. package/src/qingflow_mcp/builder_facade/schemas/views/v1alpha1/details/display.json +1 -1
  71. package/src/qingflow_mcp/builder_facade/schemas/views/v1alpha1/summary.json +1 -1
  72. package/src/qingflow_mcp/builder_facade/service.py +1367 -92
  73. package/src/qingflow_mcp/cli/commands/builder.py +120 -5
  74. package/src/qingflow_mcp/cli/formatters.py +11 -0
  75. package/src/qingflow_mcp/cli/main.py +90 -2
  76. package/src/qingflow_mcp/cli/permission_gate.py +59 -0
  77. package/src/qingflow_mcp/cloud_context.py +16 -1
  78. package/src/qingflow_mcp/entity_permissions.py +10 -0
  79. package/src/qingflow_mcp/permission_catalog.json +1210 -0
  80. package/src/qingflow_mcp/public_surface.py +69 -8
  81. package/src/qingflow_mcp/response_trim.py +2 -1
  82. package/src/qingflow_mcp/server.py +12 -6
  83. package/src/qingflow_mcp/server_app_builder.py +43 -10
  84. package/src/qingflow_mcp/server_app_user.py +9 -5
  85. package/src/qingflow_mcp/server_cloud.py +43 -7
  86. package/src/qingflow_mcp/session_store.py +14 -1
  87. package/src/qingflow_mcp/solution/compiler/icon_utils.py +73 -0
  88. package/src/qingflow_mcp/solution/executor.py +5 -2
  89. package/src/qingflow_mcp/tool_catalog.py +388 -0
  90. package/src/qingflow_mcp/tool_catalog_i18n.py +184 -0
  91. package/src/qingflow_mcp/tool_policy.py +191 -0
  92. package/src/qingflow_mcp/tools/ai_builder_tools.py +118 -20
  93. package/src/qingflow_mcp/tools/portal_tools.py +4 -54
  94. package/src/qingflow_mcp/tools/portal_writer.py +59 -0
  95. package/src/qingflow_mcp/tools/solution_tools.py +2 -0
@@ -26,7 +26,12 @@ from ..resource_uri import validate_positive_resource_id, validate_resource_iden
26
26
  from ..solution.build_assembly_store import BuildAssemblyStore, default_artifacts, default_manifest
27
27
  from ..solution.compiler.chart_compiler import qingbi_workspace_visible_auth
28
28
  from ..solution.compiler.form_compiler import build_question, default_form_payload, default_member_auth
29
- from ..solution.compiler.icon_utils import encode_workspace_icon_with_defaults, workspace_icon_config
29
+ from ..solution.compiler.icon_utils import (
30
+ encode_workspace_icon_with_defaults,
31
+ update_workspace_icon_from_existing,
32
+ validate_workspace_icon_choice,
33
+ workspace_icon_config,
34
+ )
30
35
  from ..solution.compiler.view_compiler import VIEW_TYPE_MAP
31
36
  from ..solution.executor import _build_viewgraph_questions, _compact_dict, _flatten_viewgraph_questions, extract_field_map
32
37
  from ..solution.spec_models import FieldType, FormLayoutRowSpec, FormLayoutSectionSpec, ViewSpec
@@ -35,6 +40,7 @@ from ..tools.custom_button_tools import CustomButtonTools
35
40
  from ..tools.directory_tools import DirectoryTools
36
41
  from ..tools.package_tools import PackageTools
37
42
  from ..tools.portal_tools import PortalTools
43
+ from ..tools.portal_writer import PortalWriter
38
44
  from ..tools.qingbi_report_tools import QingbiReportTools
39
45
  from ..tools.role_tools import RoleTools
40
46
  from ..tools.solution_tools import SolutionTools
@@ -45,6 +51,7 @@ from . import workflow_spec as workflow_spec_api
45
51
  from .button_style_catalog import button_style_catalog_payload
46
52
  from ..tools.view_writer import ViewWriter
47
53
  from .views_schema import ViewsContractError, compact_none_values, views_schema_registry
54
+ from .portals_schema import PortalsContractError, PortalsSchemaContext, portals_schema_registry
48
55
  from .models import (
49
56
  AppChartsReadResponse,
50
57
  AppFieldsReadResponse,
@@ -81,6 +88,7 @@ from .models import (
81
88
  LayoutSectionPatch,
82
89
  LayoutPreset,
83
90
  PortalApplyRequest,
91
+ public_portal_apply_payload,
84
92
  PortalGetResponse,
85
93
  PortalListResponse,
86
94
  PortalReadSummaryResponse,
@@ -163,9 +171,16 @@ FIELD_TYPE_TO_QUESTION_TYPE: dict[str, int] = {
163
171
  FieldType.relation.value: 25,
164
172
  }
165
173
 
174
+ # code_block / q_linker 输出目标字段类型。后端写链无类型白名单(FormSvcImpl 原样
175
+ # 落库),运行时 DataSvcImpl.getAnswerValueByString:attachment 按拆分 URL 写入、
176
+ # subtable 整表组装(均有专门分支),rich_text/data_relation 走 Question.canImport
177
+ # 兜底按字符串写入(不报错)——四者为存量合法配置,与 validator 侧白名单同口径。
178
+ # r10 再放行 link/member(存量实证:92nl6blfk402 link×2、ab9fjvj33001 member;
179
+ # 运行时同为字符串写入路径)。
166
180
  INTEGRATION_OUTPUT_TARGET_FIELD_TYPES: tuple[str, ...] = (
167
181
  FieldType.text.value,
168
182
  FieldType.long_text.value,
183
+ "rich_text",
169
184
  FieldType.number.value,
170
185
  FieldType.amount.value,
171
186
  FieldType.date.value,
@@ -173,6 +188,11 @@ INTEGRATION_OUTPUT_TARGET_FIELD_TYPES: tuple[str, ...] = (
173
188
  FieldType.single_select.value,
174
189
  FieldType.multi_select.value,
175
190
  FieldType.boolean.value,
191
+ FieldType.attachment.value,
192
+ "data_relation",
193
+ FieldType.subtable.value,
194
+ "link",
195
+ "member",
176
196
  )
177
197
 
178
198
  MATCH_TYPE_ACCURACY = 1
@@ -183,6 +203,9 @@ JUDGE_INCLUDE = 2
183
203
  JUDGE_GREATER_OR_EQUAL = 5
184
204
  JUDGE_LESS_OR_EQUAL = 7
185
205
  JUDGE_EQUAL_ANY = 9
206
+ # 成员/部门归属判定(Constants.JUDGE_BELONG_TO):轮播筛选存量数据出现,后端公式引擎
207
+ # JUDGE_FUNCTION[13]="JUDGE_BELONG_TO" 全支持,声明侧以 belongs_to 表达保真回写。
208
+ JUDGE_BELONG_TO = 13
186
209
  JUDGE_FUZZY_MATCH = 19
187
210
  JUDGE_INCLUDE_ANY = 20
188
211
  DEFAULT_TYPE_RELATION = 2
@@ -297,6 +320,7 @@ class AiBuilderFacade:
297
320
  self._view_writer = ViewWriter(views.sessions, views.backend)
298
321
  self.workflows = workflows
299
322
  self.portals = portals
323
+ self._portal_writer = PortalWriter(portals.sessions, portals.backend)
300
324
  self.charts = charts
301
325
  self.roles = roles
302
326
  self.directory = directory
@@ -3044,6 +3068,7 @@ class AiBuilderFacade:
3044
3068
  *,
3045
3069
  profile: str,
3046
3070
  visibility: VisibilityPatch | None,
3071
+ degradation_warnings: list[dict[str, Any]] | None = None,
3047
3072
  ) -> dict[str, Any]:
3048
3073
  if visibility is None:
3049
3074
  return default_member_auth()
@@ -3077,27 +3102,116 @@ class AiBuilderFacade:
3077
3102
  member_ids=visibility.external_selectors.member_ids,
3078
3103
  member_emails=visibility.external_selectors.member_emails,
3079
3104
  )
3080
- # 冗余引用降级:提取器对同一成员同时产出 uid/email/name 三通道(uid 必有且直通解析,
3081
- # 保证成员不丢);email/name 走后端通讯录搜索,受数据/权限边界影响解析可能失败。
3082
- # 这类失败降级为非阻断——只有 uid/dept_id 直通也覆盖不了的引用才真正阻断。
3105
+ # 冗余引用降级(review §2-1 逐主体锚定校验):提取器对同一成员同时产出
3106
+ # uid/email/name 三通道(uid 必有且直通解析,保证成员不丢);email/name 走
3107
+ # 后端通讯录搜索,受数据/权限边界影响解析可能失败。降级只在「该主体已被
3108
+ # 直通锚覆盖」时成立,否则升级为阻断——关闭手写声明混用 uid 锚定 + 仅
3109
+ # email/name 引用时,主体被静默丢弃的窗口。覆盖判定按失败类别的可验证面:
3110
+ # - AMBIGUOUS_*:目录命中多候选,候选(matches)与已解析直通锚 uid/deptId/
3111
+ # roleId 求交——交非空说明歧义主体之一已被锚定,主体集合不丢;
3112
+ # - *_NOT_FOUND:目录答「不存在」,失败值与已解析条目的真实属性(email/
3113
+ # name)比对(直通 stub 条目属性是 id 字符串,不会误匹配);
3114
+ # - *_SEARCH_FAILED:目录服务本身不可达,主体身份无从验证——保留全局
3115
+ # 「直通锚非空」guard(eval 隔离环境外部登录资源不可达 → 搜索 49500
3116
+ # 超时的确定性约束;纯手写声明仍阻断),降级明细经 degradation_warnings
3117
+ # 回响应信封,不再静默。
3083
3118
  _SOFT_RESOLUTION_KINDS = {"member_email", "member_name", "department_name", "role", "external_member_email"}
3084
3119
  _NOT_FOUND_RESOLUTION_CODES = {"MEMBER_NOT_FOUND", "AMBIGUOUS_MEMBER", "ROLE_NOT_FOUND", "AMBIGUOUS_ROLE", "DEPARTMENT_NOT_FOUND", "AMBIGUOUS_DEPARTMENT"}
3085
- blocking_issues = [
3086
- issue
3087
- for issue in [
3088
- *member_resolution["issues"],
3089
- *role_resolution["issues"],
3090
- *department_resolution["issues"],
3091
- *external_member_resolution["issues"],
3092
- ]
3093
- # 冗余 email/name 引用「找不到」降级为非阻断(uid/id 直通已保主体不丢);
3094
- # 权限拒绝/查询失败类(LOOKUP_FAILED/PERMISSION_DENIED)仍阻断
3095
- if not (
3096
- str(issue.get("kind") or "") in _SOFT_RESOLUTION_KINDS
3097
- and str(issue.get("error_code") or "") in _NOT_FOUND_RESOLUTION_CODES
3098
- )
3099
- ]
3120
+ member_entries = member_resolution.get("member_entries") or []
3121
+ department_entries = department_resolution.get("department_entries") or []
3122
+ role_entries = role_resolution.get("role_entries") or []
3123
+ external_entries = external_member_resolution.get("member_entries") or []
3124
+ uid_direct_count = len(member_entries) + len(department_entries)
3125
+ resolved_anchor_ids = {
3126
+ value
3127
+ for value in (
3128
+ _coerce_positive_int(entry.get("uid"))
3129
+ for entry in [*member_entries, *external_entries]
3130
+ )
3131
+ if value is not None
3132
+ } | {
3133
+ value
3134
+ for value in (
3135
+ _coerce_positive_int(entry.get("deptId"))
3136
+ for entry in department_entries
3137
+ )
3138
+ if value is not None
3139
+ } | {
3140
+ value
3141
+ for value in (_coerce_positive_int(entry.get("roleId")) for entry in role_entries)
3142
+ if value is not None
3143
+ }
3144
+
3145
+ def _match_anchor_ids(issue: dict[str, Any]) -> set[int]:
3146
+ matched: set[int] = set()
3147
+ for candidate in issue.get("matches") or []:
3148
+ if not isinstance(candidate, dict):
3149
+ continue
3150
+ for key in ("uid", "id", "memberId", "deptId", "roleId"):
3151
+ value = _coerce_positive_int(candidate.get(key))
3152
+ if value is not None:
3153
+ matched.add(value)
3154
+ return matched
3155
+
3156
+ def _matches_resolved_attribute(issue: dict[str, Any]) -> bool:
3157
+ kind = str(issue.get("kind") or "")
3158
+ raw = str(issue.get("value") or "").strip()
3159
+ if not raw:
3160
+ return False
3161
+ if kind in {"member_email", "external_member_email"}:
3162
+ entries = external_entries if kind.startswith("external") else member_entries
3163
+ return any(raw.lower() == str(entry.get("email") or "").strip().lower() for entry in entries)
3164
+ if kind == "member_name":
3165
+ return any(raw == str(entry.get("name") or "").strip() for entry in member_entries)
3166
+ if kind == "department_name":
3167
+ return any(raw == str(entry.get("deptName") or "").strip() for entry in department_entries)
3168
+ if kind == "role":
3169
+ return any(raw == str(entry.get("roleName") or "").strip() for entry in role_entries)
3170
+ return False
3171
+
3172
+ blocking_issues: list[dict[str, Any]] = []
3173
+ degraded_issues: list[dict[str, Any]] = []
3174
+ for issue in [
3175
+ *member_resolution["issues"],
3176
+ *role_resolution["issues"],
3177
+ *department_resolution["issues"],
3178
+ *external_member_resolution["issues"],
3179
+ ]:
3180
+ if str(issue.get("kind") or "") not in _SOFT_RESOLUTION_KINDS:
3181
+ blocking_issues.append(issue)
3182
+ continue
3183
+ error_code = str(issue.get("error_code") or "")
3184
+ if error_code.endswith("_SEARCH_FAILED"):
3185
+ covered = uid_direct_count > 0
3186
+ elif error_code.startswith("AMBIGUOUS_"):
3187
+ covered = bool(_match_anchor_ids(issue) & resolved_anchor_ids)
3188
+ elif error_code in _NOT_FOUND_RESOLUTION_CODES:
3189
+ covered = _matches_resolved_attribute(issue)
3190
+ else:
3191
+ # PERMISSION_DENIED/未知失败类:不可归因为「主体已被锚定的冗余通道」,
3192
+ # 维持阻断(master 语义)。
3193
+ blocking_issues.append(issue)
3194
+ continue
3195
+ if covered:
3196
+ degraded_issues.append(issue)
3197
+ else:
3198
+ blocking_issues.append(issue)
3100
3199
  self._raise_visibility_resolution_issues(blocking_issues)
3200
+ if degraded_issues and degradation_warnings is not None:
3201
+ for issue in degraded_issues:
3202
+ degradation_warnings.append(
3203
+ _warning(
3204
+ "VISIBILITY_SOFT_REFERENCE_DEGRADED",
3205
+ (
3206
+ f"visibility {issue.get('kind')} '{issue.get('value')}' could not be resolved "
3207
+ f"({issue.get('error_code')}); the subject is dropped from visibility selectors "
3208
+ "unless it was also anchored by a direct id reference"
3209
+ ),
3210
+ kind=issue.get("kind"),
3211
+ value=issue.get("value"),
3212
+ error_code=issue.get("error_code"),
3213
+ )
3214
+ )
3101
3215
 
3102
3216
  external_depart_entries: list[dict[str, Any]] = []
3103
3217
  for dept_id in visibility.external_selectors.dept_ids:
@@ -8753,7 +8867,25 @@ class AiBuilderFacade:
8753
8867
  "warnings": warnings,
8754
8868
  }
8755
8869
 
8756
- def portal_get(self, *, profile: str, dash_key: str, being_draft: bool = True) -> JSONObject:
8870
+ def portal_get(
8871
+ self,
8872
+ *,
8873
+ profile: str,
8874
+ dash_key: str,
8875
+ being_draft: bool = True,
8876
+ schema_kind: str = "raw",
8877
+ schema_version: str | None = None,
8878
+ ) -> JSONObject:
8879
+ """读取门户详情;schema_kind=summary|complete 时返回 canonical 声明投影,raw 为原始归一响应。"""
8880
+ normalized_kind = str(schema_kind or "raw").strip().lower() or "raw"
8881
+ if normalized_kind not in {"raw", "summary", "complete"}:
8882
+ return _failed(
8883
+ "UNSUPPORTED_SCHEMA_KIND",
8884
+ f"unsupported portal get schema kind: {normalized_kind}",
8885
+ normalized_args={"dash_key": dash_key, "being_draft": being_draft, "schema_kind": normalized_kind},
8886
+ details={"supportedKinds": ["raw", "summary", "complete"]},
8887
+ suggested_next_call={"tool_name": "portal_get", "arguments": {"profile": profile, "dash_key": dash_key, "schema_kind": "raw"}},
8888
+ )
8757
8889
  try:
8758
8890
  result = self.portals.portal_get(profile=profile, dash_key=dash_key, being_draft=being_draft).get("result") or {}
8759
8891
  except (QingflowApiError, RuntimeError) as error:
@@ -8761,10 +8893,52 @@ class AiBuilderFacade:
8761
8893
  return _failed_from_api_error(
8762
8894
  "PORTAL_GET_FAILED",
8763
8895
  api_error,
8764
- normalized_args={"dash_key": dash_key, "being_draft": being_draft},
8896
+ normalized_args={"dash_key": dash_key, "being_draft": being_draft, "schema_kind": normalized_kind},
8765
8897
  details={"dash_key": dash_key, "being_draft": being_draft},
8766
8898
  suggested_next_call={"tool_name": "portal_get", "arguments": {"profile": profile, "dash_key": dash_key, "being_draft": being_draft}},
8767
8899
  )
8900
+ if normalized_kind in {"summary", "complete"}:
8901
+ schema_context = None
8902
+ if schema_version is not None:
8903
+ try:
8904
+ schema_context = portals_schema_registry().resolve_schema_version(schema_version)
8905
+ except PortalsContractError as error:
8906
+ return _failed(
8907
+ error.error_code,
8908
+ str(error.message),
8909
+ normalized_args={"dash_key": dash_key, "being_draft": being_draft, "schema_kind": normalized_kind, "schema_version": schema_version},
8910
+ details={"reason_path": error.path or "", **(error.details or {})},
8911
+ suggested_next_call={"tool_name": "portal_schema", "arguments": {"schema_kind": "summary"}},
8912
+ )
8913
+ declaration, read_gaps = _portal_declaration_from_dash_detail(result, schema_kind=normalized_kind)
8914
+ response = {
8915
+ "status": "success",
8916
+ "error_code": None,
8917
+ "recoverable": False,
8918
+ "message": f"read portal declaration ({normalized_kind})",
8919
+ "normalized_args": {
8920
+ "dash_key": dash_key,
8921
+ "being_draft": being_draft,
8922
+ "schema_kind": normalized_kind,
8923
+ "schema_version": schema_version,
8924
+ },
8925
+ "missing_fields": [],
8926
+ "allowed_values": {"schema_kind": ["raw", "summary", "complete"]},
8927
+ "details": {"read_gaps": read_gaps} if read_gaps else {},
8928
+ "request_id": None,
8929
+ "suggested_next_call": None,
8930
+ "noop": False,
8931
+ "warnings": [],
8932
+ "verification": {"portal_exists": True, "being_draft": being_draft},
8933
+ "verified": True,
8934
+ "schemaVersion": schema_context.schema_version if schema_context is not None else portals_schema_registry().latest_version,
8935
+ "latestVersion": portals_schema_registry().latest_version,
8936
+ "apiVersion": schema_context.api_version if schema_context is not None else "builder.qingflow.com/v1alpha1",
8937
+ "schemaKind": normalized_kind,
8938
+ "declaration": declaration,
8939
+ "read_gap_count": len(read_gaps),
8940
+ }
8941
+ return response
8768
8942
  dash_icon = str(result.get("dashIcon") or "").strip() or None
8769
8943
  response = PortalGetResponse(
8770
8944
  dash_key=dash_key,
@@ -8859,6 +9033,124 @@ class AiBuilderFacade:
8859
9033
  **response.model_dump(mode="json"),
8860
9034
  }
8861
9035
 
9036
+ def portal_schema(
9037
+ self,
9038
+ *,
9039
+ schema_version: str | None = None,
9040
+ schema_kind: str | None = None,
9041
+ ) -> JSONObject:
9042
+ """读取版本化门户声明 schema;组件专项 kind 用于获取自包含专项配置定义。"""
9043
+ normalized_args = {"schema_version": schema_version, "schema_kind": schema_kind}
9044
+ try:
9045
+ payload = portals_schema_registry().schema(schema_version=schema_version, schema_kind=schema_kind)
9046
+ except PortalsContractError as error:
9047
+ return _failed(
9048
+ error.error_code,
9049
+ str(error.message),
9050
+ normalized_args=normalized_args,
9051
+ details={"reason_path": error.path or "", **(error.details or {})},
9052
+ suggested_next_call={"tool_name": "portal_schema", "arguments": {"schema_kind": "summary"}},
9053
+ )
9054
+ return {
9055
+ "status": "success",
9056
+ "error_code": None,
9057
+ "recoverable": False,
9058
+ "message": "read portals declaration schema",
9059
+ "normalized_args": normalized_args,
9060
+ "missing_fields": [],
9061
+ "allowed_values": {"schema_kind": payload["supportedSchemaKinds"]},
9062
+ "details": {},
9063
+ "request_id": None,
9064
+ "suggested_next_call": None,
9065
+ "warnings": [],
9066
+ "verification": {"schema_loaded": True},
9067
+ **payload,
9068
+ }
9069
+
9070
+ def portal_validate(
9071
+ self,
9072
+ *,
9073
+ declaration: JSONObject,
9074
+ schema_version: str | None = None,
9075
+ ) -> JSONObject:
9076
+ """纯离线校验一条门户声明;不访问后端。"""
9077
+ normalized_args = {"schema_version": schema_version}
9078
+ resolved_version = (
9079
+ str(schema_version or (declaration.get("schema_version") if isinstance(declaration, dict) else None) or "").strip() or None
9080
+ )
9081
+ try:
9082
+ context = portals_schema_registry().resolve_schema_version(resolved_version)
9083
+ except PortalsContractError as error:
9084
+ return _failed(
9085
+ error.error_code,
9086
+ str(error.message),
9087
+ normalized_args=normalized_args,
9088
+ details={"reason_path": error.path or "", **(error.details or {})},
9089
+ suggested_next_call={"tool_name": "portal_schema", "arguments": {"schema_kind": "complete"}},
9090
+ )
9091
+ issues: list[dict[str, Any]] = []
9092
+ if not isinstance(declaration, dict):
9093
+ issues.append({"path": "/", "code": "INVALID_SPEC", "message": "portals declaration must be a JSON object"})
9094
+ else:
9095
+ declaration_item = {
9096
+ key: value
9097
+ for key, value in declaration.items()
9098
+ if key not in {"schema_version", "schemaVersion", "apiVersion"}
9099
+ }
9100
+ try:
9101
+ parsed = PortalApplyRequest.model_validate(declaration_item)
9102
+ context.validate_upsert(compact_none_values(public_portal_apply_payload(parsed)))
9103
+ except ValidationError as exc:
9104
+ first_error = exc.errors()[0]
9105
+ issues.append(
9106
+ {
9107
+ "path": f"/{'/'.join(str(part) for part in first_error.get('loc', ()))}".rstrip("/"),
9108
+ "code": "INVALID_SPEC",
9109
+ "message": str(first_error.get("msg") or exc),
9110
+ }
9111
+ )
9112
+ except PortalsContractError as error:
9113
+ issues.append({"path": error.path or "/", "code": error.error_code, "message": str(error.message)})
9114
+ else:
9115
+ # 创建语义(无 dash_key)的 icon/color 目录校验与 apply 同口径:离线
9116
+ # jsonschema 不含目录枚举(更新语义须放行存量 hex 透传),不补这层
9117
+ # 会出现「validate 通过、apply 拒绝」的校验信任断裂(实测反馈失败二
9118
+ # 同型);更新语义不做目录校验(与 apply 更新分支一致)。
9119
+ if not str(parsed.dash_key or "").strip():
9120
+ icon_ok, icon_error_code, icon_message, _icon_details = validate_workspace_icon_choice(
9121
+ icon=parsed.icon,
9122
+ color=parsed.color,
9123
+ require_explicit=True,
9124
+ disallow_generic=True,
9125
+ )
9126
+ if not icon_ok:
9127
+ issues.append(
9128
+ {
9129
+ "path": "/color" if str(icon_error_code or "").endswith("COLOR_NOT_FOUND") or icon_error_code == "WORKSPACE_ICON_COLOR_REQUIRED" else "/icon",
9130
+ "code": icon_error_code or "WORKSPACE_ICON_INVALID",
9131
+ "message": icon_message or "invalid workspace icon configuration",
9132
+ }
9133
+ )
9134
+ ok = not issues
9135
+ return {
9136
+ "status": "success" if ok else "failed",
9137
+ "error_code": None if ok else issues[0]["code"],
9138
+ "recoverable": True,
9139
+ "message": "portals declaration is valid" if ok else "portals declaration failed validation",
9140
+ "normalized_args": normalized_args,
9141
+ "missing_fields": [],
9142
+ "allowed_values": {},
9143
+ "details": {"issues": issues},
9144
+ "request_id": None,
9145
+ "suggested_next_call": None,
9146
+ "warnings": [],
9147
+ "verification": {"validated_entries": 1 if ok else 0},
9148
+ "ok": ok,
9149
+ "schemaVersion": context.schema_version,
9150
+ "apiVersion": context.api_version,
9151
+ "issues": issues,
9152
+ }
9153
+
8862
9154
  def view_get(self, *, profile: str, view_key: str) -> JSONObject:
8863
9155
  try:
8864
9156
  config = self.views.view_get_config(profile=profile, viewgraph_key=view_key).get("result") or {}
@@ -15078,7 +15370,13 @@ class AiBuilderFacade:
15078
15370
  "safe_to_retry": not write_executed,
15079
15371
  })
15080
15372
 
15081
- def portal_apply(self, *, profile: str, request: PortalApplyRequest) -> JSONObject:
15373
+ def portal_apply(
15374
+ self,
15375
+ *,
15376
+ profile: str,
15377
+ request: PortalApplyRequest,
15378
+ schema_version: str | None = None,
15379
+ ) -> JSONObject:
15082
15380
  apply_started_at = time.perf_counter()
15083
15381
  portal_initial_read_ms: int | None = None
15084
15382
  portal_create_ms: int | None = None
@@ -15088,23 +15386,51 @@ class AiBuilderFacade:
15088
15386
  portal_draft_readback_ms: int | None = None
15089
15387
  portal_publish_ms: int | None = None
15090
15388
  portal_live_readback_ms: int | None = None
15389
+ effective_schema_version = str(schema_version or request.schema_version or "").strip() or None
15091
15390
  normalized_args = request.model_dump(mode="json")
15391
+ normalized_args["schema_version"] = effective_schema_version
15392
+ schema_context: PortalsSchemaContext | None = None
15393
+ if effective_schema_version is not None:
15394
+ try:
15395
+ schema_context = portals_schema_registry().resolve_schema_version(effective_schema_version)
15396
+ schema_context.validate_upsert(
15397
+ compact_none_values(public_portal_apply_payload(request))
15398
+ )
15399
+ except PortalsContractError as error:
15400
+ return _failed(
15401
+ error.error_code,
15402
+ str(error.message),
15403
+ normalized_args=normalized_args,
15404
+ details={"reason_path": error.path or "", **(error.details or {})},
15405
+ suggested_next_call={"tool_name": "portal_schema", "arguments": {"schema_version": effective_schema_version, "schema_kind": "complete"}},
15406
+ )
15092
15407
  permission_outcomes: list[PermissionCheckOutcome] = []
15093
15408
  dash_key = str(request.dash_key or "").strip()
15094
15409
  creating = not dash_key
15095
- sections_requested = creating or bool(request.sections)
15410
+ # sections_requested 语义:显式携带 sections 键(含空列表)即走组件重建链;
15411
+ # 未传(不在 model_fields_set)才是纯 base-info 更新。模型缺省 sections=[] 与
15412
+ # 显式空列表同值,只能用 fields_set 区分。空 sections=[] 是合法存量形态
15413
+ # (无组件门户):后端 updateDash 对空组件列表=删全部后不重建(getComponents
15414
+ # 非空才重建),createDash 不建组件——把空列表当「未传」会把携带
15415
+ # global_config/hide_copyright 的空门户拒之门外。
15416
+ sections_requested = creating or ("sections" in request.model_fields_set)
15096
15417
  verify_dash_name = creating or request.dash_name is not None
15097
15418
  verify_dash_icon = bool(request.icon or request.color)
15098
15419
  verify_auth = request.visibility is not None or request.auth is not None
15099
15420
  verify_hide_copyright = request.hide_copyright is not None and sections_requested
15100
- verify_dash_global_config = request.dash_global_config is not None and sections_requested
15421
+ verify_dash_global_config = request.global_config is not None and sections_requested
15101
15422
  verify_tags = creating or request.package_tag_id is not None
15102
15423
  requested_visibility = request.visibility
15103
15424
  if requested_visibility is None and isinstance(request.auth, dict) and request.auth:
15104
15425
  requested_visibility = VisibilityPatch.model_validate(_public_visibility_from_member_auth(request.auth))
15426
+ visibility_degradation_warnings: list[dict[str, Any]] = []
15105
15427
  try:
15106
15428
  desired_auth = (
15107
- self._compile_visibility_to_member_auth(profile=profile, visibility=requested_visibility)
15429
+ self._compile_visibility_to_member_auth(
15430
+ profile=profile,
15431
+ visibility=requested_visibility,
15432
+ degradation_warnings=visibility_degradation_warnings,
15433
+ )
15108
15434
  if requested_visibility is not None
15109
15435
  else None
15110
15436
  )
@@ -15147,6 +15473,14 @@ class AiBuilderFacade:
15147
15473
  permission_outcomes.append(portal_permission_outcome)
15148
15474
 
15149
15475
  def finalize(response: JSONObject) -> JSONObject:
15476
+ if schema_context is not None:
15477
+ response["schemaVersion"] = schema_context.schema_version
15478
+ # 可见性冗余引用降级明细回信封(review §2-1:降级不再静默)
15479
+ if visibility_degradation_warnings:
15480
+ existing_warnings = response.get("warnings")
15481
+ warnings = list(existing_warnings) if isinstance(existing_warnings, list) else []
15482
+ warnings.extend(item for item in visibility_degradation_warnings if item not in warnings)
15483
+ response["warnings"] = warnings
15150
15484
  _merge_duration_breakdown(
15151
15485
  response,
15152
15486
  portal_initial_read_ms=portal_initial_read_ms,
@@ -15184,8 +15518,8 @@ class AiBuilderFacade:
15184
15518
  unsupported_base_only_keys: list[str] = []
15185
15519
  if request.hide_copyright is not None:
15186
15520
  unsupported_base_only_keys.append("hide_copyright")
15187
- if request.dash_global_config is not None:
15188
- unsupported_base_only_keys.append("dash_global_config")
15521
+ if request.global_config is not None:
15522
+ unsupported_base_only_keys.append("global_config")
15189
15523
  if request.config:
15190
15524
  unsupported_base_only_keys.append("config")
15191
15525
  if unsupported_base_only_keys:
@@ -15200,6 +15534,7 @@ class AiBuilderFacade:
15200
15534
  suggested_next_call={"tool_name": "portal_apply", "arguments": {"profile": profile, **normalized_args}},
15201
15535
  )
15202
15536
  write_executed = False
15537
+ sections_write_completed = False
15203
15538
  draft_readback_error: JSONObject | None = None
15204
15539
  live_readback_error: JSONObject | None = None
15205
15540
  update_payload: dict[str, Any] = {}
@@ -15208,18 +15543,20 @@ class AiBuilderFacade:
15208
15543
  layout_diagnostics: dict[str, Any] = _empty_portal_layout_diagnostics()
15209
15544
  if creating:
15210
15545
  create_payload = _build_public_portal_base_payload(
15211
- dash_name=request.dash_name or "未命名门户",
15546
+ dash_name=request.dash_name if request.dash_name is not None else "未命名门户",
15212
15547
  package_tag_id=target_package_tag_id,
15213
15548
  icon=request.icon,
15214
15549
  color=request.color,
15215
15550
  auth=desired_auth,
15216
15551
  hide_copyright=request.hide_copyright,
15217
- dash_global_config=request.dash_global_config,
15552
+ dash_global_config=request.global_config,
15553
+ style_template_id=request.style_template_id,
15554
+ overall_style=request.overall_style,
15218
15555
  config=request.config,
15219
15556
  base_payload=None,
15220
15557
  )
15221
15558
  portal_create_started_at = time.perf_counter()
15222
- create_result = self.portals.portal_create(profile=profile, payload=create_payload)
15559
+ create_result = self._portal_writer.create_portal(profile=profile, payload=create_payload)
15223
15560
  portal_create_ms = _duration_ms(portal_create_started_at)
15224
15561
  write_executed = True
15225
15562
  created = create_result.get("result") if isinstance(create_result.get("result"), dict) else {}
@@ -15242,13 +15579,15 @@ class AiBuilderFacade:
15242
15579
  }
15243
15580
  base_payload = {}
15244
15581
  update_payload = _build_public_portal_base_payload(
15245
- dash_name=request.dash_name or str(base_payload.get("dashName") or "").strip() or "未命名门户",
15582
+ dash_name=request.dash_name if request.dash_name is not None else (str(base_payload.get("dashName") or "").strip() or "未命名门户"),
15246
15583
  package_tag_id=target_package_tag_id,
15247
15584
  icon=request.icon,
15248
15585
  color=request.color,
15249
15586
  auth=desired_auth,
15250
15587
  hide_copyright=request.hide_copyright,
15251
- dash_global_config=request.dash_global_config,
15588
+ dash_global_config=request.global_config,
15589
+ style_template_id=request.style_template_id,
15590
+ overall_style=request.overall_style,
15252
15591
  config=request.config,
15253
15592
  base_payload=base_payload,
15254
15593
  )
@@ -15264,9 +15603,10 @@ class AiBuilderFacade:
15264
15603
  layout_diagnostics = _portal_layout_diagnostics(request.sections, component_payload, layout_metadata=layout_metadata)
15265
15604
  update_payload["components"] = component_payload
15266
15605
  portal_update_started_at = time.perf_counter()
15267
- self.portals.portal_update(profile=profile, dash_key=dash_key, payload=update_payload)
15606
+ self._portal_writer.update_portal(profile=profile, dash_key=dash_key, payload=update_payload)
15268
15607
  portal_update_ms = _duration_ms(portal_update_started_at)
15269
15608
  write_executed = True
15609
+ sections_write_completed = True
15270
15610
  else:
15271
15611
  portal_component_build_ms = 0
15272
15612
  portal_update_ms = 0
@@ -15281,15 +15621,22 @@ class AiBuilderFacade:
15281
15621
  )
15282
15622
  if base_info_update_requested:
15283
15623
  portal_base_info_update_started_at = time.perf_counter()
15284
- self.portals.portal_update_base_info(
15624
+ base_info_payload = {
15625
+ "dashName": update_payload.get("dashName"),
15626
+ "dashIcon": update_payload.get("dashIcon"),
15627
+ "auth": deepcopy(update_payload.get("auth")),
15628
+ }
15629
+ # tags 空列表省略键:后端 updateDashBaseInfo(DashSvcImpl)对非 null 的空 tags
15630
+ # 按 ws 过滤后判空抛 PARAMS_ERROR → 整个 baseInfo 写失败(事务回滚,name/icon/auth
15631
+ # 全部静默失效,r8 实测 16 门)。省略键 → getTags()==null → 后端跳过 tags 校验与更新,
15632
+ # 其余字段正常写。声明显式给 package_tag_id 时 tags 非空,不受影响。
15633
+ base_info_tags = deepcopy(update_payload.get("tags") or [])
15634
+ if base_info_tags:
15635
+ base_info_payload["tags"] = base_info_tags
15636
+ self._portal_writer.update_portal_base_info(
15285
15637
  profile=profile,
15286
15638
  dash_key=dash_key,
15287
- payload={
15288
- "dashName": update_payload.get("dashName"),
15289
- "dashIcon": update_payload.get("dashIcon"),
15290
- "auth": deepcopy(update_payload.get("auth")),
15291
- "tags": deepcopy(update_payload.get("tags") or []),
15292
- },
15639
+ payload=base_info_payload,
15293
15640
  )
15294
15641
  portal_base_info_update_ms = _duration_ms(portal_base_info_update_started_at)
15295
15642
  write_executed = True
@@ -15308,9 +15655,55 @@ class AiBuilderFacade:
15308
15655
  draft_result = {}
15309
15656
  else:
15310
15657
  portal_draft_readback_ms = _duration_ms(portal_draft_readback_started_at)
15311
- except (QingflowApiError, RuntimeError, ValueError) as error:
15312
- api_error = _coerce_api_error(error) if not isinstance(error, ValueError) else None
15658
+ except Exception as error: # noqa: BLE001 — 任何失败都必须走清壳路径,不允许异常击穿留下半成品
15659
+ api_error = _coerce_api_error(error) if isinstance(error, (QingflowApiError, RuntimeError)) else None
15313
15660
  inline_chart_write_executed = any(bool(item.get("write_executed")) for item in inline_chart_results)
15661
+ # 本次 apply 创建的空壳回收:创建成功但 sections 未写入且无内联图表写入时,
15662
+ # 删除刚建的门户壳,阻断「失败重试 → 0 组件空门户堆积」(实测反馈 3 个空壳)。
15663
+ # 更新语义(dash_key 定位)与已有真实写入的场景不回收。
15664
+ if creating and dash_key and not sections_write_completed and not inline_chart_write_executed:
15665
+ cleanup: dict[str, Any] | None = None
15666
+ try:
15667
+ self.portals.portal_delete(profile=profile, dash_key=dash_key)
15668
+ cleanup = {"status": "deleted", "dash_key": dash_key}
15669
+ except (QingflowApiError, RuntimeError) as cleanup_error:
15670
+ cleanup = {
15671
+ "status": "failed",
15672
+ "dash_key": dash_key,
15673
+ "message": _coerce_api_error(cleanup_error).message,
15674
+ }
15675
+ if cleanup.get("status") == "deleted":
15676
+ return finalize(
15677
+ {
15678
+ "status": "failed",
15679
+ "error_code": "PORTAL_APPLY_FAILED",
15680
+ "recoverable": True,
15681
+ "message": (
15682
+ "portal apply failed before sections were written; the empty portal shell "
15683
+ "created in this call was cleaned up — retry the same declaration safely"
15684
+ ),
15685
+ "normalized_args": normalized_args,
15686
+ "missing_fields": [],
15687
+ "allowed_values": {},
15688
+ "details": {
15689
+ "created_portal_cleanup": cleanup,
15690
+ "write_error": (
15691
+ {"message": api_error.message, "transport_error": _transport_error_payload(api_error)}
15692
+ if api_error is not None
15693
+ else {"message": str(error)}
15694
+ ),
15695
+ **({"inline_chart_results": deepcopy(inline_chart_results)} if inline_chart_results else {}),
15696
+ },
15697
+ "request_id": api_error.request_id if api_error else None,
15698
+ "backend_code": api_error.backend_code if api_error else None,
15699
+ "http_status": None if api_error is None or api_error.http_status == 404 else api_error.http_status,
15700
+ "suggested_next_call": {"tool_name": "portal_apply", "arguments": {"profile": profile, **normalized_args}},
15701
+ "noop": False,
15702
+ "warnings": [],
15703
+ "verification": {"write_incomplete": True, "created_portal_cleaned_up": True},
15704
+ }
15705
+ )
15706
+ # 清理失败:空壳仍在,带 dash_key 走 partial 语义交人工处理
15314
15707
  if write_executed or inline_chart_write_executed:
15315
15708
  transport_error = _transport_error_payload(api_error) if api_error is not None else None
15316
15709
  warning = _warning(
@@ -16498,6 +16891,22 @@ class AiBuilderFacade:
16498
16891
  },
16499
16892
  )
16500
16893
  )
16894
+ except Exception as error: # noqa: BLE001
16895
+ # 工作线程的任何未预期异常(含并发 session 刷新竞态的
16896
+ # KeyError)都不得击穿整个 portal apply——否则门户壳已创建
16897
+ # 而组件未写入,清理逻辑也无从执行(实测空壳残留路径)。
16898
+ inline_chart_job_results.append(
16899
+ (
16900
+ job,
16901
+ {
16902
+ "status": "failed",
16903
+ "error_code": "PORTAL_INLINE_CHART_APPLY_FAILED",
16904
+ "message": f"{type(error).__name__}: {error}",
16905
+ "write_executed": False,
16906
+ "details": {"unexpected_error": True},
16907
+ },
16908
+ )
16909
+ )
16501
16910
 
16502
16911
  for job, chart_apply in sorted(inline_chart_job_results, key=lambda item: int(item[0].get("section_index") or 0)):
16503
16912
  app_key = str(job["app_key"])
@@ -16604,25 +17013,58 @@ class AiBuilderFacade:
16604
17013
  resolved_chart = inline_chart_resolutions.get(section_index)
16605
17014
  if not isinstance(resolved_chart, dict):
16606
17015
  raise ValueError(f"inline chart '{section.chart.name}' could not be created or updated for portal section '{section.title}'")
17016
+ chart_type = str(
17017
+ resolved_chart.get("chart_type")
17018
+ or _public_chart_type_from_backend(section.config.get("chartType") or section.config.get("chart_type"))
17019
+ or ""
17020
+ ).strip()
17021
+ chart_config = {
17022
+ "biChartId": resolved_chart["chart_id"],
17023
+ # title=None(存量空标题)不落库——_compact_dict 剔除,后端透传 NULL 保真;
17024
+ # beingShowTitle 以声明 show_title 为准(读面提取必有值),缺省回落产品默认 True。
17025
+ "chartComponentTitle": section.title,
17026
+ "beingShowTitle": section.show_title if section.show_title is not None else True,
17027
+ **deepcopy(section.config),
17028
+ }
17029
+ component = {"type": 9, "position": position_payload, "chartConfig": _compact_dict(chart_config)}
17030
+ layout_metadata.append({"source_type": section.source_type, "chart_type": chart_type, "role": section.role})
17031
+ elif section.chart_ref is not None and str(getattr(section.chart_ref, "ref_kind", "") or "") == "chart":
17032
+ # 轻流报表引用面(后端 DASH_CONTENT_TYPE_CHART=1):chart_id 携带的是
17033
+ # chart 表唯一键 chartKey,写链 addChartInfos 按 chartKey 解析,不走
17034
+ # BI 报表列表解析;不携带运行态派生键(chartId/chartName/formTitle 等读面回填)。
17035
+ chart_key = str(getattr(section.chart_ref, "chart_id", "") or "").strip()
17036
+ if not chart_key:
17037
+ raise ValueError(f"chart_ref with ref_kind=chart requires chart_id for portal section '{section.title}'")
17038
+ chart_config = {
17039
+ "chartKey": chart_key,
17040
+ # 同上:title=None 不落库、beingShowTitle 声明优先、缺省 True。
17041
+ "chartComponentTitle": section.title,
17042
+ "beingShowTitle": section.show_title if section.show_title is not None else True,
17043
+ **deepcopy(section.config),
17044
+ }
17045
+ component = {"type": 1, "position": position_payload, "chartConfig": _compact_dict(chart_config)}
17046
+ layout_metadata.append({"source_type": section.source_type, "chart_type": str(_public_chart_type_from_backend(section.config.get("chartType") or section.config.get("chart_type")) or "").strip(), "role": section.role})
16607
17047
  else:
16608
17048
  resolved_chart = _resolve_chart_reference(
16609
17049
  charts=self.charts,
16610
17050
  profile=profile,
16611
17051
  ref=section.chart_ref,
16612
17052
  )
16613
- chart_type = str(
16614
- resolved_chart.get("chart_type")
16615
- or _public_chart_type_from_backend(section.config.get("chartType") or section.config.get("chart_type"))
16616
- or ""
16617
- ).strip()
16618
- chart_config = {
16619
- "biChartId": resolved_chart["chart_id"],
16620
- "chartComponentTitle": section.title,
16621
- "beingShowTitle": True,
16622
- **deepcopy(section.config),
16623
- }
16624
- component = {"type": 9, "position": position_payload, "chartConfig": _compact_dict(chart_config)}
16625
- layout_metadata.append({"source_type": section.source_type, "chart_type": chart_type, "role": section.role})
17053
+ chart_type = str(
17054
+ resolved_chart.get("chart_type")
17055
+ or _public_chart_type_from_backend(section.config.get("chartType") or section.config.get("chart_type"))
17056
+ or ""
17057
+ ).strip()
17058
+ chart_config = {
17059
+ "biChartId": resolved_chart["chart_id"],
17060
+ # title=None(存量空标题)不落库——_compact_dict 剔除,后端透传 NULL 保真;
17061
+ # beingShowTitle 以声明 show_title 为准(读面提取必有值),缺省回落产品默认 True。
17062
+ "chartComponentTitle": section.title,
17063
+ "beingShowTitle": section.show_title if section.show_title is not None else True,
17064
+ **deepcopy(section.config),
17065
+ }
17066
+ component = {"type": 9, "position": position_payload, "chartConfig": _compact_dict(chart_config)}
17067
+ layout_metadata.append({"source_type": section.source_type, "chart_type": chart_type, "role": section.role})
16626
17068
  elif section.source_type == "view":
16627
17069
  resolved_view = _resolve_view_reference(
16628
17070
  facade=self,
@@ -16636,34 +17078,68 @@ class AiBuilderFacade:
16636
17078
  view_config = {
16637
17079
  "appKey": resolved_view["app_key"],
16638
17080
  "viewgraphKey": resolved_view["view_key"],
16639
- "viewgraphName": section.title,
17081
+ # viewgraphName=视图名(引用面锚,view_ref.view_name 优先);componentTitle=组件
17082
+ # 显示标题(title=None 的存量空标题形态经 _compact_dict 剔除,落库 NULL 保真,
17083
+ # 旧逻辑把视图名兑底进 componentTitle 会覆盖读链 chartName 派生分支)。
17084
+ "viewgraphName": getattr(section.view_ref, "view_name", None) or section.title,
16640
17085
  "formTitle": app_title_cache[resolved_view["app_key"]],
16641
17086
  "componentTitle": section.title,
16642
17087
  "viewgraphType": resolved_view["view_type"],
16643
- "beingShowTitle": True,
17088
+ # beingShowTitle 声明 show_title 优先(view_display.show_title 提取必有值;
17089
+ # 存量 false 被硬 True 覆写会漂移库表);缺省保持产品默认 True。
17090
+ "beingShowTitle": section.show_title if section.show_title is not None else True,
16644
17091
  "dataManageStatus": True,
16645
17092
  **deepcopy(section.config),
16646
17093
  }
17094
+ if section.view_display:
17095
+ display = _compile_portal_view_display(section.view_display)
17096
+ for key, value in display.items():
17097
+ view_config[key] = value
16647
17098
  component = {"type": 10, "position": position_payload, "viewgraphConfig": _compact_dict(view_config)}
16648
17099
  layout_metadata.append({"source_type": section.source_type, "role": section.role})
16649
17100
  elif section.source_type == "grid":
17101
+ # 应用入口跳转页面缺省:声明未给 linkFormType 的 type=1 条目按 1(数据列表)
17102
+ # 补齐——缺失时前端渲染的跳转目标为空、入口无法点击(实测反馈)。其余
17103
+ # 入口类型(2=门户/3=应用包/4=外链)不走该键,显式值一律保留。
17104
+ grid_config_payload = deepcopy(section.config)
17105
+ grid_items = grid_config_payload.get("items") if isinstance(grid_config_payload, dict) else None
17106
+ if isinstance(grid_items, list):
17107
+ for grid_item in grid_items:
17108
+ if isinstance(grid_item, dict) and _coerce_positive_int(grid_item.get("type")) == 1:
17109
+ if _coerce_positive_int(grid_item.get("linkFormType")) is None:
17110
+ grid_item["linkFormType"] = 1
16650
17111
  component = {
16651
17112
  "type": 2,
16652
17113
  "position": position_payload,
16653
- "gridConfig": _compact_dict({"gridTitle": section.title, "beingShowTitle": True, **deepcopy(section.config)}),
17114
+ # gridTitle=None(存量空标题)剔除不落库;beingShowTitle 缺省 True、声明 config 内
17115
+ # beingShowTitle 键后置覆盖(提取侧 grid config 保留该键,存量 false 保真)。
17116
+ "gridConfig": _compact_dict({"gridTitle": section.title, "beingShowTitle": True, **(grid_config_payload if isinstance(grid_config_payload, dict) else {})}),
16654
17117
  }
16655
17118
  layout_metadata.append({"source_type": section.source_type, "role": section.role})
16656
17119
  elif section.source_type == "filter":
16657
- component = {"type": 6, "position": position_payload, "filterConfig": deepcopy(section.config)}
17120
+ component = {"type": 6, "position": position_payload, "filterConfig": _compile_portal_filter_config(section.config)}
16658
17121
  layout_metadata.append({"source_type": section.source_type, "role": section.role})
16659
17122
  elif section.source_type == "text":
16660
17123
  component = {"type": 5, "position": position_payload, "textConfig": {"text": section.text or "", **deepcopy(section.config)}}
16661
17124
  layout_metadata.append({"source_type": section.source_type, "role": section.role})
17125
+ elif section.source_type == "carousel":
17126
+ carousel_config = self._compile_portal_carousel_config(profile=profile, section=section)
17127
+ component = {"type": 3, "position": position_payload, "carouselConfig": _compact_dict(carousel_config)}
17128
+ layout_metadata.append({"source_type": section.source_type, "role": section.role})
17129
+ elif section.source_type == "task":
17130
+ task_config = _compile_portal_task_config(section.title, section.task or {})
17131
+ component = {"type": 8, "position": position_payload, "taskConfig": _compact_dict(task_config)}
17132
+ layout_metadata.append({"source_type": section.source_type, "role": section.role})
17133
+ elif section.source_type == "favourite":
17134
+ favourite_config = _compile_portal_favourite_config(section.title, section.favourite or {})
17135
+ component = {"type": 7, "position": position_payload, "favouriteConfig": _compact_dict(favourite_config)}
17136
+ layout_metadata.append({"source_type": section.source_type, "role": section.role})
16662
17137
  else:
17138
+ link_config = {"url": section.url or "", "beingLoginAuth": bool(section.login_auth) if section.login_auth is not None else False, **deepcopy(section.config)}
16663
17139
  component = {
16664
17140
  "type": 4,
16665
17141
  "position": position_payload,
16666
- "linkConfig": {"url": section.url or "", "beingLoginAuth": False, **deepcopy(section.config)},
17142
+ "linkConfig": _compact_dict(link_config),
16667
17143
  }
16668
17144
  layout_metadata.append({"source_type": section.source_type, "role": section.role})
16669
17145
  if dash_style is not None:
@@ -16671,6 +17147,113 @@ class AiBuilderFacade:
16671
17147
  resolved_components.append(component)
16672
17148
  return resolved_components, layout_metadata, inline_chart_results
16673
17149
 
17150
+ def _compile_portal_carousel_config(self, *, profile: str, section: PortalSectionPatch) -> dict[str, Any]:
17151
+ """Compile a carousel section declaration into the backend carouselConfig shape."""
17152
+ raw = section.carousel or {}
17153
+ if not isinstance(raw, dict):
17154
+ raise ValueError("carousel section config must be an object")
17155
+ app_key = str(raw.get("source_app_key") or raw.get("sourceAppKey") or "").strip()
17156
+ carousel_config: dict[str, Any] = {}
17157
+ fields_by_que_id: dict[int, dict[str, Any]] = {}
17158
+ field_name_to_field: dict[str, dict[str, Any]] = {}
17159
+ if app_key:
17160
+ carousel_config["sourceApp"] = {"appKey": app_key}
17161
+ if raw.get("source_form_title") or raw.get("sourceFormTitle"):
17162
+ carousel_config["sourceApp"]["formTitle"] = str(raw.get("source_form_title") or raw.get("sourceFormTitle"))
17163
+ # 字段索引从原始 form schema 面构建(_read_schema_with_fallback + schema 分支,
17164
+ # 与 views apply 同源):app_read_fields 解析面的字段不带 option_details,
17165
+ # _resolve_view_filter_values 的选项文本→ID 解析分支不生效,选项文本被
17166
+ # 原样透传进 formula,后端写后自读 Integer.parseInt("文本") 崩溃回滚
17167
+ # (r6 实测 9b91e277;七条约束之四:两读面锚定同一数据源)。
17168
+ schema, _schema_source = self._read_schema_with_fallback(profile=profile, app_key=app_key)
17169
+ fields_by_que_id = _collect_fields_by_que_id([], schema=schema)
17170
+ field_name_to_field = {
17171
+ str(field.get("name") or ""): field
17172
+ for field in fields_by_que_id.values()
17173
+ if str(field.get("name") or "")
17174
+ }
17175
+ # 悬空轮播(存量形态:源表已删,related_form_id NULL,读面 sourceApp 空):后端写链
17176
+ # DraftComponentCarousel 构造对 sourceApp 空/无 appKey 不写 relatedFormId,读面回空
17177
+ # sourceApp——round-trip 保真;无源表则无从解析字段引用,仅保留运行参数(jump_mode 等)。
17178
+
17179
+ def _resolve_que_ref(field_name: Any, *, config_key: str) -> dict[str, Any] | None:
17180
+ raw_name = str(field_name or "").strip()
17181
+ if not raw_name:
17182
+ return None
17183
+ field: dict[str, Any] | None = None
17184
+ if raw_name.isdigit():
17185
+ que_id = _coerce_positive_int(raw_name)
17186
+ field = fields_by_que_id.get(que_id) if que_id is not None else None
17187
+ else:
17188
+ field = field_name_to_field.get(raw_name)
17189
+ if field is None:
17190
+ raise ValueError(
17191
+ f"carousel section '{section.title}' references unknown {config_key} '{raw_name}' in app '{app_key}'"
17192
+ )
17193
+ que_id = _coerce_positive_int(field.get("que_id"))
17194
+ if que_id is None:
17195
+ raise ValueError(
17196
+ f"carousel section '{section.title}' {config_key} '{raw_name}' has no que_id in app '{app_key}'"
17197
+ )
17198
+ return {"queId": que_id}
17199
+
17200
+ title_que = _resolve_que_ref(raw.get("title_field") or raw.get("titleField"), config_key="title_field")
17201
+ image_que = _resolve_que_ref(raw.get("image_field") or raw.get("imageField"), config_key="image_field")
17202
+ link_que = _resolve_que_ref(raw.get("link_field") or raw.get("linkField"), config_key="link_field")
17203
+ if title_que is not None:
17204
+ carousel_config["titleQue"] = title_que
17205
+ if image_que is not None:
17206
+ carousel_config["imageQue"] = image_que
17207
+ if link_que is not None:
17208
+ carousel_config["linkQue"] = link_que
17209
+ jump_mode = _coerce_positive_int(raw.get("jump_mode") or raw.get("jumpMode"))
17210
+ if jump_mode is not None:
17211
+ carousel_config["jumpMode"] = jump_mode
17212
+ if "scaling" in raw or "beingScaling" in raw:
17213
+ carousel_config["beingScaling"] = bool(raw.get("scaling", raw.get("beingScaling")))
17214
+ show_latest_limit = _coerce_positive_int(raw.get("show_latest_limit") or raw.get("showLatestLimit"))
17215
+ if show_latest_limit is not None:
17216
+ carousel_config["showLatestLimit"] = show_latest_limit
17217
+ scroll_interval = _coerce_positive_int(raw.get("scroll_interval") or raw.get("scrollInterval"))
17218
+ if scroll_interval is not None:
17219
+ carousel_config["scrollInterval"] = scroll_interval
17220
+ raw_filters = raw.get("filters")
17221
+ if isinstance(raw_filters, list) and raw_filters:
17222
+ translated_rules: list[dict[str, Any]] = []
17223
+ for raw_rule in raw_filters:
17224
+ if hasattr(raw_rule, "model_dump"):
17225
+ raw_rule = raw_rule.model_dump(mode="json")
17226
+ if not isinstance(raw_rule, dict):
17227
+ continue
17228
+ field_name = str(raw_rule.get("field_name") or raw_rule.get("fieldName") or "").strip()
17229
+ field: dict[str, Any] | None = None
17230
+ if field_name.isdigit():
17231
+ # 与 _resolve_que_ref 同型:queId 数字串优先按稳定锚解析(提取器 canonical 形态)
17232
+ que_id = _coerce_positive_int(field_name)
17233
+ field = fields_by_que_id.get(que_id) if que_id is not None else None
17234
+ if field is None:
17235
+ field = field_name_to_field.get(field_name)
17236
+ if field is None:
17237
+ raise ValueError(
17238
+ f"carousel section '{section.title}' filters reference unknown field '{field_name}' in app '{app_key}'"
17239
+ )
17240
+ rule_payload = {
17241
+ "que_id": field.get("que_id"),
17242
+ "operator": raw_rule.get("operator") or raw_rule.get("op") or "eq",
17243
+ "values": list(raw_rule.get("values") or []),
17244
+ }
17245
+ groups, filter_issues = _build_view_filter_groups(fields_by_que_id=fields_by_que_id, filters=[rule_payload])
17246
+ blocking = [issue for issue in filter_issues if issue.get("error_code")]
17247
+ if blocking:
17248
+ raise ValueError(
17249
+ f"carousel section '{section.title}' filters failed to compile: {blocking[0]}"
17250
+ )
17251
+ if groups:
17252
+ translated_rules.extend(groups[0])
17253
+ if translated_rules:
17254
+ carousel_config["filterConfig"] = [translated_rules]
17255
+ return carousel_config
17256
+
16674
17257
  def _resolve_current_user_identity(self, *, profile: str) -> JSONObject:
16675
17258
  session_profile = self.apps.sessions.get_profile(profile)
16676
17259
  backend_session = self.apps.sessions.get_backend_session(profile)
@@ -20244,6 +20827,154 @@ def _chart_item_dataset_source_type(item: dict[str, Any]) -> str:
20244
20827
  return ""
20245
20828
 
20246
20829
 
20830
+ def _compile_portal_global_config(raw: dict[str, Any] | None) -> dict[str, Any]:
20831
+ """Compile declaration-named global_config keys to backend dashGlobalConfig keys."""
20832
+ config: dict[str, Any] = dict(raw or {})
20833
+ if "auto_refresh" in config:
20834
+ config["beingAutoRefresh"] = config.pop("auto_refresh")
20835
+ if "export" in config:
20836
+ config["beingExport"] = config.pop("export")
20837
+ return config
20838
+
20839
+
20840
+ def _compile_portal_view_display(raw: dict[str, Any] | None) -> dict[str, Any]:
20841
+ """Compile declaration view_display keys to backend viewgraphConfig keys."""
20842
+ display: dict[str, Any] = {}
20843
+ payload = raw or {}
20844
+ if "show_title" in payload:
20845
+ display["beingShowTitle"] = bool(payload["show_title"])
20846
+ elif "beingShowTitle" in payload:
20847
+ display["beingShowTitle"] = bool(payload["beingShowTitle"])
20848
+ if payload.get("component_title") or payload.get("componentTitle"):
20849
+ display["componentTitle"] = str(payload.get("component_title") or payload.get("componentTitle"))
20850
+ return display
20851
+
20852
+
20853
+ def _compile_portal_task_config(section_title: str, raw: dict[str, Any]) -> dict[str, Any]:
20854
+ """Compile a task section declaration into the backend taskConfig shape."""
20855
+ payload = raw or {}
20856
+ task_config: dict[str, Any] = {
20857
+ "componentTaskTitle": section_title,
20858
+ }
20859
+ if "show_title" in payload:
20860
+ task_config["beingShowTitle"] = bool(payload["show_title"])
20861
+ elif "beingShowTitle" in payload:
20862
+ task_config["beingShowTitle"] = bool(payload["beingShowTitle"])
20863
+ if "hint" in payload or "componentTaskHint" in payload:
20864
+ task_config["componentTaskHint"] = str(payload.get("hint") or payload.get("componentTaskHint") or "")
20865
+ if "show_hint" in payload:
20866
+ task_config["beingShowHint"] = bool(payload["show_hint"])
20867
+ elif "beingShowHint" in payload:
20868
+ task_config["beingShowHint"] = bool(payload["beingShowHint"])
20869
+ if "enabled" in payload:
20870
+ task_config["beingUsing"] = bool(payload["enabled"])
20871
+ elif "beingUsing" in payload:
20872
+ task_config["beingUsing"] = bool(payload["beingUsing"])
20873
+ raw_tasks = payload.get("tasks")
20874
+ if isinstance(raw_tasks, list) and raw_tasks:
20875
+ task_items: list[dict[str, Any]] = []
20876
+ for index, raw_item in enumerate(raw_tasks):
20877
+ if not isinstance(raw_item, dict):
20878
+ continue
20879
+ item: dict[str, Any] = {
20880
+ "title": str(raw_item.get("title") or ""),
20881
+ "type": _coerce_positive_int(raw_item.get("task_type") or raw_item.get("type")) or 1,
20882
+ "ordinal": _coerce_positive_int(raw_item.get("ordinal")) or index,
20883
+ "beingCheck": bool(raw_item.get("checked", raw_item.get("beingCheck", False))),
20884
+ }
20885
+ task_items.append(item)
20886
+ if task_items:
20887
+ task_config["dashTaskConfigList"] = task_items
20888
+ # dashTaskConfigList 必须始终携带:后端 DashTaskSvcImpl#addTaskInfos 对
20889
+ # taskConfig.getDashTaskConfigList() 直接迭代(ComponentTaskConfig 字段无默认
20890
+ # 初始化),键缺失 → null.size() NPE → 500(实测反馈「task 组件无论如何 500」
20891
+ # 根因)。声明未表达 tasks 时按前端新建缺省补 4 类标准任务(title 用后端 i18n 键,
20892
+ # 与存量/前端缺省一致);提取侧读面恒有条目,round-trip 不受影响。
20893
+ if not task_config.get("dashTaskConfigList"):
20894
+ task_config["dashTaskConfigList"] = [
20895
+ {"title": "all.taskTodo", "type": 1, "ordinal": 0, "beingCheck": True},
20896
+ {"title": "all.taskTimeout", "type": 2, "ordinal": 1, "beingCheck": True},
20897
+ {"title": "all.taskUpcomingTimeout", "type": 3, "ordinal": 2, "beingCheck": True},
20898
+ {"title": "all.taskRemind", "type": 4, "ordinal": 3, "beingCheck": True},
20899
+ ]
20900
+ return task_config
20901
+
20902
+
20903
+ def _compile_portal_filter_config(raw: dict[str, Any] | None) -> dict[str, Any]:
20904
+ """Compile a filter section config into the backend ComponentFilter shape.
20905
+
20906
+ Declaration form: ``{graphs: [{chart_key, chart_name}], rules: [...]}``.
20907
+ Legacy raw form (``{graphList: [...], filterConfig: [...]}`` 后端键) 透传兼容。
20908
+ """
20909
+ payload = raw or {}
20910
+ compiled: dict[str, Any] = {}
20911
+ raw_graphs = payload.get("graphs")
20912
+ if isinstance(raw_graphs, list):
20913
+ graph_list: list[dict[str, Any]] = []
20914
+ for item in raw_graphs:
20915
+ if not isinstance(item, dict):
20916
+ continue
20917
+ graph: dict[str, Any] = {
20918
+ "graphKey": str(item.get("chart_key") or item.get("chartKey") or item.get("graphKey") or "").strip(),
20919
+ "graphName": str(item.get("chart_name") or item.get("chartName") or item.get("graphName") or "").strip(),
20920
+ "graphType": item.get("graph_type") or item.get("graphType") or "CHART",
20921
+ }
20922
+ if graph["graphKey"] or graph["graphName"]:
20923
+ graph_list.append(graph)
20924
+ compiled["graphList"] = graph_list
20925
+ elif isinstance(payload.get("graphList"), list):
20926
+ compiled["graphList"] = deepcopy(payload.get("graphList"))
20927
+ raw_rules = payload.get("rules")
20928
+ if isinstance(raw_rules, list):
20929
+ compiled["filterConfig"] = deepcopy(raw_rules)
20930
+ elif isinstance(payload.get("filterConfig"), list):
20931
+ compiled["filterConfig"] = deepcopy(payload.get("filterConfig"))
20932
+ return compiled
20933
+
20934
+
20935
+ def _compile_portal_favourite_config(section_title: str, raw: dict[str, Any]) -> dict[str, Any]:
20936
+ """Compile a favourite section declaration into the backend favouriteConfig shape."""
20937
+ payload = raw or {}
20938
+ favourite_config: dict[str, Any] = {
20939
+ "favouriteTitle": section_title,
20940
+ }
20941
+ if "show_title" in payload:
20942
+ favourite_config["beingShowTitle"] = bool(payload["show_title"])
20943
+ elif "beingShowTitle" in payload:
20944
+ favourite_config["beingShowTitle"] = bool(payload["beingShowTitle"])
20945
+ if "enabled" in payload:
20946
+ favourite_config["beingUsing"] = bool(payload["enabled"])
20947
+ elif "beingUsing" in payload:
20948
+ favourite_config["beingUsing"] = bool(payload["beingUsing"])
20949
+ raw_items = payload.get("items")
20950
+ if isinstance(raw_items, list) and raw_items:
20951
+ favourite_items: list[dict[str, Any]] = []
20952
+ for index, raw_item in enumerate(raw_items):
20953
+ if not isinstance(raw_item, dict):
20954
+ continue
20955
+ item: dict[str, Any] = {
20956
+ "title": str(raw_item.get("title") or ""),
20957
+ "type": _coerce_positive_int(raw_item.get("item_type") or raw_item.get("type")) or 1,
20958
+ "ordinal": _coerce_positive_int(raw_item.get("ordinal")) or index,
20959
+ }
20960
+ link_key = str(raw_item.get("link_key") or raw_item.get("linkKey") or "").strip()
20961
+ if link_key:
20962
+ item["linkKey"] = link_key
20963
+ link_id = _coerce_positive_int(raw_item.get("link_id") or raw_item.get("linkId"))
20964
+ if link_id is not None:
20965
+ item["linkId"] = link_id
20966
+ icon_url = str(raw_item.get("icon_url") or raw_item.get("iconUrl") or "").strip()
20967
+ if icon_url:
20968
+ item["iconUrl"] = icon_url
20969
+ jump_mode = _coerce_positive_int(raw_item.get("jump_mode") or raw_item.get("jumpMode"))
20970
+ if jump_mode is not None:
20971
+ item["jumpMode"] = jump_mode
20972
+ favourite_items.append(item)
20973
+ if favourite_items:
20974
+ favourite_config["items"] = favourite_items
20975
+ return favourite_config
20976
+
20977
+
20247
20978
  def _build_public_portal_base_payload(
20248
20979
  *,
20249
20980
  dash_name: str,
@@ -20253,19 +20984,49 @@ def _build_public_portal_base_payload(
20253
20984
  auth: dict[str, Any] | None,
20254
20985
  hide_copyright: bool | None,
20255
20986
  dash_global_config: dict[str, Any] | None,
20987
+ style_template_id: int | None = None,
20988
+ overall_style: dict[str, Any] | None = None,
20256
20989
  config: dict[str, Any] | None,
20257
20990
  base_payload: dict[str, Any] | None,
20258
20991
  ) -> dict[str, Any]:
20259
20992
  data = deepcopy(base_payload) if isinstance(base_payload, dict) else {}
20260
- effective_name = str(dash_name or data.get("dashName") or "").strip() or "未命名门户"
20993
+ # dash_name 语义:None=未指定(沿用 base_payload 读面名,缺省再回落未命名门户);
20994
+ # 空串=显式空名(后端 dash_name 允许空串,生产存量存在;round-trip 保真必须透传)。
20995
+ if dash_name is not None:
20996
+ effective_name = str(dash_name).strip()
20997
+ else:
20998
+ effective_name = str(data.get("dashName") or "").strip() or "未命名门户"
20261
20999
  effective_hide_copyright = hide_copyright if hide_copyright is not None else bool(data.get("hideCopyright", False))
20262
- if icon or color or not data.get("dashIcon"):
21000
+ # dashIcon round-trip 保真(r4 全量实测「默认值补写」修复):
21001
+ # - 声明显式给 icon/color → 重编码(存量形态走最小 patch);
21002
+ # - 声明未指定 + 创建语义(base_payload 无) → 合成默认(创建行为不变);
21003
+ # - 声明未指定 + 更新语义 → 不碰 dashIcon:存量有则保留原值,存量空则**不合成**。
21004
+ # 后端 updateDashBaseInfo 对 dashIcon 无校验直接透传;合成默认会让「B0 无图标」
21005
+ # 门户在 apply 后长出默认图标/默认色(r4 实测 50 处 color diff 根因)。
21006
+ if icon or color:
21007
+ if base_payload is not None and isinstance(base_payload.get("dashIcon"), str):
21008
+ data["dashIcon"] = update_workspace_icon_from_existing(
21009
+ icon=icon,
21010
+ color=color,
21011
+ title=effective_name,
21012
+ existing_icon=str(data.get("dashIcon") or "").strip() or None,
21013
+ fallback_icon_name="view-grid",
21014
+ )
21015
+ else:
21016
+ data["dashIcon"] = encode_workspace_icon_with_defaults(
21017
+ icon=icon,
21018
+ color=color,
21019
+ title=effective_name,
21020
+ fallback_icon_name="view-grid",
21021
+ existing_icon=str(data.get("dashIcon") or "").strip() or None,
21022
+ )
21023
+ elif base_payload is None:
20263
21024
  data["dashIcon"] = encode_workspace_icon_with_defaults(
20264
- icon=icon,
20265
- color=color,
21025
+ icon=None,
21026
+ color=None,
20266
21027
  title=effective_name,
20267
21028
  fallback_icon_name="view-grid",
20268
- existing_icon=str(data.get("dashIcon") or "").strip() or None,
21029
+ existing_icon=None,
20269
21030
  )
20270
21031
  data["dashName"] = effective_name
20271
21032
  data["auth"] = deepcopy(auth if auth is not None else data.get("auth") or default_member_auth())
@@ -20275,10 +21036,15 @@ def _build_public_portal_base_payload(
20275
21036
  elif "tags" not in data:
20276
21037
  data["tags"] = []
20277
21038
  global_config = deepcopy(dash_global_config if isinstance(dash_global_config, dict) else data.get("dashGlobalConfig") or {})
21039
+ global_config = _compile_portal_global_config(global_config)
20278
21040
  global_config.pop("layout", None)
20279
21041
  global_config["interval"] = global_config.get("interval") or 60
20280
21042
  global_config["beingAutoRefresh"] = bool(global_config.get("beingAutoRefresh", False))
20281
21043
  data["dashGlobalConfig"] = global_config
21044
+ if style_template_id is not None:
21045
+ data["styleTemplateId"] = style_template_id
21046
+ if overall_style is not None:
21047
+ data["overallConfigBO"] = deepcopy(overall_style)
20282
21048
  if isinstance(config, dict):
20283
21049
  data.update(deepcopy(config))
20284
21050
  return data
@@ -20384,18 +21150,37 @@ def _find_chart_by_name(items: Any, *, chart_name: str, chart_type: str | None =
20384
21150
 
20385
21151
  def _portal_position_payload(position: Any, *, inferred_mobile_y: int = 0) -> dict[str, Any]:
20386
21152
  mobile_provided = bool(getattr(position, "mobile_provided", False))
20387
- mobile_rows = int(getattr(position, "mobile_h", 8)) if mobile_provided else int(getattr(position, "pc_h", 8))
21153
+
21154
+ def _coord(raw: Any, *, explicit: bool, default: int) -> int | None:
21155
+ # explicit=False(mobile 未提供):忽略模型默认值,沿用调用方 default(布局推断),
21156
+ # 与旧实现 `int(v) if provided else default` 行为一致;
21157
+ # explicit=True:显式 null 原样透传(后端 DashPosition null 语义,筛选组件等原生
21158
+ # NULL 位置读写链双向透传),仅键缺省时才回落布局默认值。
21159
+ if not explicit:
21160
+ return default
21161
+ if raw is None:
21162
+ return None
21163
+ return int(raw)
21164
+
21165
+ mobile_h_raw = getattr(position, "mobile_h", None) if mobile_provided else None
21166
+ pc_h_raw = getattr(position, "pc_h", None)
21167
+ if mobile_provided:
21168
+ # mobile 显式提供:rows 以 mobile_h 为准,null 透传(后端语义)
21169
+ mobile_rows = None if mobile_h_raw is None else int(mobile_h_raw)
21170
+ else:
21171
+ # mobile 未提供:rows 跟随 pc 高度(与旧实现一致);pc_h 显式 null 时回落布局默认 8
21172
+ mobile_rows = int(pc_h_raw) if pc_h_raw is not None else 8
20388
21173
  return {
20389
21174
  "pc": {
20390
- "x": int(getattr(position, "pc_x", 0)),
20391
- "y": int(getattr(position, "pc_y", 0)),
20392
- "cols": int(getattr(position, "pc_w", 12)),
20393
- "rows": int(getattr(position, "pc_h", 8)),
21175
+ "x": _coord(getattr(position, "pc_x", None), explicit=True, default=0),
21176
+ "y": _coord(getattr(position, "pc_y", None), explicit=True, default=0),
21177
+ "cols": _coord(getattr(position, "pc_w", None), explicit=True, default=12),
21178
+ "rows": _coord(getattr(position, "pc_h", None), explicit=True, default=8),
20394
21179
  },
20395
21180
  "mobile": {
20396
- "x": int(getattr(position, "mobile_x", 0)) if mobile_provided else 0,
20397
- "y": int(getattr(position, "mobile_y", 0)) if mobile_provided else int(inferred_mobile_y),
20398
- "cols": int(getattr(position, "mobile_w", 6)) if mobile_provided else 6,
21181
+ "x": _coord(getattr(position, "mobile_x", None), explicit=mobile_provided, default=0),
21182
+ "y": _coord(getattr(position, "mobile_y", None), explicit=mobile_provided, default=inferred_mobile_y),
21183
+ "cols": _coord(getattr(position, "mobile_w", None), explicit=mobile_provided, default=6),
20399
21184
  "rows": mobile_rows,
20400
21185
  },
20401
21186
  }
@@ -20426,6 +21211,15 @@ def _portal_component_position_public(
20426
21211
  elif source_name == "link":
20427
21212
  cols = 12
20428
21213
  rows = 2
21214
+ elif source_name == "carousel":
21215
+ cols = 24
21216
+ rows = 7
21217
+ elif source_name == "task":
21218
+ cols = 12
21219
+ rows = 8
21220
+ elif source_name == "favourite":
21221
+ cols = 12
21222
+ rows = 6
20429
21223
  else:
20430
21224
  if layout_preset == "dashboard_2col":
20431
21225
  cols = 12
@@ -23237,6 +24031,23 @@ def _apply_field_mutation(field: dict[str, Any], mutation: Any) -> None:
23237
24031
  field.pop("_question_rebuild_required", None)
23238
24032
 
23239
24033
 
24034
+ class AmbiguousFieldSelector(ValueError):
24035
+ """name-only selector 命中多个同名字段。
24036
+
24037
+ 方案 A(duplicate-field-name):后端以 queId 为字段身份、允许同父级同名;
24038
+ name 命中多个字段时禁止静默取第一个,必须显式失败并给出候选 queId。
24039
+ compiler 包装层(app_form)把它转写为 AMBIGUOUS_FIELD_SELECTOR 错误码。
24040
+ """
24041
+
24042
+ def __init__(self, location: str, candidates: list[int]) -> None:
24043
+ self.location = location
24044
+ self.candidates = candidates
24045
+ super().__init__(
24046
+ f"{location} matches multiple fields with the same name; "
24047
+ f"use queId to disambiguate (candidate queIds: {sorted(candidates)})"
24048
+ )
24049
+
24050
+
23240
24051
  def _resolve_field_selector_with_uniqueness(
23241
24052
  *,
23242
24053
  fields: list[dict[str, Any]],
@@ -23252,7 +24063,12 @@ def _resolve_field_selector_with_uniqueness(
23252
24063
  name = str(selector.name or "").strip()
23253
24064
  matched = [field for field in fields if str(field.get("name") or "").strip() == name]
23254
24065
  if len(matched) > 1:
23255
- raise ValueError(f"{location} matched multiple fields with the same name; use field_id or que_id")
24066
+ candidate_ids = [
24067
+ ref
24068
+ for candidate in matched
24069
+ if (ref := _coerce_any_int(candidate.get("que_id"))) is not None
24070
+ ]
24071
+ raise AmbiguousFieldSelector(location, candidate_ids)
23256
24072
  else:
23257
24073
  matched = []
23258
24074
  if len(matched) != 1:
@@ -23554,6 +24370,24 @@ def _ensure_field_temp_ids(fields: list[dict[str, Any]]) -> None:
23554
24370
  temp_id -= 100
23555
24371
 
23556
24372
 
24373
+ def _field_index_by_ref(fields: list[dict[str, Any]]) -> dict[int, dict[str, Any]]:
24374
+ """按稳定引用(que_id,新字段退化 que_temp_id)建索引——方案 A 同名场景
24375
+ 下 by_name 会把不同 queId 的同名字段折叠成一个,relation 目标错位(实测
24376
+ a9lfp40imk02:两个同名 code_block 各自输出到同名不同 queId 的 text 字段,
24377
+ by_name 把两条 relation 撞到同一目标,触发 multiple default-value relations)。
24378
+ """
24379
+ index: dict[int, dict[str, Any]] = {}
24380
+ for field in fields:
24381
+ if not isinstance(field, dict):
24382
+ continue
24383
+ ref = _coerce_positive_int(field.get("que_id"))
24384
+ if ref is None:
24385
+ ref = _coerce_any_int(field.get("que_temp_id"))
24386
+ if ref is not None and ref not in index:
24387
+ index[ref] = field
24388
+ return index
24389
+
24390
+
23557
24391
  def _compile_code_block_binding_fields(
23558
24392
  *,
23559
24393
  fields: list[dict[str, Any]],
@@ -23566,6 +24400,7 @@ def _compile_code_block_binding_fields(
23566
24400
  for field in next_fields
23567
24401
  if isinstance(field, dict) and str(field.get("name") or "")
23568
24402
  }
24403
+ by_ref = _field_index_by_ref(next_fields)
23569
24404
  existing_relations = current_schema.get("questionRelations") if isinstance(current_schema.get("questionRelations"), list) else []
23570
24405
  relation_specs: list[dict[str, Any]] = []
23571
24406
  affected_source_refs: set[int] = set()
@@ -23681,7 +24516,12 @@ def _compile_code_block_binding_fields(
23681
24516
  target_payload = output_item.get("target_field")
23682
24517
  if not isinstance(target_payload, dict):
23683
24518
  continue
23684
- target_field = by_name.get(str(target_payload.get("name") or ""))
24519
+ # 编译产物 target_field 已带按 queId 唯一解析出的 que_id(同名字段
24520
+ # 不折叠);以 ref 定位目标,que_id 缺失(新字段 temp 形态)才退化
24521
+ # by_name——by_name 对同名目标会错位到任意一个同名字段。
24522
+ target_field = by_ref.get(_coerce_any_int(target_payload.get("que_id")) or -1)
24523
+ if not isinstance(target_field, dict):
24524
+ target_field = by_name.get(str(target_payload.get("name") or ""))
23685
24525
  if not isinstance(target_field, dict):
23686
24526
  continue
23687
24527
  target_ref = _coerce_positive_int(target_field.get("que_id"))
@@ -23749,6 +24589,7 @@ def _materialize_code_block_question_relations(
23749
24589
  relation_specs: list[dict[str, Any]],
23750
24590
  ) -> list[dict[str, Any]]:
23751
24591
  by_name = {str(field.get("name") or ""): field for field in fields if isinstance(field, dict) and str(field.get("name") or "")}
24592
+ by_ref = _field_index_by_ref(fields)
23752
24593
  materialized: list[dict[str, Any]] = []
23753
24594
  for relation in relation_specs:
23754
24595
  if not isinstance(relation, dict):
@@ -23756,8 +24597,15 @@ def _materialize_code_block_question_relations(
23756
24597
  if _coerce_positive_int(relation.get("relationType")) == RELATION_TYPE_CODE_BLOCK:
23757
24598
  materialized.append(deepcopy(relation))
23758
24599
  continue
23759
- source_field = by_name.get(str(relation.get("source_field_name") or ""))
23760
- target_field = by_name.get(str(relation.get("target_field_name") or ""))
24600
+ # relation_spec 的 *_field_ref 来自编译期按 queId 唯一解析的结果,优先
24601
+ # 以 ref 定位源/目标字段;ref 缺失(新字段 temp 形态)退化 by_name——
24602
+ # 同名字段场景 by_name 会折叠错位(与 _compile_* 侧同口径)。
24603
+ source_field = by_ref.get(_coerce_any_int(relation.get("source_field_ref")) or -1)
24604
+ if not isinstance(source_field, dict):
24605
+ source_field = by_name.get(str(relation.get("source_field_name") or ""))
24606
+ target_field = by_ref.get(_coerce_any_int(relation.get("target_field_ref")) or -1)
24607
+ if not isinstance(target_field, dict):
24608
+ target_field = by_name.get(str(relation.get("target_field_name") or ""))
23761
24609
  if not isinstance(source_field, dict) or not isinstance(target_field, dict):
23762
24610
  continue
23763
24611
  source_ref = _coerce_positive_int(source_field.get("que_id"))
@@ -23881,6 +24729,7 @@ def _compile_q_linker_binding_fields(
23881
24729
  for field in next_fields
23882
24730
  if isinstance(field, dict) and str(field.get("name") or "")
23883
24731
  }
24732
+ by_ref = _field_index_by_ref(next_fields)
23884
24733
  existing_relations = current_schema.get("questionRelations") if isinstance(current_schema.get("questionRelations"), list) else []
23885
24734
  relation_specs: list[dict[str, Any]] = []
23886
24735
  affected_source_refs: set[int] = set()
@@ -23977,21 +24826,39 @@ def _compile_q_linker_binding_fields(
23977
24826
  compiled_json_value = None if request.get("json_value") is None else str(request.get("json_value") or "")
23978
24827
  compiled_xml_value = None if request.get("xml_value") is None else str(request.get("xml_value") or "")
23979
24828
  for index, input_item in enumerate(cast(list[dict[str, Any]], binding.get("inputs") or [])):
23980
- source_field = _resolve_field_selector_with_uniqueness(
23981
- fields=next_fields,
23982
- selector_payload=cast(dict[str, Any], input_item.get("field") or {}),
23983
- location=f"q_linker_binding.inputs[{index}].field",
23984
- )
23985
- source_que_id = _coerce_positive_int(source_field.get("que_id"))
23986
- if source_que_id is None:
23987
- source_que_id = _coerce_any_int(source_field.get("que_temp_id"))
24829
+ selector_payload = cast(dict[str, Any], input_item.get("field") or {})
24830
+ declared_que_id = _coerce_positive_int(selector_payload.get("que_id"))
24831
+ declared_name = str(selector_payload.get("name") or "").strip()
24832
+ try:
24833
+ source_field = _resolve_field_selector_with_uniqueness(
24834
+ fields=next_fields,
24835
+ selector_payload=selector_payload,
24836
+ location=f"q_linker_binding.inputs[{index}].field",
24837
+ )
24838
+ except AmbiguousFieldSelector:
24839
+ raise
24840
+ except ValueError:
24841
+ if declared_que_id is None:
24842
+ raise
24843
+ # 透传:queId 已锚定但字段不在当前表单(存量悬空/改名引用)——后端
24844
+ # 写链对 params_que_id 无存在性校验,按声明 queId 直写,名称用声明名
24845
+ source_field = None
24846
+ if source_field is None:
24847
+ source_que_id = declared_que_id
24848
+ else:
24849
+ source_que_id = _coerce_positive_int(source_field.get("que_id"))
24850
+ if source_que_id is None:
24851
+ source_que_id = _coerce_any_int(source_field.get("que_temp_id"))
23988
24852
  if source_que_id is None:
23989
- raise ValueError(f"q_linker input field '{source_field.get('name')}' does not have a stable que_id")
24853
+ raise ValueError(f"q_linker input field '{declared_name or (source_field or {}).get('name')}' does not have a stable que_id")
24854
+ # 引用重组优先用声明名:B0 模板引用名与当前字段名可能不同(存量字段名
24855
+ # 带尾随空格等,如 am4oh08v2401),按解析名重组会改写模板破坏 round-trip
24856
+ compose_name = declared_name or str((source_field or {}).get("name") or "")
23990
24857
  key = str(input_item.get("key") or "").strip()
23991
24858
  source_kind = str(input_item.get("source") or "").strip().lower()
23992
24859
  compiled_inputs.append(
23993
24860
  {
23994
- "field": {"name": source_field.get("name"), "que_id": source_que_id},
24861
+ "field": {"name": compose_name, "que_id": source_que_id},
23995
24862
  "key": key,
23996
24863
  "source": source_kind,
23997
24864
  }
@@ -24005,7 +24872,7 @@ def _compile_q_linker_binding_fields(
24005
24872
  compiled_url_encoded.append(kv_item)
24006
24873
  elif source_kind == "json_path":
24007
24874
  token = "{{" + key + "}}"
24008
- reference = _compose_qlinker_value_reference(field_name=str(source_field.get("name") or ""), que_id=source_que_id)
24875
+ reference = _compose_qlinker_value_reference(field_name=compose_name, que_id=source_que_id)
24009
24876
  compiled_url = compiled_url.replace(token, reference)
24010
24877
  if compiled_json_value is not None:
24011
24878
  compiled_json_value = compiled_json_value.replace(token, reference)
@@ -24091,7 +24958,12 @@ def _compile_q_linker_binding_fields(
24091
24958
  target_payload = output_item.get("target_field")
24092
24959
  if not isinstance(target_payload, dict):
24093
24960
  continue
24094
- target_field = by_name.get(str(target_payload.get("name") or ""))
24961
+ # 编译产物 target_field 已带按 queId 唯一解析出的 que_id(同名字段
24962
+ # 不折叠);以 ref 定位目标,que_id 缺失(新字段 temp 形态)才退化
24963
+ # by_name——by_name 对同名目标会错位到任意一个同名字段。
24964
+ target_field = by_ref.get(_coerce_any_int(target_payload.get("que_id")) or -1)
24965
+ if not isinstance(target_field, dict):
24966
+ target_field = by_name.get(str(target_payload.get("name") or ""))
24095
24967
  if not isinstance(target_field, dict):
24096
24968
  continue
24097
24969
  target_ref = _coerce_positive_int(target_field.get("que_id"))
@@ -24149,12 +25021,20 @@ def _materialize_q_linker_question_relations(
24149
25021
  relation_specs: list[dict[str, Any]],
24150
25022
  ) -> list[dict[str, Any]]:
24151
25023
  by_name = {str(field.get("name") or ""): field for field in fields if isinstance(field, dict) and str(field.get("name") or "")}
25024
+ by_ref = _field_index_by_ref(fields)
24152
25025
  materialized: list[dict[str, Any]] = []
24153
25026
  for relation in relation_specs:
24154
25027
  if not isinstance(relation, dict):
24155
25028
  continue
24156
- source_field = by_name.get(str(relation.get("source_field_name") or ""))
24157
- target_field = by_name.get(str(relation.get("target_field_name") or ""))
25029
+ # relation_spec 的 *_field_ref 来自编译期按 queId 唯一解析的结果,优先
25030
+ # 以 ref 定位源/目标字段;ref 缺失(新字段 temp 形态)退化 by_name——
25031
+ # 同名字段场景 by_name 会折叠错位(与 _compile_* 侧同口径)。
25032
+ source_field = by_ref.get(_coerce_any_int(relation.get("source_field_ref")) or -1)
25033
+ if not isinstance(source_field, dict):
25034
+ source_field = by_name.get(str(relation.get("source_field_name") or ""))
25035
+ target_field = by_ref.get(_coerce_any_int(relation.get("target_field_ref")) or -1)
25036
+ if not isinstance(target_field, dict):
25037
+ target_field = by_name.get(str(relation.get("target_field_name") or ""))
24158
25038
  if not isinstance(source_field, dict) or not isinstance(target_field, dict):
24159
25039
  continue
24160
25040
  source_ref = _coerce_positive_int(source_field.get("que_id"))
@@ -27784,6 +28664,385 @@ def _normalize_portal_components(components: Any) -> list[dict[str, Any]]:
27784
28664
  return items
27785
28665
 
27786
28666
 
28667
+ def _portal_component_source_type_by_backend(value: Any) -> str:
28668
+ raw = value if isinstance(value, (int, str)) else str(value or "").strip()
28669
+ mapping = {
28670
+ 1: "chart",
28671
+ 2: "grid",
28672
+ 3: "carousel",
28673
+ 4: "link",
28674
+ 5: "text",
28675
+ 6: "filter",
28676
+ 7: "favourite",
28677
+ 8: "task",
28678
+ 9: "chart",
28679
+ 10: "view",
28680
+ }
28681
+ if isinstance(raw, int):
28682
+ return mapping.get(raw, "unknown")
28683
+ raw_str = str(raw or "").strip()
28684
+ if raw_str.isdigit():
28685
+ return mapping.get(int(raw_str), "unknown")
28686
+ return _normalize_portal_component_source_type(raw)
28687
+
28688
+
28689
+ def _portal_section_from_component(
28690
+ component: dict[str, Any],
28691
+ *,
28692
+ index: int,
28693
+ complete: bool,
28694
+ ) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
28695
+ """Reverse-compile one DashComponentInfo into a canonical section."""
28696
+ source_type = _portal_component_source_type_by_backend(component.get("type"))
28697
+ config_key_map = {
28698
+ "grid": "gridConfig",
28699
+ "link": "linkConfig",
28700
+ "text": "textConfig",
28701
+ "filter": "filterConfig",
28702
+ "chart": "chartConfig",
28703
+ "view": "viewgraphConfig",
28704
+ "carousel": "carouselConfig",
28705
+ "task": "taskConfig",
28706
+ "favourite": "favouriteConfig",
28707
+ }
28708
+ if source_type == "unknown":
28709
+ return None, {
28710
+ "index": index,
28711
+ "code": "UNKNOWN_COMPONENT_TYPE",
28712
+ "message": f"component type {component.get('type')} is not part of the portals declaration contract",
28713
+ "blocking_field": "source_type",
28714
+ }
28715
+ config = component.get(config_key_map.get(source_type, "")) if isinstance(component.get(config_key_map.get(source_type, "")), dict) else {}
28716
+ section: dict[str, Any] = {"source_type": source_type}
28717
+ title = _extract_portal_component_title(component, source_type=source_type)
28718
+ gaps: list[dict[str, Any]] = []
28719
+ if source_type == "carousel":
28720
+ title = str(config.get("sourceApp", {}).get("formTitle") or "").strip() or f"轮播 {index + 1}"
28721
+ elif source_type == "task":
28722
+ title = str(config.get("componentTaskTitle") or f"待办 {index + 1}")
28723
+ elif source_type == "favourite":
28724
+ title = str(config.get("favouriteTitle") or f"收藏 {index + 1}")
28725
+ # chart/grid/view 的 title 语义=组件显示标题(component_title/grid_title 落库列),
28726
+ # 生产存量大量存在「显示标题开但标题空」形态(读链渲染时回退图表名/视图名):
28727
+ # 合成「组件 N」会把不存在的标题落库(读链 chartName 派生被覆盖 + 库表漂移),
28728
+ # 如实保留 None(编译不落库,round-trip 保真)。carousel/task/favourite 的
28729
+ # 读面自有真名回填(formTitle/componentTaskTitle/favouriteTitle),其合成兑底保留。
28730
+ # filter 同样不合成:后端 addComponentInfos 对筛选组件不落任何标题(无标题存储),
28731
+ # 读面按代理键 HashMap 迭代序返回——合成「组件 {index+1}」的标签是列表序号的
28732
+ # 函数,apply 删重建致代理键位移后标题跟着置换(r6 幂等差 3 的唯一根因)。
28733
+ if source_type not in {"chart", "grid", "view", "filter"}:
28734
+ title = title or f"组件 {index + 1}"
28735
+ section["title"] = title
28736
+ if source_type in {"chart", "view"} and complete:
28737
+ # beingShowTitle 落库列(draft_dash_chart.being_show_title):读面必有值;
28738
+ # 提取必须保真(存量 false 被「硬编码 True」覆写会漂移库表)。grid 的开关
28739
+ # 在 grid_config.beingShowTitle 键内随 config 保留,无需单独建模。
28740
+ if "beingShowTitle" in config:
28741
+ section["show_title"] = bool(config.get("beingShowTitle"))
28742
+ position = component.get("position")
28743
+ if isinstance(position, dict) and position:
28744
+ section["position"] = deepcopy(position)
28745
+ if complete:
28746
+ style = component.get("dashStyleConfigBO")
28747
+ if isinstance(style, dict) and style:
28748
+ section["style_config"] = deepcopy(style)
28749
+ if source_type == "chart":
28750
+ # 后端两类图表组件引用面不同(DashSvcImpl 写链):type=1 轻流报表锚 chart 表唯一键
28751
+ # chartKey(addChartInfos);type=9 轻析 BI 报表锚 bi_chart 整型 chart_id(addBiChartInfo)。
28752
+ # 提取时以读面 type 判别 ref_kind,保证 apply 回写同一引用面。
28753
+ backend_type = component.get("type")
28754
+ is_qingflow_chart = backend_type == 1 or (
28755
+ backend_type != 9 and str(config.get("chartKey") or "").strip() and not config.get("biChartId")
28756
+ )
28757
+ if is_qingflow_chart:
28758
+ chart_ref: dict[str, Any] = {
28759
+ "ref_kind": "chart",
28760
+ "chart_id": str(config.get("chartKey") or "").strip() or None,
28761
+ "chart_name": str(config.get("chartName") or title or "").strip() or None,
28762
+ }
28763
+ else:
28764
+ chart_ref = {
28765
+ "chart_id": str(config.get("biChartId") or "").strip() or None,
28766
+ "chart_name": str(config.get("chartComponentTitle") or title or "").strip() or None,
28767
+ }
28768
+ chart_ref = {key: value for key, value in chart_ref.items() if value is not None}
28769
+ if not chart_ref.get("chart_id"):
28770
+ gaps.append({
28771
+ "index": index,
28772
+ "code": "CHART_REF_MISSING",
28773
+ "message": "chart component has no chartKey/biChartId in the read face",
28774
+ "blocking_field": "chart_ref.chart_id",
28775
+ })
28776
+ return None, gaps[0]
28777
+ section["chart_ref"] = chart_ref
28778
+ elif source_type == "view":
28779
+ view_ref: dict[str, Any] = {
28780
+ "app_key": str(config.get("appKey") or "").strip() or None,
28781
+ "view_key": str(config.get("viewgraphKey") or "").strip() or None,
28782
+ "view_name": str(config.get("viewgraphName") or title or "").strip() or None,
28783
+ }
28784
+ view_ref = {key: value for key, value in view_ref.items() if value is not None}
28785
+ if not view_ref.get("view_key"):
28786
+ gaps.append({
28787
+ "index": index,
28788
+ "code": "VIEW_REF_MISSING",
28789
+ "message": "view component has no viewgraphKey in the read face",
28790
+ "blocking_field": "view_ref.view_key",
28791
+ })
28792
+ return None, gaps[0]
28793
+ section["view_ref"] = view_ref
28794
+ if complete and ("beingShowTitle" in config or config.get("componentTitle")):
28795
+ display: dict[str, Any] = {}
28796
+ if "beingShowTitle" in config:
28797
+ display["show_title"] = bool(config.get("beingShowTitle"))
28798
+ if config.get("componentTitle"):
28799
+ display["component_title"] = str(config.get("componentTitle"))
28800
+ if display:
28801
+ section["view_display"] = display
28802
+ elif source_type == "grid":
28803
+ grid_config: dict[str, Any] = {}
28804
+ for key in ("gridTitle", "beingShowTitle", "items"):
28805
+ if key in config:
28806
+ grid_config[key] = deepcopy(config.get(key))
28807
+ if isinstance(grid_config.get("items"), list):
28808
+ # 归一到声明规范键集(DraftComponentGridItem 落库列 + 读面派生 title):
28809
+ # 丢弃运行态/代理键(id/gridId/beingShowTitle/beingTrial/trialExpireDate——
28810
+ # 前者是自增代理键(比对器另剔),后两者读面运行态不入库,title/iconUrl 由
28811
+ # setTitleAndIconByType 按引用派生);空 title 条目仍过滤(后端读面同型)。
28812
+ kept_item_keys = {
28813
+ "type", "jumpMode", "linkAppKey", "linkFormType", "linkDashKey",
28814
+ "linkTagId", "linkUrl", "title", "customTitle", "beingCustomTitle",
28815
+ "iconUrl", "ordinal",
28816
+ }
28817
+ normalized_items: list[dict[str, Any]] = []
28818
+ for item in grid_config["items"]:
28819
+ if not isinstance(item, dict) or not str(item.get("title") or "").strip():
28820
+ continue
28821
+ normalized = {
28822
+ key: deepcopy(value)
28823
+ for key, value in item.items()
28824
+ if key in kept_item_keys and value is not None
28825
+ }
28826
+ # iconUrl 语义按条目类型分裂(Java ComponentGridItemInfo#setTitleAndIconByType):
28827
+ # type 1/2/3(应用/门户/应用包)的 iconUrl 与 title 是读面按引用目标当前
28828
+ # 图标实时派生的投影——门户声明不拥有也无法保真(写侧不回写生效值),
28829
+ # 提取侧剔除;自定义条目 iconUrl 落库原样读回,保留 round-trip。
28830
+ # 空串 iconUrl 统一剔除(与 favourite 提取对称,消 ""↔缺键不对称)。
28831
+ if _coerce_positive_int(normalized.get("type")) in {1, 2, 3} or not str(normalized.get("iconUrl") or "").strip():
28832
+ normalized.pop("iconUrl", None)
28833
+ normalized_items.append(normalized)
28834
+ grid_config["items"] = normalized_items
28835
+ section["config"] = grid_config
28836
+ elif source_type == "text":
28837
+ section["text"] = str(config.get("text") or "")
28838
+ if complete and config:
28839
+ extra_config = {key: deepcopy(value) for key, value in config.items() if key not in {"text"}}
28840
+ if extra_config:
28841
+ section["config"] = extra_config
28842
+ elif source_type == "link":
28843
+ section["url"] = str(config.get("url") or "")
28844
+ if complete and "beingLoginAuth" in config:
28845
+ section["login_auth"] = bool(config.get("beingLoginAuth"))
28846
+ elif source_type == "filter":
28847
+ graph_list = config.get("graphList") if isinstance(config.get("graphList"), list) else []
28848
+ graphs = [
28849
+ {
28850
+ "chart_key": str(item.get("graphKey") or "").strip() or None,
28851
+ "chart_name": str(item.get("graphName") or "").strip() or None,
28852
+ }
28853
+ for item in graph_list
28854
+ if isinstance(item, dict)
28855
+ ]
28856
+ graphs = [
28857
+ {key: value for key, value in item.items() if value is not None}
28858
+ for item in graphs
28859
+ ]
28860
+ rules: list[dict[str, Any]] = []
28861
+ for group in config.get("filterConfig") or []:
28862
+ if not isinstance(group, dict):
28863
+ continue
28864
+ # 剔除后端删除重建的代理键(filterGroupId/filterItemId,自增 id 每次位移,七条约束之六):
28865
+ # 声明级比以此归一,规则语义真源是 filterGroupName/filterItemName/judge 系内容列。
28866
+ rules.append({
28867
+ key: deepcopy(value)
28868
+ for key, value in group.items()
28869
+ if key not in {"filterGroupId"}
28870
+ })
28871
+ for group in rules:
28872
+ for item in group.get("filterGroupConfig") or []:
28873
+ if isinstance(item, dict):
28874
+ item.pop("filterItemId", None)
28875
+ section["config"] = {"graphs": graphs, "rules": rules}
28876
+ elif source_type == "carousel":
28877
+ carousel: dict[str, Any] = {}
28878
+ source_app = config.get("sourceApp") if isinstance(config.get("sourceApp"), dict) else {}
28879
+ if source_app.get("appKey"):
28880
+ carousel["source_app_key"] = str(source_app.get("appKey"))
28881
+ if source_app.get("formTitle"):
28882
+ carousel["source_form_title"] = str(source_app.get("formTitle"))
28883
+ for raw_key, target_key in (("titleQue", "title_field"), ("imageQue", "image_field"), ("linkQue", "link_field")):
28884
+ que = config.get(raw_key) if isinstance(config.get(raw_key), dict) else {}
28885
+ if que.get("queId") is not None:
28886
+ carousel[target_key] = str(que.get("queId"))
28887
+ if "jumpMode" in config:
28888
+ carousel["jump_mode"] = config.get("jumpMode")
28889
+ if "beingScaling" in config:
28890
+ carousel["scaling"] = bool(config.get("beingScaling"))
28891
+ if "showLatestLimit" in config:
28892
+ carousel["show_latest_limit"] = config.get("showLatestLimit")
28893
+ if "scrollInterval" in config:
28894
+ carousel["scroll_interval"] = config.get("scrollInterval")
28895
+ filter_config = config.get("filterConfig")
28896
+ if isinstance(filter_config, list) and filter_config:
28897
+ # ComponentCarouselConfig.filterConfig 是单组 AND 的 MatchRule 列表。
28898
+ # DashSvcImpl#getDashDetail 会补 judgeValueDetails/judgeType;复用门户既有
28899
+ # match-rule 映射,优先以 details 作为选项值真源,避免只回传派生 judgeValues。
28900
+ raw_rules = filter_config[0] if isinstance(filter_config[0], list) else filter_config
28901
+ filters: list[dict[str, Any]] = []
28902
+ for rule in raw_rules:
28903
+ if not isinstance(rule, dict):
28904
+ continue
28905
+ que_id = _coerce_positive_int(rule.get("queId"))
28906
+ if que_id is None:
28907
+ gaps.append({
28908
+ "index": index,
28909
+ "code": "CAROUSEL_FILTER_FIELD_UNRESOLVED",
28910
+ "message": "carousel filter rule has no resolvable queId",
28911
+ "blocking_field": "carousel.filters",
28912
+ })
28913
+ continue
28914
+ field = {"que_id": que_id, "name": str(rule.get("queTitle") or que_id)}
28915
+ values = _public_view_filter_rule_values(rule, field=field)
28916
+ operator = _public_view_filter_operator_from_judge_type(rule.get("judgeType"), values=values)
28917
+ if operator.startswith("judge_type:"):
28918
+ gaps.append({
28919
+ "index": index,
28920
+ "code": "CAROUSEL_FILTER_OPERATOR_UNSUPPORTED",
28921
+ "message": "carousel filter rule judgeType is not expressible in v1alpha1",
28922
+ "blocking_field": "carousel.filters",
28923
+ "judge_type": rule.get("judgeType"),
28924
+ })
28925
+ continue
28926
+ item: dict[str, Any] = {"field_name": str(que_id), "operator": operator}
28927
+ if operator not in {"is_empty", "not_empty"}:
28928
+ item["values"] = values
28929
+ filters.append(item)
28930
+ if filters:
28931
+ carousel["filters"] = filters
28932
+ section["carousel"] = carousel
28933
+ elif source_type == "task":
28934
+ task: dict[str, Any] = {}
28935
+ if "beingShowTitle" in config:
28936
+ task["show_title"] = bool(config.get("beingShowTitle"))
28937
+ if config.get("componentTaskHint") is not None:
28938
+ task["hint"] = str(config.get("componentTaskHint") or "")
28939
+ if "beingShowHint" in config:
28940
+ task["show_hint"] = bool(config.get("beingShowHint"))
28941
+ if "beingUsing" in config:
28942
+ task["enabled"] = bool(config.get("beingUsing"))
28943
+ raw_tasks = config.get("dashTaskConfigList")
28944
+ if isinstance(raw_tasks, list) and raw_tasks:
28945
+ task["tasks"] = [
28946
+ {
28947
+ "title": str(item.get("title") or ""),
28948
+ "task_type": item.get("type"),
28949
+ "ordinal": item.get("ordinal"),
28950
+ "checked": bool(item.get("beingCheck")),
28951
+ }
28952
+ for item in raw_tasks
28953
+ if isinstance(item, dict)
28954
+ ]
28955
+ section["task"] = task
28956
+ elif source_type == "favourite":
28957
+ favourite: dict[str, Any] = {}
28958
+ if "beingShowTitle" in config:
28959
+ favourite["show_title"] = bool(config.get("beingShowTitle"))
28960
+ if "beingUsing" in config:
28961
+ favourite["enabled"] = bool(config.get("beingUsing"))
28962
+ raw_items = config.get("items")
28963
+ if isinstance(raw_items, list) and raw_items:
28964
+ favourite["items"] = [
28965
+ {
28966
+ "title": str(item.get("title") or ""),
28967
+ "item_type": item.get("type"),
28968
+ "link_key": str(item.get("linkKey") or "") or None,
28969
+ "link_id": item.get("linkId"),
28970
+ "icon_url": str(item.get("iconUrl") or "") or None,
28971
+ "jump_mode": item.get("jumpMode"),
28972
+ "ordinal": item.get("ordinal"),
28973
+ }
28974
+ for item in raw_items
28975
+ if isinstance(item, dict)
28976
+ ]
28977
+ favourite["items"] = [
28978
+ {key: value for key, value in item.items() if value is not None}
28979
+ for item in favourite["items"]
28980
+ ]
28981
+ section["favourite"] = favourite
28982
+ return section, (gaps[0] if gaps else None)
28983
+
28984
+
28985
+ def _portal_declaration_from_dash_detail(
28986
+ detail: dict[str, Any],
28987
+ *,
28988
+ schema_kind: str,
28989
+ ) -> tuple[dict[str, Any], list[dict[str, Any]]]:
28990
+ """Reverse-compile a DashDetailInfo read into a canonical portal declaration."""
28991
+ complete = schema_kind == "complete"
28992
+ gaps: list[dict[str, Any]] = []
28993
+ sections: list[dict[str, Any]] = []
28994
+ raw_components = detail.get("components") if isinstance(detail.get("components"), list) else []
28995
+ for index, component in enumerate(raw_components):
28996
+ if not isinstance(component, dict):
28997
+ continue
28998
+ section, gap = _portal_section_from_component(component, index=index, complete=complete)
28999
+ if gap is not None:
29000
+ gaps.append(gap)
29001
+ if section is not None:
29002
+ sections.append(section)
29003
+ declaration: dict[str, Any] = {"sections": sections}
29004
+ # 后端 dash_name 允许空串(生产存量存在,updateDashBaseInfo 无非空校验):
29005
+ # 提取侧始终写出 name 键,空名透传(round-trip 保真),不再把空名当成缺省。
29006
+ declaration["name"] = str(detail.get("dashName") or "").strip()
29007
+ tags = detail.get("tags") if isinstance(detail.get("tags"), list) else []
29008
+ first_tag = tags[0] if tags and isinstance(tags[0], dict) else {}
29009
+ tag_id = _coerce_positive_int(first_tag.get("tagId"))
29010
+ if tag_id is not None:
29011
+ declaration["package_tag_id"] = tag_id
29012
+ if not complete:
29013
+ return declaration, gaps
29014
+ dash_icon = str(detail.get("dashIcon") or "").strip() or None
29015
+ if dash_icon:
29016
+ icon_config = workspace_icon_config(dash_icon)
29017
+ icon = str(icon_config.get("icon_name") or "").strip() or None
29018
+ color = str(icon_config.get("icon_color") or "").strip() or None
29019
+ if icon:
29020
+ declaration["icon"] = icon
29021
+ if color:
29022
+ declaration["color"] = color
29023
+ if "hideCopyright" in detail:
29024
+ declaration["hide_copyright"] = bool(detail.get("hideCopyright"))
29025
+ global_config = detail.get("dashGlobalConfig") if isinstance(detail.get("dashGlobalConfig"), dict) else {}
29026
+ if global_config:
29027
+ declaration["global_config"] = {}
29028
+ if "interval" in global_config:
29029
+ declaration["global_config"]["interval"] = global_config.get("interval")
29030
+ if "beingAutoRefresh" in global_config:
29031
+ declaration["global_config"]["auto_refresh"] = bool(global_config.get("beingAutoRefresh"))
29032
+ if "beingExport" in global_config:
29033
+ declaration["global_config"]["export"] = bool(global_config.get("beingExport"))
29034
+ visibility = _public_visibility_from_member_auth(detail.get("auth"))
29035
+ if isinstance(visibility, dict) and visibility:
29036
+ declaration["visibility"] = visibility
29037
+ style_template_id = _coerce_positive_int(detail.get("styleTemplateId"))
29038
+ if style_template_id is not None:
29039
+ declaration["style_template_id"] = style_template_id
29040
+ overall = detail.get("overallConfigBO")
29041
+ if isinstance(overall, dict) and overall:
29042
+ declaration["overall_style"] = deepcopy(overall)
29043
+ return declaration, gaps
29044
+
29045
+
27787
29046
  def _custom_button_view_configs_from_view_summaries(views: list[dict[str, Any]]) -> list[dict[str, Any]]:
27788
29047
  view_configs: list[dict[str, Any]] = []
27789
29048
  for view in views:
@@ -27937,7 +29196,10 @@ def _extract_portal_component_title(component: dict[str, Any], *, source_type: s
27937
29196
  "text": ["title", "textTitle"],
27938
29197
  "filter": ["title", "filterTitle"],
27939
29198
  "chart": ["chartComponentTitle", "componentTitle", "title"],
27940
- "view": ["componentTitle", "viewgraphName", "title"],
29199
+ # view 的 title 语义=组件显示标题(component_title 落库列,可空);视图名
29200
+ # (viewgraphName)是引用面锚进 view_ref.view_name,不再混入 title 候选
29201
+ # (旧候选把它兑底进 title,编译时覆写 componentTitle 造成库表漂移)。
29202
+ "view": ["componentTitle", "title"],
27941
29203
  }
27942
29204
  for key in title_candidates.get(source_type, []):
27943
29205
  title = str(config.get(key) or "").strip()
@@ -29932,6 +31194,14 @@ def _build_view_update_payload(
29932
31194
  payload["viewgraphType"] = "calendarView"
29933
31195
  payload["beingShowTitleQue"] = True
29934
31196
  payload.pop("groupQueId", None)
31197
+ elif normalized_type == "hierarchy":
31198
+ payload["viewgraphType"] = "hierarchyView"
31199
+ payload["beingShowTitleQue"] = True
31200
+ payload.pop("groupQueId", None)
31201
+ elif normalized_type == "calendar":
31202
+ payload["viewgraphType"] = "calendarView"
31203
+ payload["beingShowTitleQue"] = True
31204
+ payload.pop("groupQueId", None)
29935
31205
  return _hydrate_view_backend_payload(
29936
31206
  payload=payload,
29937
31207
  view_type=normalized_type,
@@ -30491,6 +31761,9 @@ def _translate_view_filter_rule(*, field: dict[str, Any], rule: dict[str, Any])
30491
31761
  elif operator == "in":
30492
31762
  payload["judgeType"] = JUDGE_INCLUDE_ANY if field_type in INCLUDE_ANY_FLOW_FIELD_TYPES else JUDGE_EQUAL_ANY
30493
31763
  payload["judgeValues"] = judge_values
31764
+ elif operator == "belongs_to":
31765
+ payload["judgeType"] = JUDGE_BELONG_TO
31766
+ payload["judgeValues"] = judge_values
30494
31767
  elif operator == "contains":
30495
31768
  payload["judgeType"] = JUDGE_INCLUDE
30496
31769
  payload["judgeValues"] = judge_values[:1] if judge_values else []
@@ -30812,6 +32085,8 @@ def _public_view_filter_operator_from_judge_type(judge_type: Any, *, values: lis
30812
32085
  # ANY 判型+空值 = "该字段未选任何值"的合法存量形态(judgeType 保真回写,
30813
32086
  # 转 is_empty 会丢判型——后端 9 与 0 是不同判定域,实测回读不同)
30814
32087
  return "in"
32088
+ if normalized == JUDGE_BELONG_TO:
32089
+ return "belongs_to"
30815
32090
  if normalized == JUDGE_GREATER_OR_EQUAL:
30816
32091
  return "gte"
30817
32092
  if normalized == JUDGE_LESS_OR_EQUAL: