create-windy 0.2.33 → 0.3.0

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 (284) hide show
  1. package/dist/cli.js +173 -17
  2. package/package.json +1 -1
  3. package/template/.agents/skills/windy-business-module/SKILL.md +10 -1
  4. package/template/.windy-template.json +2 -2
  5. package/template/AGENTS.md +9 -0
  6. package/template/README.md +3 -1
  7. package/template/apps/agent-server/Dockerfile +1 -0
  8. package/template/apps/agent-server/README.md +28 -5
  9. package/template/apps/agent-server/adk_web_agents/__init__.py +1 -0
  10. package/template/apps/agent-server/adk_web_agents/safe_debug/__init__.py +3 -0
  11. package/template/apps/agent-server/adk_web_agents/safe_debug/agent.py +40 -0
  12. package/template/apps/agent-server/pyproject.toml +1 -1
  13. package/template/apps/agent-server/src/southwind_agent_server/adk_adapter.py +191 -16
  14. package/template/apps/agent-server/src/southwind_agent_server/adk_failure.py +13 -0
  15. package/template/apps/agent-server/src/southwind_agent_server/adk_model.py +225 -0
  16. package/template/apps/agent-server/src/southwind_agent_server/adk_tools.py +76 -0
  17. package/template/apps/agent-server/src/southwind_agent_server/app.py +63 -3
  18. package/template/apps/agent-server/src/southwind_agent_server/contracts.py +35 -0
  19. package/template/apps/agent-server/src/southwind_agent_server/engine.py +2 -0
  20. package/template/apps/agent-server/src/southwind_agent_server/openai_engine.py +31 -3
  21. package/template/apps/agent-server/src/southwind_agent_server/openai_provider.py +22 -9
  22. package/template/apps/agent-server/src/southwind_agent_server/provider_audit.py +144 -0
  23. package/template/apps/agent-server/src/southwind_agent_server/provider_governance.py +227 -0
  24. package/template/apps/agent-server/src/southwind_agent_server/service.py +1 -0
  25. package/template/apps/agent-server/tests/test_adk_adapter.py +305 -0
  26. package/template/apps/agent-server/tests/test_adk_web_agent.py +12 -0
  27. package/template/apps/agent-server/tests/test_api.py +16 -1
  28. package/template/apps/agent-server/tests/test_openai_provider.py +79 -0
  29. package/template/apps/agent-server/tests/test_provider_governance.py +215 -0
  30. package/template/apps/server/package.json +4 -1
  31. package/template/apps/server/src/agent/provider-input-governance.test.ts +82 -0
  32. package/template/apps/server/src/agent/provider-input-governance.ts +140 -0
  33. package/template/apps/server/src/agent/remote-runtime.test.ts +22 -0
  34. package/template/apps/server/src/agent/remote-runtime.ts +1 -0
  35. package/template/apps/server/src/agent/run-contracts.ts +2 -0
  36. package/template/apps/server/src/agent/run-facade.test.ts +52 -2
  37. package/template/apps/server/src/agent/run-facade.ts +38 -9
  38. package/template/apps/server/src/agent/tool-registry.ts +2 -6
  39. package/template/apps/server/src/application-services.ts +50 -0
  40. package/template/apps/server/src/audit/drizzle-log-store.ts +25 -0
  41. package/template/apps/server/src/audit/search-summary.ts +2 -6
  42. package/template/apps/server/src/auth/credential-restriction.ts +1 -0
  43. package/template/apps/server/src/auth/password.ts +30 -21
  44. package/template/apps/server/src/auth/routes.test.ts +44 -3
  45. package/template/apps/server/src/auth/routes.ts +6 -1
  46. package/template/apps/server/src/auth/runtime.ts +4 -1
  47. package/template/apps/server/src/auth/service.ts +25 -7
  48. package/template/apps/server/src/configuration/bootstrap.ts +20 -1
  49. package/template/apps/server/src/configuration/definition.test.ts +71 -0
  50. package/template/apps/server/src/configuration/definition.ts +242 -12
  51. package/template/apps/server/src/configuration/drizzle-repository.ts +36 -2
  52. package/template/apps/server/src/configuration/repository.ts +27 -2
  53. package/template/apps/server/src/configuration/routes.ts +4 -1
  54. package/template/apps/server/src/configuration/service.test.ts +100 -0
  55. package/template/apps/server/src/configuration/service.ts +50 -10
  56. package/template/apps/server/src/data-access/scoped-repository.integration.test.ts +3 -2
  57. package/template/apps/server/src/data-governance/export/service.ts +2 -6
  58. package/template/apps/server/src/example-modules.ts +4 -1
  59. package/template/apps/server/src/guards.ts +18 -5
  60. package/template/apps/server/src/http/request-source.test.ts +85 -0
  61. package/template/apps/server/src/http/request-source.ts +90 -0
  62. package/template/apps/server/src/index.ts +45 -45
  63. package/template/apps/server/src/license/routes.ts +2 -0
  64. package/template/apps/server/src/license/runtime-service.ts +10 -11
  65. package/template/apps/server/src/module-bootstrap.ts +2 -2
  66. package/template/apps/server/src/module-host/initialize-contracts.ts +6 -0
  67. package/template/apps/server/src/module-host/initialize.ts +30 -44
  68. package/template/apps/server/src/module-host/request-context.ts +29 -23
  69. package/template/apps/server/src/module-host/resource-file-policies.test.ts +197 -0
  70. package/template/apps/server/src/module-host/resource-file-policies.ts +108 -0
  71. package/template/apps/server/src/module-host/route-declaration.ts +45 -0
  72. package/template/apps/server/src/module-host/route-installer.ts +27 -3
  73. package/template/apps/server/src/module-host/storage-port.test.ts +170 -1
  74. package/template/apps/server/src/module-host/storage-port.ts +134 -1
  75. package/template/apps/server/src/module-host/storage-scope.ts +89 -0
  76. package/template/apps/server/src/module-host/tool-handlers.test.ts +305 -0
  77. package/template/apps/server/src/module-host/tool-handlers.ts +38 -4
  78. package/template/apps/server/src/module-host/user-directory-composition.test.ts +126 -0
  79. package/template/apps/server/src/module-host/user-directory-port.test.ts +238 -0
  80. package/template/apps/server/src/module-host/user-directory-port.ts +139 -0
  81. package/template/apps/server/src/module-host.ts +4 -0
  82. package/template/apps/server/src/notification/channel-adapter.ts +46 -0
  83. package/template/apps/server/src/notification/delivery-policy.test.ts +59 -0
  84. package/template/apps/server/src/notification/delivery-policy.ts +37 -0
  85. package/template/apps/server/src/notification/delivery-repository.ts +198 -0
  86. package/template/apps/server/src/notification/delivery-worker.test.ts +87 -0
  87. package/template/apps/server/src/notification/delivery-worker.ts +88 -0
  88. package/template/apps/server/src/notification/drizzle-management.ts +180 -0
  89. package/template/apps/server/src/notification/drizzle-query.ts +160 -0
  90. package/template/apps/server/src/notification/drizzle-repository.integration.test.ts +301 -0
  91. package/template/apps/server/src/notification/drizzle-repository.ts +156 -90
  92. package/template/apps/server/src/notification/extension-routes.test.ts +119 -0
  93. package/template/apps/server/src/notification/extension-routes.ts +111 -0
  94. package/template/apps/server/src/notification/memory-delivery-repository.ts +137 -0
  95. package/template/apps/server/src/notification/memory-support.ts +72 -0
  96. package/template/apps/server/src/notification/preference-repository.ts +95 -0
  97. package/template/apps/server/src/notification/recipient-directory.ts +104 -0
  98. package/template/apps/server/src/notification/repository.test.ts +171 -0
  99. package/template/apps/server/src/notification/repository.ts +179 -32
  100. package/template/apps/server/src/notification/revision-routes.test.ts +186 -0
  101. package/template/apps/server/src/notification/route-support.ts +225 -0
  102. package/template/apps/server/src/notification/routes.test.ts +182 -0
  103. package/template/apps/server/src/notification/routes.ts +225 -132
  104. package/template/apps/server/src/notification/service.test.ts +104 -0
  105. package/template/apps/server/src/notification/service.ts +140 -0
  106. package/template/apps/server/src/notification/smtp-adapter.test.ts +65 -0
  107. package/template/apps/server/src/notification/smtp-adapter.ts +68 -0
  108. package/template/apps/server/src/persistence.integration.test.ts +41 -2
  109. package/template/apps/server/src/route-guards.ts +1 -0
  110. package/template/apps/server/src/runtime-audit-list.test.ts +39 -0
  111. package/template/apps/server/src/runtime-development.ts +2 -0
  112. package/template/apps/server/src/runtime.test.ts +23 -9
  113. package/template/apps/server/src/runtime.ts +39 -2
  114. package/template/apps/server/src/scheduler/audit.ts +2 -11
  115. package/template/apps/server/src/scheduler/definitions.test.ts +6 -0
  116. package/template/apps/server/src/scheduler/definitions.ts +7 -0
  117. package/template/apps/server/src/scheduler/recovery-service.ts +2 -11
  118. package/template/apps/server/src/scheduler/routes.ts +2 -7
  119. package/template/apps/server/src/search/opensearch-client.test.ts +45 -0
  120. package/template/apps/server/src/search/opensearch-client.ts +145 -0
  121. package/template/apps/server/src/search/service.ts +2 -6
  122. package/template/apps/server/src/settings/routes.ts +15 -3
  123. package/template/apps/server/src/settings/runtime.ts +10 -1
  124. package/template/apps/server/src/storage/runtime.ts +13 -0
  125. package/template/apps/server/src/system/audit-query.ts +33 -4
  126. package/template/apps/server/src/system/audit-routes.test.ts +58 -4
  127. package/template/apps/server/src/system/audit-routes.ts +6 -5
  128. package/template/apps/server/src/system/built-in-roles.ts +1 -0
  129. package/template/apps/server/src/system/department-organization.ts +320 -0
  130. package/template/apps/server/src/system/department-routes.test.ts +207 -48
  131. package/template/apps/server/src/system/department-routes.ts +114 -33
  132. package/template/apps/server/src/system/drizzle-repository.ts +15 -7
  133. package/template/apps/server/src/system/drizzle-scoped-repository.ts +5 -3
  134. package/template/apps/server/src/system/drizzle-system.ts +37 -9
  135. package/template/apps/server/src/system/drizzle-transaction-context.ts +14 -0
  136. package/template/apps/server/src/system/identity-route-config.ts +7 -2
  137. package/template/apps/server/src/system/mutation-runner.ts +23 -0
  138. package/template/apps/server/src/system/organization-postgres.integration.test.ts +176 -0
  139. package/template/apps/server/src/system/resource-access-response.ts +12 -6
  140. package/template/apps/server/src/system/role-department-scope-policy.ts +55 -0
  141. package/template/apps/server/src/system/route-helpers.ts +2 -5
  142. package/template/apps/server/src/system/route-types.ts +12 -3
  143. package/template/apps/server/src/system/routes-validation.test.ts +26 -0
  144. package/template/apps/server/src/system/routes.test.ts +10 -2
  145. package/template/apps/server/src/system/routes.ts +70 -36
  146. package/template/apps/server/src/system/seed.ts +7 -0
  147. package/template/apps/server/src/work-order/data-scope.integration.test.ts +9 -2
  148. package/template/apps/server/src/work-order/opensearch-index.test.ts +97 -0
  149. package/template/apps/server/src/work-order/opensearch-index.ts +313 -0
  150. package/template/apps/server/src/work-order/search-provider.ts +60 -1
  151. package/template/apps/server/src/work-order/service.ts +42 -10
  152. package/template/apps/web/src/app/error-pages.ts +9 -0
  153. package/template/apps/web/src/components/auth/PasswordChangeForm.vue +16 -11
  154. package/template/apps/web/src/components/auth/PasswordChangeForm.webtest.ts +14 -0
  155. package/template/apps/web/src/components/common/FormDialog.vue +16 -2
  156. package/template/apps/web/src/components/common/ModalLayout.webtest.ts +20 -1
  157. package/template/apps/web/src/composables/useGlobalSearch.ts +68 -0
  158. package/template/apps/web/src/composables/usePlatformSettings.ts +8 -7
  159. package/template/apps/web/src/layout/GlobalSearchResults.vue +58 -0
  160. package/template/apps/web/src/layout/NavigationSearchDialog.vue +42 -6
  161. package/template/apps/web/src/layout/NavigationSearchDialog.webtest.ts +71 -0
  162. package/template/apps/web/src/layout/NotificationMenu.vue +73 -31
  163. package/template/apps/web/src/layout/NotificationMenu.webtest.ts +44 -1
  164. package/template/apps/web/src/layout/NotificationMenuItem.vue +61 -0
  165. package/template/apps/web/src/layout/NotificationPreferencesDialog.vue +181 -0
  166. package/template/apps/web/src/layout/NotificationPreferencesDialog.webtest.ts +80 -0
  167. package/template/apps/web/src/lib/date-time.ts +22 -10
  168. package/template/apps/web/src/lib/date-time.webtest.ts +9 -1
  169. package/template/apps/web/src/main.ts +14 -1
  170. package/template/apps/web/src/pages/auth/ChangePasswordPage.vue +16 -1
  171. package/template/apps/web/src/pages/configuration/components/ModuleConfigVersionList.vue +1 -0
  172. package/template/apps/web/src/pages/configuration/components/ModuleConfigurationEditor.vue +10 -0
  173. package/template/apps/web/src/pages/configuration/components/ModuleConfigurationWorkbench.vue +37 -6
  174. package/template/apps/web/src/pages/errors/PlatformErrorPage.vue +115 -0
  175. package/template/apps/web/src/pages/errors/PlatformErrorPage.webtest.ts +44 -0
  176. package/template/apps/web/src/pages/errors/error-page-extension.ts +26 -0
  177. package/template/apps/web/src/pages/system/SystemNotificationsPage.vue +136 -68
  178. package/template/apps/web/src/pages/system/SystemNotificationsPage.webtest.ts +224 -12
  179. package/template/apps/web/src/pages/system/audit-log-presenter.ts +86 -0
  180. package/template/apps/web/src/pages/system/audit-time-range.ts +28 -0
  181. package/template/apps/web/src/pages/system/components/AuditActionCell.vue +10 -69
  182. package/template/apps/web/src/pages/system/components/AuditActionCell.webtest.ts +20 -27
  183. package/template/apps/web/src/pages/system/components/AuditLogDetailDialog.vue +134 -0
  184. package/template/apps/web/src/pages/system/components/AuditLogDetailDialog.webtest.ts +76 -0
  185. package/template/apps/web/src/pages/system/components/AuditLogFilters.vue +116 -52
  186. package/template/apps/web/src/pages/system/components/AuditLogFilters.webtest.ts +52 -15
  187. package/template/apps/web/src/pages/system/components/NotificationHistoryDialog.vue +129 -0
  188. package/template/apps/web/src/pages/system/components/NotificationManagementCard.vue +91 -0
  189. package/template/apps/web/src/pages/system/components/NotificationPublishDialog.vue +121 -0
  190. package/template/apps/web/src/pages/system/components/NotificationPublishForm.vue +162 -1
  191. package/template/apps/web/src/pages/system/components/SystemResourceActions.vue +68 -0
  192. package/template/apps/web/src/pages/system/components/SystemResourceEditor.vue +74 -0
  193. package/template/apps/web/src/pages/system/components/SystemResourceFilters.vue +3 -4
  194. package/template/apps/web/src/pages/system/components/SystemResourcePage.vue +91 -98
  195. package/template/apps/web/src/pages/system/components/SystemResourcePage.webtest.ts +68 -0
  196. package/template/apps/web/src/pages/system/components/SystemResourceTable.vue +20 -1
  197. package/template/apps/web/src/pages/system/components/SystemResourceTable.webtest.ts +28 -7
  198. package/template/apps/web/src/pages/system/components/department/DepartmentOrganizationForm.vue +210 -0
  199. package/template/apps/web/src/pages/system/components/department/DepartmentTransitionDialog.vue +112 -0
  200. package/template/apps/web/src/pages/system/components/user-account/UserAccountForm.vue +17 -4
  201. package/template/apps/web/src/pages/system/composables/useDepartmentTransitions.ts +79 -0
  202. package/template/apps/web/src/pages/system/composables/useNotificationPermissions.ts +14 -0
  203. package/template/apps/web/src/pages/system/composables/useSystemResource.ts +2 -0
  204. package/template/apps/web/src/pages/system/composables/useSystemResource.webtest.ts +15 -2
  205. package/template/apps/web/src/pages/system/resource-config.ts +12 -4
  206. package/template/apps/web/src/router/error-navigation.ts +50 -0
  207. package/template/apps/web/src/router/error-navigation.webtest.ts +106 -0
  208. package/template/apps/web/src/router/index.ts +71 -0
  209. package/template/apps/web/src/router/index.webtest.ts +29 -0
  210. package/template/apps/web/src/router/manifest-routes.webtest.ts +4 -0
  211. package/template/apps/web/src/router/shared-scaffold-neutrality.webtest.ts +12 -0
  212. package/template/apps/web/src/services/auth-api.ts +5 -0
  213. package/template/apps/web/src/services/http.ts +43 -6
  214. package/template/apps/web/src/services/http.webtest.ts +70 -0
  215. package/template/apps/web/src/services/notification-api.ts +85 -2
  216. package/template/apps/web/src/services/notification-api.webtest.ts +110 -0
  217. package/template/apps/web/src/services/search-api.ts +39 -0
  218. package/template/apps/web/src/services/system-api.ts +18 -0
  219. package/template/apps/web/vitest.config.ts +1 -0
  220. package/template/docker-compose.yml +68 -0
  221. package/template/docs/architecture/ai-egress.md +49 -7
  222. package/template/docs/architecture/ai-runtime.md +34 -6
  223. package/template/docs/architecture/data-scope-query-enforcement.md +4 -0
  224. package/template/docs/architecture/object-storage.md +22 -2
  225. package/template/docs/architecture/search-provider-protocol.md +38 -2
  226. package/template/docs/development/custom-error-pages.md +78 -0
  227. package/template/docs/development/custom-login-page.md +3 -3
  228. package/template/docs/platform/agent-runtime.md +76 -7
  229. package/template/docs/platform/audit-reliability.md +46 -2
  230. package/template/docs/platform/business-user-directory.md +82 -0
  231. package/template/docs/platform/module-configuration.md +13 -4
  232. package/template/docs/platform/notifications.md +67 -11
  233. package/template/docs/platform/organization-membership.md +17 -3
  234. package/template/docs/platform/system-crud-api.md +16 -0
  235. package/template/docs/platform/web-system-crud.md +6 -2
  236. package/template/package.json +4 -0
  237. package/template/packages/config/index.test.ts +45 -0
  238. package/template/packages/config/package.json +1 -1
  239. package/template/packages/config/src/platform.ts +169 -48
  240. package/template/packages/database/drizzle/0035_material_nightshade.sql +10 -0
  241. package/template/packages/database/drizzle/0036_hesitant_speed.sql +35 -0
  242. package/template/packages/database/drizzle/0037_absent_nick_fury.sql +2 -0
  243. package/template/packages/database/drizzle/0038_uneven_wasp.sql +38 -0
  244. package/template/packages/database/drizzle/meta/0035_snapshot.json +7331 -0
  245. package/template/packages/database/drizzle/meta/0036_snapshot.json +7436 -0
  246. package/template/packages/database/drizzle/meta/0037_snapshot.json +7457 -0
  247. package/template/packages/database/drizzle/meta/0038_snapshot.json +7749 -0
  248. package/template/packages/database/drizzle/meta/_journal.json +28 -0
  249. package/template/packages/database/package.json +1 -1
  250. package/template/packages/database/src/schema/identity.ts +7 -0
  251. package/template/packages/database/src/schema/notifications.ts +135 -0
  252. package/template/packages/database/src/schema-notification-delivery.test.ts +54 -0
  253. package/template/packages/database/src/schema-workflow-notification.test.ts +40 -1
  254. package/template/packages/modules/package.json +1 -1
  255. package/template/packages/modules/src/ai-operation-composition.test.ts +68 -0
  256. package/template/packages/modules/src/ai-operation-composition.ts +115 -0
  257. package/template/packages/modules/src/manifest.ts +26 -0
  258. package/template/packages/modules/src/provider-data-policy-composition.test.ts +74 -0
  259. package/template/packages/modules/src/system-api-permissions.ts +54 -0
  260. package/template/packages/modules/src/system-audit-actions.ts +15 -0
  261. package/template/packages/modules/src/system-features.ts +6 -1
  262. package/template/packages/modules/src/system-module-catalog.test.ts +16 -0
  263. package/template/packages/modules/src/system-module-catalog.ts +28 -4
  264. package/template/packages/modules/src/system-modules.test.ts +13 -1
  265. package/template/packages/modules/src/system-modules.ts +12 -0
  266. package/template/packages/modules/src/system-permissions.ts +11 -5
  267. package/template/packages/server-sdk/index.ts +11 -0
  268. package/template/packages/server-sdk/package.json +3 -2
  269. package/template/packages/server-sdk/src/ai-operation-registration.ts +2 -1
  270. package/template/packages/server-sdk/src/module-host.ts +8 -0
  271. package/template/packages/server-sdk/src/request-context.ts +2 -0
  272. package/template/packages/server-sdk/src/storage-port.ts +66 -0
  273. package/template/packages/server-sdk/src/tool-registration.ts +6 -0
  274. package/template/packages/server-sdk/src/user-directory-port.ts +42 -0
  275. package/template/packages/shared/package.json +1 -1
  276. package/template/packages/shared/src/audit.ts +25 -0
  277. package/template/packages/shared/src/module-configuration.ts +5 -0
  278. package/template/packages/shared/src/notification.ts +92 -1
  279. package/template/packages/shared/src/password.ts +7 -2
  280. package/template/packages/shared/src/platform-settings.ts +2 -0
  281. package/template/packages/storage/package.json +1 -1
  282. package/template/packages/storage/src/upload-service.test.ts +16 -0
  283. package/template/packages/storage/src/upload-service.ts +5 -1
  284. package/template/scripts/notification-postgres-regression.ts +27 -0
