create-windy 0.2.34 → 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 (237) hide show
  1. package/dist/cli.js +167 -17
  2. package/package.json +1 -1
  3. package/template/.windy-template.json +2 -2
  4. package/template/AGENTS.md +5 -0
  5. package/template/README.md +3 -1
  6. package/template/apps/agent-server/Dockerfile +1 -0
  7. package/template/apps/agent-server/README.md +18 -5
  8. package/template/apps/agent-server/adk_web_agents/__init__.py +1 -0
  9. package/template/apps/agent-server/adk_web_agents/safe_debug/__init__.py +3 -0
  10. package/template/apps/agent-server/adk_web_agents/safe_debug/agent.py +40 -0
  11. package/template/apps/agent-server/pyproject.toml +1 -1
  12. package/template/apps/agent-server/src/southwind_agent_server/adk_adapter.py +191 -16
  13. package/template/apps/agent-server/src/southwind_agent_server/adk_failure.py +13 -0
  14. package/template/apps/agent-server/src/southwind_agent_server/adk_model.py +225 -0
  15. package/template/apps/agent-server/src/southwind_agent_server/adk_tools.py +76 -0
  16. package/template/apps/agent-server/src/southwind_agent_server/app.py +1 -2
  17. package/template/apps/agent-server/tests/test_adk_adapter.py +305 -0
  18. package/template/apps/agent-server/tests/test_adk_web_agent.py +12 -0
  19. package/template/apps/server/package.json +4 -1
  20. package/template/apps/server/src/agent/run-facade.ts +2 -7
  21. package/template/apps/server/src/agent/tool-registry.ts +2 -6
  22. package/template/apps/server/src/application-services.ts +50 -0
  23. package/template/apps/server/src/audit/drizzle-log-store.ts +25 -0
  24. package/template/apps/server/src/audit/search-summary.ts +2 -6
  25. package/template/apps/server/src/auth/credential-restriction.ts +1 -0
  26. package/template/apps/server/src/auth/password.ts +30 -21
  27. package/template/apps/server/src/auth/routes.test.ts +44 -3
  28. package/template/apps/server/src/auth/routes.ts +6 -1
  29. package/template/apps/server/src/auth/runtime.ts +4 -1
  30. package/template/apps/server/src/auth/service.ts +25 -7
  31. package/template/apps/server/src/configuration/bootstrap.ts +20 -1
  32. package/template/apps/server/src/configuration/definition.test.ts +71 -0
  33. package/template/apps/server/src/configuration/definition.ts +242 -12
  34. package/template/apps/server/src/configuration/drizzle-repository.ts +36 -2
  35. package/template/apps/server/src/configuration/repository.ts +27 -2
  36. package/template/apps/server/src/configuration/routes.ts +4 -1
  37. package/template/apps/server/src/configuration/service.test.ts +100 -0
  38. package/template/apps/server/src/configuration/service.ts +50 -10
  39. package/template/apps/server/src/data-access/scoped-repository.integration.test.ts +3 -2
  40. package/template/apps/server/src/data-governance/export/service.ts +2 -6
  41. package/template/apps/server/src/example-modules.ts +4 -1
  42. package/template/apps/server/src/guards.ts +18 -5
  43. package/template/apps/server/src/http/request-source.test.ts +85 -0
  44. package/template/apps/server/src/http/request-source.ts +90 -0
  45. package/template/apps/server/src/index.ts +23 -6
  46. package/template/apps/server/src/license/routes.ts +2 -0
  47. package/template/apps/server/src/license/runtime-service.ts +10 -11
  48. package/template/apps/server/src/module-bootstrap.ts +2 -2
  49. package/template/apps/server/src/module-host/request-context.ts +6 -6
  50. package/template/apps/server/src/module-host/storage-scope.ts +2 -9
  51. package/template/apps/server/src/module-host/user-directory-port.ts +2 -6
  52. package/template/apps/server/src/notification/channel-adapter.ts +46 -0
  53. package/template/apps/server/src/notification/delivery-policy.test.ts +59 -0
  54. package/template/apps/server/src/notification/delivery-policy.ts +37 -0
  55. package/template/apps/server/src/notification/delivery-repository.ts +198 -0
  56. package/template/apps/server/src/notification/delivery-worker.test.ts +87 -0
  57. package/template/apps/server/src/notification/delivery-worker.ts +88 -0
  58. package/template/apps/server/src/notification/drizzle-management.ts +180 -0
  59. package/template/apps/server/src/notification/drizzle-query.ts +160 -0
  60. package/template/apps/server/src/notification/drizzle-repository.integration.test.ts +301 -0
  61. package/template/apps/server/src/notification/drizzle-repository.ts +156 -90
  62. package/template/apps/server/src/notification/extension-routes.test.ts +119 -0
  63. package/template/apps/server/src/notification/extension-routes.ts +111 -0
  64. package/template/apps/server/src/notification/memory-delivery-repository.ts +137 -0
  65. package/template/apps/server/src/notification/memory-support.ts +72 -0
  66. package/template/apps/server/src/notification/preference-repository.ts +95 -0
  67. package/template/apps/server/src/notification/recipient-directory.ts +104 -0
  68. package/template/apps/server/src/notification/repository.test.ts +171 -0
  69. package/template/apps/server/src/notification/repository.ts +179 -32
  70. package/template/apps/server/src/notification/revision-routes.test.ts +186 -0
  71. package/template/apps/server/src/notification/route-support.ts +225 -0
  72. package/template/apps/server/src/notification/routes.test.ts +182 -0
  73. package/template/apps/server/src/notification/routes.ts +225 -132
  74. package/template/apps/server/src/notification/service.test.ts +104 -0
  75. package/template/apps/server/src/notification/service.ts +140 -0
  76. package/template/apps/server/src/notification/smtp-adapter.test.ts +65 -0
  77. package/template/apps/server/src/notification/smtp-adapter.ts +68 -0
  78. package/template/apps/server/src/persistence.integration.test.ts +41 -2
  79. package/template/apps/server/src/route-guards.ts +1 -0
  80. package/template/apps/server/src/runtime-audit-list.test.ts +39 -0
  81. package/template/apps/server/src/runtime-development.ts +1 -0
  82. package/template/apps/server/src/runtime.test.ts +23 -9
  83. package/template/apps/server/src/runtime.ts +39 -2
  84. package/template/apps/server/src/scheduler/audit.ts +2 -11
  85. package/template/apps/server/src/scheduler/definitions.test.ts +6 -0
  86. package/template/apps/server/src/scheduler/definitions.ts +7 -0
  87. package/template/apps/server/src/scheduler/recovery-service.ts +2 -11
  88. package/template/apps/server/src/scheduler/routes.ts +2 -7
  89. package/template/apps/server/src/search/opensearch-client.test.ts +45 -0
  90. package/template/apps/server/src/search/opensearch-client.ts +145 -0
  91. package/template/apps/server/src/search/service.ts +2 -6
  92. package/template/apps/server/src/settings/routes.ts +15 -3
  93. package/template/apps/server/src/settings/runtime.ts +10 -1
  94. package/template/apps/server/src/storage/runtime.ts +13 -0
  95. package/template/apps/server/src/system/audit-query.ts +33 -4
  96. package/template/apps/server/src/system/audit-routes.test.ts +58 -4
  97. package/template/apps/server/src/system/audit-routes.ts +6 -5
  98. package/template/apps/server/src/system/department-organization.ts +320 -0
  99. package/template/apps/server/src/system/department-routes.test.ts +207 -48
  100. package/template/apps/server/src/system/department-routes.ts +114 -33
  101. package/template/apps/server/src/system/drizzle-repository.ts +15 -7
  102. package/template/apps/server/src/system/drizzle-scoped-repository.ts +5 -3
  103. package/template/apps/server/src/system/drizzle-system.ts +37 -9
  104. package/template/apps/server/src/system/drizzle-transaction-context.ts +14 -0
  105. package/template/apps/server/src/system/identity-route-config.ts +7 -2
  106. package/template/apps/server/src/system/mutation-runner.ts +23 -0
  107. package/template/apps/server/src/system/organization-postgres.integration.test.ts +176 -0
  108. package/template/apps/server/src/system/resource-access-response.ts +12 -6
  109. package/template/apps/server/src/system/role-department-scope-policy.ts +55 -0
  110. package/template/apps/server/src/system/route-helpers.ts +2 -5
  111. package/template/apps/server/src/system/route-types.ts +12 -3
  112. package/template/apps/server/src/system/routes-validation.test.ts +26 -0
  113. package/template/apps/server/src/system/routes.test.ts +10 -2
  114. package/template/apps/server/src/system/routes.ts +70 -36
  115. package/template/apps/server/src/system/seed.ts +7 -0
  116. package/template/apps/server/src/work-order/data-scope.integration.test.ts +9 -2
  117. package/template/apps/server/src/work-order/opensearch-index.test.ts +97 -0
  118. package/template/apps/server/src/work-order/opensearch-index.ts +313 -0
  119. package/template/apps/server/src/work-order/search-provider.ts +60 -1
  120. package/template/apps/server/src/work-order/service.ts +42 -10
  121. package/template/apps/web/src/app/error-pages.ts +9 -0
  122. package/template/apps/web/src/components/auth/PasswordChangeForm.vue +16 -11
  123. package/template/apps/web/src/components/auth/PasswordChangeForm.webtest.ts +14 -0
  124. package/template/apps/web/src/components/common/FormDialog.vue +16 -2
  125. package/template/apps/web/src/components/common/ModalLayout.webtest.ts +20 -1
  126. package/template/apps/web/src/composables/useGlobalSearch.ts +68 -0
  127. package/template/apps/web/src/composables/usePlatformSettings.ts +8 -7
  128. package/template/apps/web/src/layout/GlobalSearchResults.vue +58 -0
  129. package/template/apps/web/src/layout/NavigationSearchDialog.vue +42 -6
  130. package/template/apps/web/src/layout/NavigationSearchDialog.webtest.ts +71 -0
  131. package/template/apps/web/src/layout/NotificationMenu.vue +73 -31
  132. package/template/apps/web/src/layout/NotificationMenu.webtest.ts +44 -1
  133. package/template/apps/web/src/layout/NotificationMenuItem.vue +61 -0
  134. package/template/apps/web/src/layout/NotificationPreferencesDialog.vue +181 -0
  135. package/template/apps/web/src/layout/NotificationPreferencesDialog.webtest.ts +80 -0
  136. package/template/apps/web/src/lib/date-time.ts +22 -10
  137. package/template/apps/web/src/lib/date-time.webtest.ts +9 -1
  138. package/template/apps/web/src/main.ts +14 -1
  139. package/template/apps/web/src/pages/auth/ChangePasswordPage.vue +16 -1
  140. package/template/apps/web/src/pages/configuration/components/ModuleConfigVersionList.vue +1 -0
  141. package/template/apps/web/src/pages/configuration/components/ModuleConfigurationEditor.vue +10 -0
  142. package/template/apps/web/src/pages/configuration/components/ModuleConfigurationWorkbench.vue +37 -6
  143. package/template/apps/web/src/pages/errors/PlatformErrorPage.vue +115 -0
  144. package/template/apps/web/src/pages/errors/PlatformErrorPage.webtest.ts +44 -0
  145. package/template/apps/web/src/pages/errors/error-page-extension.ts +26 -0
  146. package/template/apps/web/src/pages/system/SystemNotificationsPage.vue +136 -68
  147. package/template/apps/web/src/pages/system/SystemNotificationsPage.webtest.ts +224 -12
  148. package/template/apps/web/src/pages/system/audit-log-presenter.ts +86 -0
  149. package/template/apps/web/src/pages/system/audit-time-range.ts +28 -0
  150. package/template/apps/web/src/pages/system/components/AuditActionCell.vue +10 -69
  151. package/template/apps/web/src/pages/system/components/AuditActionCell.webtest.ts +20 -27
  152. package/template/apps/web/src/pages/system/components/AuditLogDetailDialog.vue +134 -0
  153. package/template/apps/web/src/pages/system/components/AuditLogDetailDialog.webtest.ts +76 -0
  154. package/template/apps/web/src/pages/system/components/AuditLogFilters.vue +116 -52
  155. package/template/apps/web/src/pages/system/components/AuditLogFilters.webtest.ts +52 -15
  156. package/template/apps/web/src/pages/system/components/NotificationHistoryDialog.vue +129 -0
  157. package/template/apps/web/src/pages/system/components/NotificationManagementCard.vue +91 -0
  158. package/template/apps/web/src/pages/system/components/NotificationPublishDialog.vue +121 -0
  159. package/template/apps/web/src/pages/system/components/NotificationPublishForm.vue +162 -1
  160. package/template/apps/web/src/pages/system/components/SystemResourceActions.vue +68 -0
  161. package/template/apps/web/src/pages/system/components/SystemResourceEditor.vue +74 -0
  162. package/template/apps/web/src/pages/system/components/SystemResourceFilters.vue +3 -4
  163. package/template/apps/web/src/pages/system/components/SystemResourcePage.vue +91 -98
  164. package/template/apps/web/src/pages/system/components/SystemResourcePage.webtest.ts +68 -0
  165. package/template/apps/web/src/pages/system/components/SystemResourceTable.vue +20 -1
  166. package/template/apps/web/src/pages/system/components/SystemResourceTable.webtest.ts +28 -7
  167. package/template/apps/web/src/pages/system/components/department/DepartmentOrganizationForm.vue +210 -0
  168. package/template/apps/web/src/pages/system/components/department/DepartmentTransitionDialog.vue +112 -0
  169. package/template/apps/web/src/pages/system/components/user-account/UserAccountForm.vue +17 -4
  170. package/template/apps/web/src/pages/system/composables/useDepartmentTransitions.ts +79 -0
  171. package/template/apps/web/src/pages/system/composables/useNotificationPermissions.ts +14 -0
  172. package/template/apps/web/src/pages/system/composables/useSystemResource.ts +2 -0
  173. package/template/apps/web/src/pages/system/composables/useSystemResource.webtest.ts +15 -2
  174. package/template/apps/web/src/pages/system/resource-config.ts +12 -4
  175. package/template/apps/web/src/router/error-navigation.ts +50 -0
  176. package/template/apps/web/src/router/error-navigation.webtest.ts +106 -0
  177. package/template/apps/web/src/router/index.ts +71 -0
  178. package/template/apps/web/src/router/index.webtest.ts +29 -0
  179. package/template/apps/web/src/router/manifest-routes.webtest.ts +4 -0
  180. package/template/apps/web/src/router/shared-scaffold-neutrality.webtest.ts +12 -0
  181. package/template/apps/web/src/services/auth-api.ts +5 -0
  182. package/template/apps/web/src/services/http.ts +43 -6
  183. package/template/apps/web/src/services/http.webtest.ts +70 -0
  184. package/template/apps/web/src/services/notification-api.ts +85 -2
  185. package/template/apps/web/src/services/notification-api.webtest.ts +110 -0
  186. package/template/apps/web/src/services/search-api.ts +39 -0
  187. package/template/apps/web/src/services/system-api.ts +18 -0
  188. package/template/apps/web/vitest.config.ts +1 -0
  189. package/template/docker-compose.yml +66 -0
  190. package/template/docs/architecture/ai-runtime.md +14 -5
  191. package/template/docs/architecture/search-provider-protocol.md +38 -2
  192. package/template/docs/development/custom-error-pages.md +78 -0
  193. package/template/docs/development/custom-login-page.md +3 -3
  194. package/template/docs/platform/agent-runtime.md +32 -6
  195. package/template/docs/platform/audit-reliability.md +46 -2
  196. package/template/docs/platform/module-configuration.md +13 -4
  197. package/template/docs/platform/notifications.md +67 -11
  198. package/template/docs/platform/organization-membership.md +17 -3
  199. package/template/docs/platform/system-crud-api.md +16 -0
  200. package/template/docs/platform/web-system-crud.md +6 -2
  201. package/template/package.json +4 -0
  202. package/template/packages/config/index.test.ts +45 -0
  203. package/template/packages/config/package.json +1 -1
  204. package/template/packages/config/src/platform.ts +169 -48
  205. package/template/packages/database/drizzle/0035_material_nightshade.sql +10 -0
  206. package/template/packages/database/drizzle/0036_hesitant_speed.sql +35 -0
  207. package/template/packages/database/drizzle/0037_absent_nick_fury.sql +2 -0
  208. package/template/packages/database/drizzle/0038_uneven_wasp.sql +38 -0
  209. package/template/packages/database/drizzle/meta/0035_snapshot.json +7331 -0
  210. package/template/packages/database/drizzle/meta/0036_snapshot.json +7436 -0
  211. package/template/packages/database/drizzle/meta/0037_snapshot.json +7457 -0
  212. package/template/packages/database/drizzle/meta/0038_snapshot.json +7749 -0
  213. package/template/packages/database/drizzle/meta/_journal.json +28 -0
  214. package/template/packages/database/package.json +1 -1
  215. package/template/packages/database/src/schema/identity.ts +7 -0
  216. package/template/packages/database/src/schema/notifications.ts +135 -0
  217. package/template/packages/database/src/schema-notification-delivery.test.ts +54 -0
  218. package/template/packages/database/src/schema-workflow-notification.test.ts +40 -1
  219. package/template/packages/modules/package.json +1 -1
  220. package/template/packages/modules/src/system-api-permissions.ts +54 -0
  221. package/template/packages/modules/src/system-audit-actions.ts +10 -0
  222. package/template/packages/modules/src/system-features.ts +1 -1
  223. package/template/packages/modules/src/system-module-catalog.ts +2 -1
  224. package/template/packages/modules/src/system-modules.test.ts +13 -1
  225. package/template/packages/modules/src/system-modules.ts +12 -0
  226. package/template/packages/modules/src/system-permissions.ts +9 -5
  227. package/template/packages/server-sdk/package.json +1 -1
  228. package/template/packages/shared/package.json +1 -1
  229. package/template/packages/shared/src/audit.ts +25 -0
  230. package/template/packages/shared/src/module-configuration.ts +5 -0
  231. package/template/packages/shared/src/notification.ts +92 -1
  232. package/template/packages/shared/src/password.ts +7 -2
  233. package/template/packages/shared/src/platform-settings.ts +2 -0
  234. package/template/packages/storage/package.json +1 -1
  235. package/template/packages/storage/src/upload-service.test.ts +16 -0
  236. package/template/packages/storage/src/upload-service.ts +5 -1
  237. package/template/scripts/notification-postgres-regression.ts +27 -0