@@ -0,0 +1,320 @@
1
+ import type { LifecycleStatus } from "@southwind-ai/shared";
2
+ import type { RequestActor } from "../guards.js";
3
+ import type {
4
+ ManagedDepartment,
5
+ ManagedRole,
6
+ ManagedUser,
7
+ } from "./entities.js";
8
+ import type { EntityRepository } from "./repository.js";
9
+ import type {
10
+ ResourcePolicyError,
11
+ ResourcePolicyResult,
12
+ } from "./route-types.js";
13
+
14
+ export type DepartmentTransitionAction = "disable" | "delete";
15
+
16
+ export interface DepartmentTransitionResult {
17
+ department: ManagedDepartment;
18
+ movedChildren: number;
19
+ movedUsers: number;
20
+ updatedRoles: number;
21
+ }
22
+
23
+ interface OrganizationRepositories {
24
+ departments: EntityRepository<ManagedDepartment>;
25
+ users: EntityRepository<ManagedUser>;
26
+ roles: EntityRepository<ManagedRole>;
27
+ }
28
+
29
+ export class DepartmentOrganizationPolicy {
30
+ constructor(private readonly repositories: OrganizationRepositories) {}
31
+
32
+ async validateInput(
33
+ input: Partial<ManagedDepartment>,
34
+ current?: ManagedDepartment,
35
+ ): Promise<ResourcePolicyResult> {
36
+ if (
37
+ input.code !== undefined &&
38
+ (typeof input.code !== "string" ||
39
+ !/^[a-zA-Z][a-zA-Z0-9_-]{1,79}$/.test(input.code.trim()))
40
+ ) {
41
+ return invalid(
42
+ "INVALID_DEPARTMENT_CODE",
43
+ "部门编码需以字母开头且至少 2 位",
44
+ );
45
+ }
46
+ if (
47
+ input.name !== undefined &&
48
+ (typeof input.name !== "string" || !input.name.trim())
49
+ ) {
50
+ return invalid("INVALID_DEPARTMENT_NAME", "部门名称不能为空");
51
+ }
52
+ if (
53
+ input.order !== undefined &&
54
+ (!Number.isSafeInteger(input.order) || input.order < 0)
55
+ ) {
56
+ return invalid("INVALID_DEPARTMENT_ORDER", "部门排序必须是非负整数");
57
+ }
58
+ if (input.status !== undefined && !isLifecycleStatus(input.status)) {
59
+ return invalid("INVALID_DEPARTMENT_STATUS", "部门状态不合法");
60
+ }
61
+ if (
62
+ !current &&
63
+ (typeof input.code !== "string" ||
64
+ typeof input.name !== "string" ||
65
+ typeof input.parentId !== "string" ||
66
+ !input.parentId)
67
+ ) {
68
+ return invalid(
69
+ "DEPARTMENT_PARENT_REQUIRED",
70
+ "平台只允许一个根组织,新部门必须选择上级部门",
71
+ );
72
+ }
73
+ return undefined;
74
+ }
75
+
76
+ async beforeCreate(
77
+ input: Partial<ManagedDepartment>,
78
+ ): Promise<ResourcePolicyResult> {
79
+ const duplicate = (await this.repositories.departments.all()).find(
80
+ (department) => department.code === input.code?.trim(),
81
+ );
82
+ if (duplicate) {
83
+ return conflict("DUPLICATE_DEPARTMENT_CODE", "部门编码已存在");
84
+ }
85
+ return this.validateParent(undefined, input.parentId);
86
+ }
87
+
88
+ async beforeUpdate(
89
+ current: ManagedDepartment,
90
+ input: Partial<ManagedDepartment>,
91
+ ): Promise<ResourcePolicyResult> {
92
+ if (input.code && input.code !== current.code) {
93
+ const duplicate = (await this.repositories.departments.all()).find(
94
+ (department) =>
95
+ department.id !== current.id &&
96
+ department.code === input.code?.trim(),
97
+ );
98
+ if (duplicate) {
99
+ return conflict("DUPLICATE_DEPARTMENT_CODE", "部门编码已存在");
100
+ }
101
+ }
102
+ if (input.parentId !== undefined) {
103
+ const parentError = await this.validateParent(current, input.parentId);
104
+ if (parentError) return parentError;
105
+ }
106
+ if (
107
+ input.status !== undefined &&
108
+ input.status !== "active" &&
109
+ current.status === "active"
110
+ ) {
111
+ return this.validateCanLeaveActive(current);
112
+ }
113
+ if (input.status === "active") {
114
+ return this.validateParent(current, current.parentId);
115
+ }
116
+ return undefined;
117
+ }
118
+
119
+ beforeDelete(current: ManagedDepartment): Promise<ResourcePolicyResult> {
120
+ return this.validateCanLeaveActive(current);
121
+ }
122
+
123
+ async transition(
124
+ id: string,
125
+ action: DepartmentTransitionAction,
126
+ targetDepartmentId: string | undefined,
127
+ actor: RequestActor,
128
+ ): Promise<DepartmentTransitionResult | ResourcePolicyError> {
129
+ const source = await this.repositories.departments.get(id);
130
+ if (!source) {
131
+ return conflict("DEPARTMENT_NOT_FOUND", "部门不存在或已删除");
132
+ }
133
+ if (!source.parentId) {
134
+ return conflict("ROOT_DEPARTMENT_IMMUTABLE", "根组织不能停用或删除");
135
+ }
136
+ const references = await this.references(source.id);
137
+ const referenceCount =
138
+ references.children.length +
139
+ references.users.length +
140
+ references.roles.length;
141
+ let target: ManagedDepartment | undefined;
142
+ if (referenceCount > 0) {
143
+ if (!targetDepartmentId) {
144
+ return conflict(
145
+ "DEPARTMENT_MIGRATION_REQUIRED",
146
+ "部门仍有关联数据,请选择迁移目标后重试",
147
+ referenceDetails(references),
148
+ );
149
+ }
150
+ target = await this.repositories.departments.get(targetDepartmentId);
151
+ const targetError = await this.validateMigrationTarget(source, target);
152
+ if (targetError) return targetError;
153
+ } else if (targetDepartmentId) {
154
+ target = await this.repositories.departments.get(targetDepartmentId);
155
+ const targetError = await this.validateMigrationTarget(source, target);
156
+ if (targetError) return targetError;
157
+ }
158
+
159
+ if (target) {
160
+ await this.repositories.departments.updateMany(
161
+ references.children.map((child) => ({
162
+ id: child.id,
163
+ input: { parentId: target.id },
164
+ })),
165
+ actor,
166
+ );
167
+ await this.repositories.users.updateMany(
168
+ references.users.map((user) => ({
169
+ id: user.id,
170
+ input: { departmentId: target.id },
171
+ })),
172
+ actor,
173
+ );
174
+ await this.repositories.roles.updateMany(
175
+ references.roles.map((role) => ({
176
+ id: role.id,
177
+ input: {
178
+ departmentIds: unique(
179
+ (role.departmentIds || []).map((departmentId) =>
180
+ departmentId === source.id ? target.id : departmentId,
181
+ ),
182
+ ),
183
+ },
184
+ })),
185
+ actor,
186
+ );
187
+ }
188
+ const department =
189
+ action === "delete"
190
+ ? await this.repositories.departments.softDelete(source.id, actor)
191
+ : await this.repositories.departments.update(
192
+ source.id,
193
+ { status: "disabled" },
194
+ actor,
195
+ );
196
+ if (!department) {
197
+ return conflict("DEPARTMENT_NOT_FOUND", "部门不存在或已删除");
198
+ }
199
+ return {
200
+ department,
201
+ movedChildren: references.children.length,
202
+ movedUsers: references.users.length,
203
+ updatedRoles: references.roles.length,
204
+ };
205
+ }
206
+
207
+ private async validateParent(
208
+ current: ManagedDepartment | undefined,
209
+ parentId: string | undefined,
210
+ ): Promise<ResourcePolicyResult> {
211
+ if (current && !current.parentId) {
212
+ return parentId === undefined
213
+ ? undefined
214
+ : conflict("ROOT_DEPARTMENT_IMMUTABLE", "根组织不能迁移到其它部门");
215
+ }
216
+ if (!parentId) {
217
+ return conflict(
218
+ "DEPARTMENT_PARENT_REQUIRED",
219
+ "平台只允许一个根组织,部门必须保留上级部门",
220
+ );
221
+ }
222
+ const parent = await this.repositories.departments.get(parentId);
223
+ if (!parent || parent.status !== "active") {
224
+ return conflict("INVALID_DEPARTMENT_PARENT", "上级部门不存在或未启用");
225
+ }
226
+ if (!current) return undefined;
227
+ return (await this.isDescendant(parent.id, current.id))
228
+ ? conflict("DEPARTMENT_CYCLE", "不能把部门移动到自身或其下级部门")
229
+ : undefined;
230
+ }
231
+
232
+ private async validateCanLeaveActive(
233
+ current: ManagedDepartment,
234
+ ): Promise<ResourcePolicyResult> {
235
+ if (!current.parentId) {
236
+ return conflict("ROOT_DEPARTMENT_IMMUTABLE", "根组织不能停用或删除");
237
+ }
238
+ const references = await this.references(current.id);
239
+ return references.children.length ||
240
+ references.users.length ||
241
+ references.roles.length
242
+ ? conflict(
243
+ "DEPARTMENT_MIGRATION_REQUIRED",
244
+ "部门仍有关联数据,请通过组织迁移完成停用或删除",
245
+ referenceDetails(references),
246
+ )
247
+ : undefined;
248
+ }
249
+
250
+ private async validateMigrationTarget(
251
+ source: ManagedDepartment,
252
+ target: ManagedDepartment | undefined,
253
+ ): Promise<ResourcePolicyError | undefined> {
254
+ if (!target || target.status !== "active") {
255
+ return conflict("INVALID_MIGRATION_TARGET", "迁移目标不存在或未启用");
256
+ }
257
+ if (await this.isDescendant(target.id, source.id)) {
258
+ return conflict("DEPARTMENT_CYCLE", "迁移目标不能是当前部门或其下级部门");
259
+ }
260
+ return undefined;
261
+ }
262
+
263
+ private async isDescendant(
264
+ candidateId: string,
265
+ ancestorId: string,
266
+ ): Promise<boolean> {
267
+ if (candidateId === ancestorId) return true;
268
+ const departments = await this.repositories.departments.all();
269
+ const byId = new Map(departments.map((item) => [item.id, item]));
270
+ const visited = new Set<string>();
271
+ let current = byId.get(candidateId);
272
+ while (current?.parentId && !visited.has(current.id)) {
273
+ visited.add(current.id);
274
+ if (current.parentId === ancestorId) return true;
275
+ current = byId.get(current.parentId);
276
+ }
277
+ return false;
278
+ }
279
+
280
+ private async references(departmentId: string) {
281
+ const departments = await this.repositories.departments.all();
282
+ const users = await this.repositories.users.all();
283
+ const roles = await this.repositories.roles.all();
284
+ return {
285
+ children: departments.filter((item) => item.parentId === departmentId),
286
+ users: users.filter((item) => item.departmentId === departmentId),
287
+ roles: roles.filter((item) => item.departmentIds?.includes(departmentId)),
288
+ };
289
+ }
290
+ }
291
+
292
+ function referenceDetails(
293
+ references: Awaited<ReturnType<DepartmentOrganizationPolicy["references"]>>,
294
+ ): Record<string, unknown> {
295
+ return {
296
+ childDepartmentCount: references.children.length,
297
+ userCount: references.users.length,
298
+ roleCount: references.roles.length,
299
+ };
300
+ }
301
+
302
+ function invalid(error: string, message: string): ResourcePolicyError {
303
+ return { error, message };
304
+ }
305
+
306
+ function conflict(
307
+ error: string,
308
+ message: string,
309
+ details?: Record<string, unknown>,
310
+ ): ResourcePolicyError {
311
+ return { error, message, ...(details ? { details } : {}) };
312
+ }
313
+
314
+ function unique(values: string[]): string[] {
315
+ return [...new Set(values)].sort();
316
+ }
317
+
318
+ function isLifecycleStatus(value: unknown): value is LifecycleStatus {
319
+ return ["draft", "active", "disabled", "archived"].includes(String(value));
320
+ }
@@ -1,35 +1,33 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import { createFoundationSnapshot } from "../foundation.js";
3
3
  import { createServerRuntime } from "../runtime.js";
4
- import { registerSystemRoutes, type RouteApp } from "./routes.js";
4
+ import { FakeRouteApp } from "./route-test-app.js";
5
+ import { registerSystemRoutes } from "./routes.js";
5
6
  import { createSystemRepositories } from "./seed.js";
6
7
 
7
- class FakeRouteApp implements RouteApp {
8
- private readonly handlers = new Map<string, (context: unknown) => unknown>();
9
-
10
- get(path: string, handler: (context: unknown) => unknown): void {
11
- this.handlers.set(`GET ${path}`, handler);
12
- }
13
- post(path: string, handler: (context: unknown) => unknown): void {
14
- this.handlers.set(`POST ${path}`, handler);
15
- }
16
- put(path: string, handler: (context: unknown) => unknown): void {
17
- this.handlers.set(`PUT ${path}`, handler);
18
- }
19
- delete(path: string, handler: (context: unknown) => unknown): void {
20
- this.handlers.set(`DELETE ${path}`, handler);
21
- }
22
- invoke(method: string, path: string, context: unknown): unknown {
23
- const handler = this.handlers.get(`${method} ${path}`);
24
- if (!handler) throw new Error(`未注册路由 ${method} ${path}`);
25
- return handler(context);
26
- }
8
+ async function fixture() {
9
+ const snapshot = createFoundationSnapshot();
10
+ const repositories = createSystemRepositories(snapshot);
11
+ const runtime = createServerRuntime({ WINDY_DEV_ADMIN_TOKEN: "token_1" });
12
+ const app = new FakeRouteApp();
13
+ registerSystemRoutes(app, repositories, runtime, snapshot.features);
14
+ const guardContext = await runtime.createGuardContext(
15
+ new Request("http://localhost/api/system/departments", {
16
+ headers: { authorization: "Bearer token_1" },
17
+ }),
18
+ );
19
+ return {
20
+ app,
21
+ repositories,
22
+ runtime,
23
+ context: { guardContext, params: {}, query: {} },
24
+ };
27
25
  }
28
26
 
29
- describe("部门归属路由", () => {
30
- test("用户表单快捷创建部门并拒绝绑定不存在的部门", async () => {
27
+ describe("部门组织路由", () => {
28
+ test("部门处置缺少权限时经过统一 Guard 拒绝", async () => {
31
29
  const snapshot = createFoundationSnapshot();
32
- const runtime = createServerRuntime({ WINDY_DEV_ADMIN_TOKEN: "token_1" });
30
+ const runtime = createServerRuntime();
33
31
  const app = new FakeRouteApp();
34
32
  registerSystemRoutes(
35
33
  app,
@@ -38,43 +36,204 @@ describe("部门归属路由", () => {
38
36
  snapshot.features,
39
37
  );
40
38
  const guardContext = await runtime.createGuardContext(
41
- new Request("http://localhost/api/system/users", {
42
- headers: { authorization: "Bearer token_1" },
43
- }),
39
+ new Request(
40
+ "http://localhost/api/system/departments/dept_platform/transition",
41
+ ),
44
42
  );
45
- const context = { guardContext, params: {}, query: {} };
43
+ const response = (await app.invoke(
44
+ "POST",
45
+ "/system/departments/:id/transition",
46
+ {
47
+ guardContext,
48
+ params: { id: "dept_platform" },
49
+ query: {},
50
+ body: { action: "delete" },
51
+ },
52
+ )) as Response;
46
53
 
54
+ expect(response.status).toBe(403);
55
+ await expect(response.json()).resolves.toMatchObject({
56
+ error: "FORBIDDEN",
57
+ });
58
+ expect(runtime.auditSink.list()[0]?.action).toBe("security.denied");
59
+ });
60
+
61
+ test("快捷创建必须挂到唯一根组织并拒绝第二个根", async () => {
62
+ const { app, context } = await fixture();
63
+ const missingParent = (await app.invoke(
64
+ "POST",
65
+ "/system/departments/quick",
66
+ {
67
+ ...context,
68
+ body: { code: "sales", name: "销售部" },
69
+ },
70
+ )) as Response;
47
71
  const department = (await app.invoke("POST", "/system/departments/quick", {
48
72
  ...context,
49
- body: { code: "sales", name: "销售部" },
50
- })) as { id: string; code: string };
51
- const user = (await app.invoke("POST", "/system/users", {
73
+ body: {
74
+ code: "sales",
75
+ name: "销售部",
76
+ parentId: "dept_platform",
77
+ },
78
+ })) as { id: string; parentId: string };
79
+ const secondRoot = (await app.invoke("POST", "/system/departments", {
80
+ ...context,
81
+ body: { code: "root2", name: "第二根组织", order: 20 },
82
+ })) as Response;
83
+
84
+ expect(missingParent.status).toBe(400);
85
+ await expect(missingParent.json()).resolves.toMatchObject({
86
+ error: "DEPARTMENT_PARENT_REQUIRED",
87
+ });
88
+ expect(department.parentId).toBe("dept_platform");
89
+ expect(secondRoot.status).toBe(400);
90
+ await expect(secondRoot.json()).resolves.toMatchObject({
91
+ error: "DEPARTMENT_PARENT_REQUIRED",
92
+ });
93
+ });
94
+
95
+ test("移动部门会拒绝自身、下级和根组织变更", async () => {
96
+ const { app, context } = await fixture();
97
+ await createDepartment(app, context, "dept_a", "部门 A", "dept_platform");
98
+ await createDepartment(app, context, "dept_b", "部门 B", "dept_a");
99
+
100
+ const cycle = (await app.invoke("PUT", "/system/departments/:id", {
101
+ ...context,
102
+ params: { id: "dept_a" },
103
+ body: { parentId: "dept_b" },
104
+ })) as Response;
105
+ const rootMove = (await app.invoke("PUT", "/system/departments/:id", {
106
+ ...context,
107
+ params: { id: "dept_platform" },
108
+ body: { parentId: "dept_a" },
109
+ })) as Response;
110
+
111
+ expect(cycle.status).toBe(409);
112
+ await expect(cycle.json()).resolves.toMatchObject({
113
+ error: "DEPARTMENT_CYCLE",
114
+ });
115
+ expect(rootMove.status).toBe(409);
116
+ await expect(rootMove.json()).resolves.toMatchObject({
117
+ error: "ROOT_DEPARTMENT_IMMUTABLE",
118
+ });
119
+ });
120
+
121
+ test("有关联数据时要求显式迁移,并原子更新子级、用户和角色范围", async () => {
122
+ const { app, context, repositories, runtime } = await fixture();
123
+ await createDepartment(
124
+ app,
125
+ context,
126
+ "dept_source",
127
+ "待处置部门",
128
+ "dept_platform",
129
+ );
130
+ await createDepartment(
131
+ app,
132
+ context,
133
+ "dept_child",
134
+ "下级部门",
135
+ "dept_source",
136
+ );
137
+ await app.invoke("POST", "/system/roles", {
52
138
  ...context,
53
139
  body: {
54
- username: "sales-user",
55
- displayName: "销售用户",
56
- roleIds: ["role_user"],
57
- departmentId: department.id,
140
+ id: "role_custom",
141
+ code: "custom-scope",
142
+ name: "自定义范围",
143
+ dataScope: "custom",
144
+ departmentIds: ["dept_source"],
145
+ permissionKeys: [],
146
+ menuKeys: [],
58
147
  },
59
- })) as { departmentId: string };
60
- const invalid = (await app.invoke("POST", "/system/users", {
148
+ });
149
+ await app.invoke("POST", "/system/users", {
61
150
  ...context,
62
151
  body: {
63
- username: "ghost-user",
64
- displayName: "无部门用户",
65
- roleIds: ["role_user"],
66
- departmentId: "dept_missing",
152
+ id: "user_source",
153
+ username: "source-user",
154
+ displayName: "来源用户",
155
+ roleIds: ["role_custom"],
156
+ departmentId: "dept_source",
67
157
  },
158
+ });
159
+
160
+ const blocked = (await app.invoke("DELETE", "/system/departments/:id", {
161
+ ...context,
162
+ params: { id: "dept_source" },
68
163
  })) as Response;
164
+ expect(blocked.status).toBe(409);
165
+ await expect(blocked.json()).resolves.toMatchObject({
166
+ error: "DEPARTMENT_MIGRATION_REQUIRED",
167
+ details: {
168
+ childDepartmentCount: 1,
169
+ userCount: 1,
170
+ roleCount: 1,
171
+ },
172
+ });
69
173
 
70
- expect(department.code).toBe("sales");
71
- expect(user.departmentId).toBe(department.id);
72
- expect(invalid.status).toBe(400);
73
- await expect(invalid.json()).resolves.toMatchObject({
74
- error: "INVALID_RESOURCE",
174
+ const transitioned = (await app.invoke(
175
+ "POST",
176
+ "/system/departments/:id/transition",
177
+ {
178
+ ...context,
179
+ params: { id: "dept_source" },
180
+ body: {
181
+ action: "delete",
182
+ targetDepartmentId: "dept_platform",
183
+ },
184
+ },
185
+ )) as {
186
+ movedChildren: number;
187
+ movedUsers: number;
188
+ updatedRoles: number;
189
+ };
190
+ expect(transitioned).toMatchObject({
191
+ movedChildren: 1,
192
+ movedUsers: 1,
193
+ updatedRoles: 1,
194
+ });
195
+ expect(await repositories.departments.get("dept_source")).toBeUndefined();
196
+ expect(await repositories.departments.get("dept_child")).toMatchObject({
197
+ parentId: "dept_platform",
75
198
  });
76
- expect(runtime.auditSink.list().map(({ action }) => action)).toContain(
77
- "crud.create",
199
+ expect(await repositories.users.get("user_source")).toMatchObject({
200
+ departmentId: "dept_platform",
201
+ });
202
+ expect(await repositories.roles.get("role_custom")).toMatchObject({
203
+ departmentIds: ["dept_platform"],
204
+ });
205
+ expect(runtime.auditSink.list().at(-1)?.action).toBe(
206
+ "organization.department.transition",
78
207
  );
79
208
  });
209
+
210
+ test("角色自定义数据权限只接受启用部门", async () => {
211
+ const { app, context } = await fixture();
212
+ const response = (await app.invoke("POST", "/system/roles", {
213
+ ...context,
214
+ body: {
215
+ code: "invalid-custom",
216
+ name: "无效范围",
217
+ dataScope: "custom",
218
+ departmentIds: ["dept_missing"],
219
+ },
220
+ })) as Response;
221
+ expect(response.status).toBe(400);
222
+ await expect(response.json()).resolves.toMatchObject({
223
+ error: "INVALID_ROLE_DEPARTMENT_SCOPE",
224
+ });
225
+ });
80
226
  });
227
+
228
+ function createDepartment(
229
+ app: FakeRouteApp,
230
+ context: Record<string, unknown>,
231
+ id: string,
232
+ name: string,
233
+ parentId: string,
234
+ ) {
235
+ return app.invoke("POST", "/system/departments", {
236
+ ...context,
237
+ body: { id, code: id, name, parentId, order: 10 },
238
+ });
239
+ }