@@ -0,0 +1,180 @@
1
+ import {
2
+ notificationRevisions,
3
+ platformNotifications,
4
+ } from "@southwind-ai/database";
5
+ import type {
6
+ NotificationRevision,
7
+ PageResult,
8
+ PublishNotificationInput,
9
+ UpdateNotificationInput,
10
+ } from "@southwind-ai/shared";
11
+ import { and, desc, eq, inArray, sql } from "drizzle-orm";
12
+ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
13
+ import type { RequestActor } from "../guards.js";
14
+ import { toNotification, toRevision } from "./drizzle-query.js";
15
+
16
+ export function publishNotification(
17
+ db: NodePgDatabase,
18
+ input: PublishNotificationInput,
19
+ actor: RequestActor,
20
+ ) {
21
+ return db.transaction(async (tx) => {
22
+ const now = new Date();
23
+ const [row] = await tx
24
+ .insert(platformNotifications)
25
+ .values({
26
+ id: Bun.randomUUIDv7(),
27
+ ...input,
28
+ scheduledFor: input.scheduledFor
29
+ ? new Date(input.scheduledFor)
30
+ : undefined,
31
+ status: input.scheduledFor ? "scheduled" : "published",
32
+ publishedAt: input.scheduledFor ? new Date(input.scheduledFor) : now,
33
+ createdAt: now,
34
+ createdBy: actor.id,
35
+ updatedAt: now,
36
+ updatedBy: actor.id,
37
+ revision: 1,
38
+ })
39
+ .onConflictDoNothing()
40
+ .returning();
41
+ if (!row && input.sourceKey) {
42
+ const [existing] = await tx
43
+ .select()
44
+ .from(platformNotifications)
45
+ .where(eq(platformNotifications.sourceKey, input.sourceKey))
46
+ .limit(1);
47
+ if (existing) return toNotification(existing);
48
+ }
49
+ if (!row) throw new Error("通知发布未返回记录");
50
+ await tx.insert(notificationRevisions).values({
51
+ notificationId: row.id,
52
+ revision: row.revision,
53
+ title: row.title,
54
+ summary: row.summary,
55
+ content: row.content,
56
+ category: row.category,
57
+ editedAt: now,
58
+ editedBy: actor.id,
59
+ });
60
+ return toNotification(row);
61
+ });
62
+ }
63
+
64
+ export function updateNotification(
65
+ db: NodePgDatabase,
66
+ notificationId: string,
67
+ input: UpdateNotificationInput,
68
+ actor: RequestActor,
69
+ ) {
70
+ return db.transaction(async (tx) => {
71
+ const [current] = await tx
72
+ .select()
73
+ .from(platformNotifications)
74
+ .where(
75
+ and(
76
+ eq(platformNotifications.id, notificationId),
77
+ eq(platformNotifications.status, "published"),
78
+ ),
79
+ )
80
+ .for("update")
81
+ .limit(1);
82
+ if (!current) return undefined;
83
+ if (sameContent(current, input)) {
84
+ return { notification: toNotification(current), changed: false };
85
+ }
86
+ const editedAt = new Date();
87
+ const [updated] = await tx
88
+ .update(platformNotifications)
89
+ .set({
90
+ ...input,
91
+ revision: sql`${platformNotifications.revision} + 1`,
92
+ updatedAt: editedAt,
93
+ updatedBy: actor.id,
94
+ })
95
+ .where(eq(platformNotifications.id, notificationId))
96
+ .returning();
97
+ if (!updated) throw new Error("通知更新未返回记录");
98
+ await tx.insert(notificationRevisions).values({
99
+ notificationId,
100
+ revision: updated.revision,
101
+ title: updated.title,
102
+ summary: updated.summary,
103
+ content: updated.content,
104
+ category: updated.category,
105
+ editedAt,
106
+ editedBy: actor.id,
107
+ });
108
+ return { notification: toNotification(updated), changed: true };
109
+ });
110
+ }
111
+
112
+ export async function listNotificationRevisions(
113
+ db: NodePgDatabase,
114
+ notificationId: string,
115
+ page: number,
116
+ pageSize: number,
117
+ ): Promise<PageResult<NotificationRevision> | undefined> {
118
+ const [notification] = await db
119
+ .select({ id: platformNotifications.id })
120
+ .from(platformNotifications)
121
+ .where(eq(platformNotifications.id, notificationId))
122
+ .limit(1);
123
+ if (!notification) return undefined;
124
+ const [rows, [{ count = 0 } = { count: 0 }]] = await Promise.all([
125
+ db
126
+ .select()
127
+ .from(notificationRevisions)
128
+ .where(eq(notificationRevisions.notificationId, notificationId))
129
+ .orderBy(desc(notificationRevisions.revision))
130
+ .limit(pageSize)
131
+ .offset((page - 1) * pageSize),
132
+ db
133
+ .select({ count: sql<number>`count(*)::int` })
134
+ .from(notificationRevisions)
135
+ .where(eq(notificationRevisions.notificationId, notificationId)),
136
+ ]);
137
+ return {
138
+ items: rows.map(toRevision),
139
+ total: count,
140
+ page,
141
+ pageSize,
142
+ };
143
+ }
144
+
145
+ export async function archiveNotification(
146
+ db: NodePgDatabase,
147
+ notificationId: string,
148
+ actor: RequestActor,
149
+ ) {
150
+ const now = new Date();
151
+ const [row] = await db
152
+ .update(platformNotifications)
153
+ .set({
154
+ status: "archived",
155
+ archivedAt: now,
156
+ archivedBy: actor.id,
157
+ updatedAt: now,
158
+ updatedBy: actor.id,
159
+ })
160
+ .where(
161
+ and(
162
+ eq(platformNotifications.id, notificationId),
163
+ inArray(platformNotifications.status, ["published", "scheduled"]),
164
+ ),
165
+ )
166
+ .returning();
167
+ return row ? toNotification(row) : undefined;
168
+ }
169
+
170
+ function sameContent(
171
+ current: typeof platformNotifications.$inferSelect,
172
+ input: UpdateNotificationInput,
173
+ ) {
174
+ return (
175
+ current.title === input.title &&
176
+ current.summary === input.summary &&
177
+ current.content === input.content &&
178
+ current.category === input.category
179
+ );
180
+ }
@@ -0,0 +1,160 @@
1
+ import {
2
+ notificationFavorites,
3
+ notificationReads,
4
+ notificationRevisions,
5
+ platformNotifications,
6
+ } from "@southwind-ai/database";
7
+ import type {
8
+ NotificationInboxFilters,
9
+ NotificationRevision,
10
+ PlatformNotification,
11
+ } from "@southwind-ai/shared";
12
+ import {
13
+ and,
14
+ eq,
15
+ ilike,
16
+ isNotNull,
17
+ isNull,
18
+ or,
19
+ sql,
20
+ type SQL,
21
+ } from "drizzle-orm";
22
+ import type { RequestActor } from "../guards.js";
23
+
24
+ export function toNotification(
25
+ row: typeof platformNotifications.$inferSelect,
26
+ ): PlatformNotification {
27
+ return {
28
+ id: row.id,
29
+ title: row.title,
30
+ summary: row.summary,
31
+ content: row.content,
32
+ category: row.category,
33
+ status: row.status as PlatformNotification["status"],
34
+ publishedAt: row.publishedAt.toISOString(),
35
+ scheduledFor: row.scheduledFor?.toISOString(),
36
+ createdAt: row.createdAt.toISOString(),
37
+ createdBy: row.createdBy,
38
+ updatedAt: row.updatedAt.toISOString(),
39
+ updatedBy: row.updatedBy,
40
+ archivedAt: row.archivedAt?.toISOString(),
41
+ archivedBy: row.archivedBy || undefined,
42
+ target: row.target || undefined,
43
+ recipientUserId: row.recipientUserId || undefined,
44
+ recipientUserIds: row.recipientUserIds,
45
+ recipientRoleCodes: row.recipientRoleCodes,
46
+ recipientDepartmentIds: row.recipientDepartmentIds,
47
+ includeChildDepartments: row.includeChildDepartments,
48
+ deliveryChannels: row.deliveryChannels,
49
+ sourceKey: row.sourceKey || undefined,
50
+ revision: row.revision,
51
+ };
52
+ }
53
+
54
+ export function toRevision(
55
+ row: typeof notificationRevisions.$inferSelect,
56
+ ): NotificationRevision {
57
+ return {
58
+ notificationId: row.notificationId,
59
+ revision: row.revision,
60
+ title: row.title,
61
+ summary: row.summary,
62
+ content: row.content,
63
+ category: row.category,
64
+ editedAt: row.editedAt.toISOString(),
65
+ editedBy: row.editedBy,
66
+ };
67
+ }
68
+
69
+ export function audienceWhere(
70
+ actor: Pick<RequestActor, "id" | "roleCodes" | "scopeContext">,
71
+ ): SQL {
72
+ const roleClauses = actor.roleCodes.map(
73
+ (role) =>
74
+ sql`${platformNotifications.recipientRoleCodes} @> ${JSON.stringify([role])}::jsonb`,
75
+ );
76
+ return or(
77
+ and(
78
+ isNull(platformNotifications.recipientUserId),
79
+ sql`jsonb_array_length(${platformNotifications.recipientUserIds}) = 0`,
80
+ sql`jsonb_array_length(${platformNotifications.recipientRoleCodes}) = 0`,
81
+ sql`jsonb_array_length(${platformNotifications.recipientDepartmentIds}) = 0`,
82
+ ),
83
+ eq(platformNotifications.recipientUserId, actor.id),
84
+ sql`${platformNotifications.recipientUserIds} @> ${JSON.stringify([actor.id])}::jsonb`,
85
+ ...(actor.scopeContext?.departmentId
86
+ ? [
87
+ sql`(
88
+ ${platformNotifications.recipientDepartmentIds} @>
89
+ ${JSON.stringify([actor.scopeContext.departmentId])}::jsonb
90
+ or (
91
+ ${platformNotifications.includeChildDepartments} = true
92
+ and exists (
93
+ with recursive ancestors as (
94
+ select id, parent_id from departments
95
+ where id = ${actor.scopeContext.departmentId}
96
+ union all
97
+ select department.id, department.parent_id
98
+ from departments department
99
+ join ancestors child on child.parent_id = department.id
100
+ )
101
+ select 1 from ancestors
102
+ where ${platformNotifications.recipientDepartmentIds} @>
103
+ jsonb_build_array(ancestors.id)
104
+ )
105
+ )
106
+ )`,
107
+ ]
108
+ : []),
109
+ ...roleClauses,
110
+ )!;
111
+ }
112
+
113
+ export function inboxWhere(
114
+ actor: Pick<RequestActor, "id" | "roleCodes" | "scopeContext">,
115
+ filters: NotificationInboxFilters,
116
+ ): SQL {
117
+ const conditions: SQL[] = [
118
+ eq(platformNotifications.status, "published"),
119
+ audienceWhere(actor),
120
+ ];
121
+ const keyword = filters.q?.trim();
122
+ if (keyword) {
123
+ conditions.push(
124
+ or(
125
+ ilike(platformNotifications.title, `%${keyword}%`),
126
+ ilike(platformNotifications.summary, `%${keyword}%`),
127
+ ilike(platformNotifications.content, `%${keyword}%`),
128
+ ilike(platformNotifications.category, `%${keyword}%`),
129
+ )!,
130
+ );
131
+ }
132
+ const category = filters.category?.trim();
133
+ if (category) conditions.push(eq(platformNotifications.category, category));
134
+ if (filters.read !== undefined) {
135
+ conditions.push(
136
+ filters.read === "read"
137
+ ? isNotNull(notificationReads.readAt)
138
+ : isNull(notificationReads.readAt),
139
+ );
140
+ }
141
+ if (filters.favorite !== undefined) {
142
+ conditions.push(
143
+ filters.favorite
144
+ ? isNotNull(notificationFavorites.favoritedAt)
145
+ : isNull(notificationFavorites.favoritedAt),
146
+ );
147
+ }
148
+ return and(...conditions)!;
149
+ }
150
+
151
+ export function searchWhere(query?: string): SQL | undefined {
152
+ const keyword = query?.trim();
153
+ return keyword
154
+ ? or(
155
+ ilike(platformNotifications.title, `%${keyword}%`),
156
+ ilike(platformNotifications.summary, `%${keyword}%`),
157
+ ilike(platformNotifications.category, `%${keyword}%`),
158
+ )
159
+ : undefined;
160
+ }
@@ -0,0 +1,301 @@
1
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2
+ import { resolve } from "node:path";
3
+ import { drizzle } from "drizzle-orm/node-postgres";
4
+ import { migrate } from "drizzle-orm/node-postgres/migrator";
5
+ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
6
+ import { Pool } from "pg";
7
+ import type { RequestActor } from "../guards.js";
8
+ import { buildActorScopeContexts } from "../data-access/context.js";
9
+ import { DrizzleNotificationDeliveryRepository } from "./delivery-repository.js";
10
+ import { DrizzleNotificationPreferenceRepository } from "./preference-repository.js";
11
+ import { DrizzleNotificationRepository } from "./drizzle-repository.js";
12
+
13
+ const databaseUrl = process.env.NOTIFICATION_TEST_DATABASE_URL;
14
+ const describePostgres = databaseUrl ? describe : describe.skip;
15
+
16
+ describePostgres("PostgreSQL 通知 Repository", () => {
17
+ let pool: Pool;
18
+ let db: NodePgDatabase;
19
+ let repository: DrizzleNotificationRepository;
20
+ let rootDepartmentId: string;
21
+
22
+ beforeAll(async () => {
23
+ pool = new Pool({ connectionString: databaseUrl });
24
+ db = drizzle(pool);
25
+ await migrate(db, {
26
+ migrationsFolder: resolve(
27
+ import.meta.dir,
28
+ "../../../../packages/database/drizzle",
29
+ ),
30
+ migrationsSchema: "public",
31
+ migrationsTable: "__notification_test_migrations",
32
+ });
33
+ await pool.query(
34
+ "truncate table notification_delivery_outbox, notification_preferences, notification_favorites, notification_reads, notification_revisions, platform_notifications",
35
+ );
36
+ await pool.query(`insert into users (
37
+ id, username, display_name, status, created_by, updated_by
38
+ ) values
39
+ ('notification-user-a', 'notification-user-a', '通知用户 A', 'active', 'test', 'test'),
40
+ ('notification-user-b', 'notification-user-b', '通知用户 B', 'active', 'test', 'test')
41
+ on conflict (id) do nothing`);
42
+ const root = await pool.query<{ id: string }>(
43
+ "select id from departments where parent_id is null and deleted_at is null limit 1",
44
+ );
45
+ rootDepartmentId = root.rows[0]?.id || "notification-root";
46
+ if (root.rows.length === 0) {
47
+ await pool.query(
48
+ `insert into departments
49
+ (id, name, code, "order", status, created_by, updated_by)
50
+ values ($1, '通知测试根部门', 'NOTIFICATION_ROOT', 1, 'active', 'test', 'test')`,
51
+ [rootDepartmentId],
52
+ );
53
+ }
54
+ await pool.query(
55
+ `insert into departments
56
+ (id, parent_id, name, code, "order", status, created_by, updated_by)
57
+ values
58
+ ('notification-child', $1, '通知测试子部门', 'NOTIFICATION_CHILD', 1, 'active', 'test', 'test')
59
+ on conflict (id) do update set parent_id = excluded.parent_id`,
60
+ [rootDepartmentId],
61
+ );
62
+ await pool.query(
63
+ "update users set department_id = 'notification-child' where id = 'notification-user-a'",
64
+ );
65
+ repository = new DrizzleNotificationRepository(db);
66
+ });
67
+
68
+ afterAll(async () => {
69
+ await pool?.end();
70
+ });
71
+
72
+ test("组合筛选与 total 使用同一 Actor 可见范围", async () => {
73
+ await repository.publish(notice("季度安全提醒", "安全"), admin);
74
+ const selected = await repository.publish(
75
+ notice("安全维护窗口", "安全"),
76
+ admin,
77
+ );
78
+ await repository.publish(notice("产品更新", "产品"), admin);
79
+ await repository.publish(
80
+ {
81
+ ...notice("其他用户维护通知", "安全"),
82
+ recipientUserId: userB.id,
83
+ },
84
+ admin,
85
+ );
86
+ await repository.markRead(selected.id, userA);
87
+ await repository.setFavorite(selected.id, true, userA);
88
+
89
+ const result = await repository.listInbox(userA, 1, 1, {
90
+ q: "维护",
91
+ category: "安全",
92
+ read: "read",
93
+ favorite: true,
94
+ });
95
+
96
+ expect(result).toMatchObject({ total: 1, page: 1, pageSize: 1 });
97
+ expect(result.items[0]).toMatchObject({
98
+ id: selected.id,
99
+ read: true,
100
+ favorite: true,
101
+ });
102
+ });
103
+
104
+ test("收藏跨 Repository 持久化、按 Actor 隔离且不改变已读", async () => {
105
+ const published = await repository.publish(
106
+ notice("持久化收藏测试", "系统"),
107
+ admin,
108
+ );
109
+ const favorites = await Promise.all([
110
+ repository.setFavorite(published.id, true, userA),
111
+ repository.setFavorite(published.id, true, userA),
112
+ ]);
113
+ expect(favorites.filter((result) => result?.changed)).toHaveLength(1);
114
+
115
+ const restarted = new DrizzleNotificationRepository(drizzle(pool));
116
+ expect((await restarted.listInbox(userA, 1, 10)).items).toContainEqual(
117
+ expect.objectContaining({
118
+ id: published.id,
119
+ favorite: true,
120
+ read: false,
121
+ }),
122
+ );
123
+ expect((await restarted.listInbox(userB, 1, 10)).items).toContainEqual(
124
+ expect.objectContaining({
125
+ id: published.id,
126
+ favorite: false,
127
+ read: false,
128
+ }),
129
+ );
130
+
131
+ await restarted.markRead(published.id, userA);
132
+ const removals = await Promise.all([
133
+ restarted.setFavorite(published.id, false, userA),
134
+ restarted.setFavorite(published.id, false, userA),
135
+ ]);
136
+ expect(removals.filter((result) => result?.changed)).toHaveLength(1);
137
+ expect((await restarted.listInbox(userA, 1, 10)).items).toContainEqual(
138
+ expect.objectContaining({
139
+ id: published.id,
140
+ favorite: false,
141
+ read: true,
142
+ }),
143
+ );
144
+ });
145
+
146
+ test("不可见通知的收藏和取消收藏统一拒绝", async () => {
147
+ const targeted = await repository.publish(
148
+ {
149
+ ...notice("仅用户 A 可见", "审批"),
150
+ recipientUserId: userA.id,
151
+ },
152
+ admin,
153
+ );
154
+
155
+ expect(
156
+ await repository.setFavorite(targeted.id, true, userB),
157
+ ).toBeUndefined();
158
+ expect(
159
+ await repository.setFavorite(targeted.id, false, userB),
160
+ ).toBeUndefined();
161
+ });
162
+
163
+ test("并发修改串行生成版本号并由重建 Repository 查询时间历史", async () => {
164
+ const published = await repository.publish(
165
+ notice("版本历史公告", "系统"),
166
+ admin,
167
+ );
168
+ const results = await Promise.all([
169
+ repository.update(published.id, notice("版本历史公告 A", "安全"), userA),
170
+ repository.update(published.id, notice("版本历史公告 B", "产品"), userB),
171
+ ]);
172
+ expect(results.every((result) => result?.changed)).toBe(true);
173
+ expect(
174
+ results.map((result) => result?.notification.revision).sort(),
175
+ ).toEqual([2, 3]);
176
+
177
+ const restarted = new DrizzleNotificationRepository(drizzle(pool));
178
+ const history = await restarted.listRevisions(published.id, 1, 10);
179
+ expect(history?.total).toBe(3);
180
+ expect(history?.items.map(({ revision }) => revision)).toEqual([3, 2, 1]);
181
+ expect(
182
+ history?.items.every(
183
+ ({ editedAt, editedBy }) => Boolean(editedAt) && Boolean(editedBy),
184
+ ),
185
+ ).toBe(true);
186
+ });
187
+
188
+ test("归档公告拒绝修改但保留版本历史", async () => {
189
+ const published = await repository.publish(
190
+ notice("归档历史公告", "系统"),
191
+ admin,
192
+ );
193
+ await repository.archive(published.id, admin);
194
+
195
+ expect(
196
+ await repository.update(
197
+ published.id,
198
+ notice("归档后修改", "系统"),
199
+ admin,
200
+ ),
201
+ ).toBeUndefined();
202
+ expect((await repository.listRevisions(published.id, 1, 10))?.total).toBe(
203
+ 1,
204
+ );
205
+ });
206
+
207
+ test("父部门通知包含子部门用户,其他用户不可见", async () => {
208
+ const targeted = await repository.publish(
209
+ {
210
+ ...notice("部门定向通知", "组织"),
211
+ recipientDepartmentIds: [rootDepartmentId],
212
+ includeChildDepartments: true,
213
+ },
214
+ admin,
215
+ );
216
+ const scopedUserA = actor(
217
+ "notification-user-a",
218
+ ["member"],
219
+ "notification-child",
220
+ );
221
+ expect(
222
+ (await repository.listInbox(scopedUserA, 1, 100)).items,
223
+ ).toContainEqual(expect.objectContaining({ id: targeted.id }));
224
+ expect(
225
+ (await repository.listInbox(userB, 1, 100)).items,
226
+ ).not.toContainEqual(expect.objectContaining({ id: targeted.id }));
227
+ });
228
+
229
+ test("偏好与 outbox 跨 Repository 持久化,lease token 防止伪完成", async () => {
230
+ const preferences = new DrizzleNotificationPreferenceRepository(db);
231
+ expect(
232
+ await preferences.save(
233
+ userA.id,
234
+ { enabledChannels: ["email"], disabledCategories: ["营销"] },
235
+ userA.id,
236
+ ),
237
+ ).toMatchObject({
238
+ enabledChannels: ["email"],
239
+ disabledCategories: ["营销"],
240
+ });
241
+ expect(
242
+ await new DrizzleNotificationPreferenceRepository(db).get(userA.id),
243
+ ).toMatchObject({ enabledChannels: ["email"] });
244
+
245
+ const published = await repository.publish(
246
+ notice("外部投递通知", "系统"),
247
+ admin,
248
+ );
249
+ const deliveries = new DrizzleNotificationDeliveryRepository(db);
250
+ expect(
251
+ await deliveries.enqueue([
252
+ {
253
+ notificationId: published.id,
254
+ userId: userA.id,
255
+ channel: "email",
256
+ subject: published.title,
257
+ content: published.content,
258
+ },
259
+ ]),
260
+ ).toBe(1);
261
+ const [claimed] = await deliveries.claim(new Date(), 10);
262
+ expect(claimed).toBeDefined();
263
+ expect(await deliveries.complete(claimed!.id, "forged-token")).toBe(false);
264
+ expect(
265
+ await deliveries.complete(claimed!.id, claimed!.leaseToken, "smtp-1"),
266
+ ).toBe(true);
267
+ expect((await deliveries.list(published.id))[0]).toMatchObject({
268
+ status: "delivered",
269
+ attemptCount: 1,
270
+ });
271
+ });
272
+ });
273
+
274
+ function notice(title: string, category: string) {
275
+ return {
276
+ title,
277
+ summary: `${title}摘要`,
278
+ content: `${title}正文`,
279
+ category,
280
+ };
281
+ }
282
+
283
+ const admin = actor("notification-admin", ["admin"]);
284
+ const userA = actor("notification-user-a", ["member"]);
285
+ const userB = actor("notification-user-b", ["member"]);
286
+
287
+ function actor(
288
+ id: string,
289
+ roleCodes: string[],
290
+ departmentId?: string,
291
+ ): RequestActor {
292
+ const scopes = buildActorScopeContexts(id, departmentId, []);
293
+ return {
294
+ id,
295
+ name: id,
296
+ type: "user",
297
+ roleCodes,
298
+ permissionKeys: ["system.notification.read"],
299
+ ...scopes,
300
+ };
301
+ }