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
@@ -1,31 +1,48 @@
1
- import { notificationReads, platformNotifications } from "@southwind-ai/database";
1
+ import {
2
+ notificationFavorites,
3
+ notificationReads,
4
+ platformNotifications,
5
+ } from "@southwind-ai/database";
2
6
  import type {
7
+ NotificationInboxFilters,
3
8
  NotificationInboxItem,
4
9
  PageResult,
5
10
  PlatformNotification,
6
11
  PublishNotificationInput,
12
+ UpdateNotificationInput,
7
13
  } from "@southwind-ai/shared";
8
- import { and, desc, eq, ilike, isNull, or, sql, type SQL } from "drizzle-orm";
14
+ import { and, desc, eq, sql } from "drizzle-orm";
9
15
  import type { NodePgDatabase } from "drizzle-orm/node-postgres";
10
16
  import type { RequestActor } from "../guards.js";
17
+ import {
18
+ audienceWhere,
19
+ inboxWhere,
20
+ searchWhere,
21
+ toNotification,
22
+ } from "./drizzle-query.js";
23
+ import {
24
+ archiveNotification,
25
+ listNotificationRevisions,
26
+ publishNotification,
27
+ updateNotification,
28
+ } from "./drizzle-management.js";
11
29
  import type { NotificationRepository } from "./repository.js";
12
30
 
13
31
  export class DrizzleNotificationRepository implements NotificationRepository {
14
32
  constructor(private readonly db: NodePgDatabase) {}
15
33
 
16
34
  async listInbox(
17
- actor: Pick<RequestActor, "id" | "roleCodes">,
35
+ actor: Pick<RequestActor, "id" | "roleCodes" | "scopeContext">,
18
36
  page: number,
19
37
  pageSize: number,
38
+ filters: NotificationInboxFilters = {},
20
39
  ) {
21
- const where = and(
22
- eq(platformNotifications.status, "published"),
23
- audienceWhere(actor),
24
- );
40
+ const where = inboxWhere(actor, filters);
25
41
  const rows = await this.db
26
42
  .select({
27
43
  notification: platformNotifications,
28
44
  readAt: notificationReads.readAt,
45
+ favoritedAt: notificationFavorites.favoritedAt,
29
46
  })
30
47
  .from(platformNotifications)
31
48
  .leftJoin(
@@ -35,6 +52,13 @@ export class DrizzleNotificationRepository implements NotificationRepository {
35
52
  eq(notificationReads.userId, actor.id),
36
53
  ),
37
54
  )
55
+ .leftJoin(
56
+ notificationFavorites,
57
+ and(
58
+ eq(notificationFavorites.notificationId, platformNotifications.id),
59
+ eq(notificationFavorites.userId, actor.id),
60
+ ),
61
+ )
38
62
  .where(where)
39
63
  .orderBy(desc(platformNotifications.publishedAt))
40
64
  .limit(pageSize)
@@ -42,12 +66,28 @@ export class DrizzleNotificationRepository implements NotificationRepository {
42
66
  const [{ count = 0 } = { count: 0 }] = await this.db
43
67
  .select({ count: sql<number>`count(*)::int` })
44
68
  .from(platformNotifications)
69
+ .leftJoin(
70
+ notificationReads,
71
+ and(
72
+ eq(notificationReads.notificationId, platformNotifications.id),
73
+ eq(notificationReads.userId, actor.id),
74
+ ),
75
+ )
76
+ .leftJoin(
77
+ notificationFavorites,
78
+ and(
79
+ eq(notificationFavorites.notificationId, platformNotifications.id),
80
+ eq(notificationFavorites.userId, actor.id),
81
+ ),
82
+ )
45
83
  .where(where);
46
84
  return {
47
- items: rows.map(({ notification, readAt }) => ({
85
+ items: rows.map(({ notification, readAt, favoritedAt }) => ({
48
86
  ...toNotification(notification),
49
87
  read: Boolean(readAt),
50
88
  readAt: readAt?.toISOString(),
89
+ favorite: Boolean(favoritedAt),
90
+ favoritedAt: favoritedAt?.toISOString(),
51
91
  })),
52
92
  total: count,
53
93
  page,
@@ -85,36 +125,59 @@ export class DrizzleNotificationRepository implements NotificationRepository {
85
125
  }
86
126
 
87
127
  async publish(input: PublishNotificationInput, actor: RequestActor) {
88
- const now = new Date();
128
+ return publishNotification(this.db, input, actor);
129
+ }
130
+
131
+ async listDueScheduled(now: Date, limit: number) {
132
+ const rows = await this.db
133
+ .select()
134
+ .from(platformNotifications)
135
+ .where(
136
+ and(
137
+ eq(platformNotifications.status, "scheduled"),
138
+ sql`${platformNotifications.scheduledFor} <= ${now}`,
139
+ ),
140
+ )
141
+ .orderBy(platformNotifications.scheduledFor)
142
+ .limit(limit);
143
+ return rows.map(toNotification);
144
+ }
145
+
146
+ async activateScheduled(notificationId: string, now: Date) {
89
147
  const [row] = await this.db
90
- .insert(platformNotifications)
91
- .values({
92
- id: Bun.randomUUIDv7(),
93
- ...input,
148
+ .update(platformNotifications)
149
+ .set({
94
150
  status: "published",
95
151
  publishedAt: now,
96
- createdAt: now,
97
- createdBy: actor.id,
98
152
  updatedAt: now,
99
- updatedBy: actor.id,
153
+ updatedBy: "notification-scheduler",
100
154
  })
101
- .onConflictDoNothing()
155
+ .where(
156
+ and(
157
+ eq(platformNotifications.id, notificationId),
158
+ eq(platformNotifications.status, "scheduled"),
159
+ sql`${platformNotifications.scheduledFor} <= ${now}`,
160
+ ),
161
+ )
102
162
  .returning();
103
- if (!row && input.sourceKey) {
104
- const [existing] = await this.db
105
- .select()
106
- .from(platformNotifications)
107
- .where(eq(platformNotifications.sourceKey, input.sourceKey))
108
- .limit(1);
109
- if (existing) return toNotification(existing);
110
- }
111
- if (!row) throw new Error("通知发布未返回记录");
112
- return toNotification(row);
163
+ return row ? toNotification(row) : undefined;
164
+ }
165
+
166
+ async update(
167
+ notificationId: string,
168
+ input: UpdateNotificationInput,
169
+ actor: RequestActor,
170
+ ) {
171
+ return updateNotification(this.db, notificationId, input, actor);
172
+ }
173
+
174
+ async listRevisions(notificationId: string, page: number, pageSize: number) {
175
+ return listNotificationRevisions(this.db, notificationId, page, pageSize);
113
176
  }
114
177
 
115
178
  async markRead(
116
179
  notificationId: string,
117
- actor: Pick<RequestActor, "id" | "roleCodes">,
180
+ actor: Pick<RequestActor, "id" | "roleCodes" | "scopeContext">,
118
181
  ) {
119
182
  const [notification] = await this.db
120
183
  .select({ id: platformNotifications.id })
@@ -160,74 +223,77 @@ export class DrizzleNotificationRepository implements NotificationRepository {
160
223
  : undefined;
161
224
  }
162
225
 
226
+ async setFavorite(
227
+ notificationId: string,
228
+ favorite: boolean,
229
+ actor: Pick<RequestActor, "id" | "roleCodes" | "scopeContext">,
230
+ ) {
231
+ if (!(await this.isVisible(notificationId, actor))) return undefined;
232
+ if (!favorite) {
233
+ const deleted = await this.db
234
+ .delete(notificationFavorites)
235
+ .where(
236
+ and(
237
+ eq(notificationFavorites.notificationId, notificationId),
238
+ eq(notificationFavorites.userId, actor.id),
239
+ ),
240
+ )
241
+ .returning({ notificationId: notificationFavorites.notificationId });
242
+ return {
243
+ success: true,
244
+ favorite: false,
245
+ changed: Boolean(deleted[0]),
246
+ } as const;
247
+ }
248
+ const favoritedAt = new Date();
249
+ const inserted = await this.db
250
+ .insert(notificationFavorites)
251
+ .values({ notificationId, userId: actor.id, favoritedAt })
252
+ .onConflictDoNothing()
253
+ .returning({ favoritedAt: notificationFavorites.favoritedAt });
254
+ const persistedAt =
255
+ inserted[0]?.favoritedAt ||
256
+ (
257
+ await this.db
258
+ .select({ favoritedAt: notificationFavorites.favoritedAt })
259
+ .from(notificationFavorites)
260
+ .where(
261
+ and(
262
+ eq(notificationFavorites.notificationId, notificationId),
263
+ eq(notificationFavorites.userId, actor.id),
264
+ ),
265
+ )
266
+ .limit(1)
267
+ )[0]?.favoritedAt;
268
+ return persistedAt
269
+ ? ({
270
+ success: true,
271
+ favorite: true,
272
+ changed: Boolean(inserted[0]),
273
+ favoritedAt: persistedAt.toISOString(),
274
+ } as const)
275
+ : undefined;
276
+ }
277
+
163
278
  async archive(notificationId: string, actor: RequestActor) {
164
- const now = new Date();
165
- const [row] = await this.db
166
- .update(platformNotifications)
167
- .set({
168
- status: "archived",
169
- archivedAt: now,
170
- archivedBy: actor.id,
171
- updatedAt: now,
172
- updatedBy: actor.id,
173
- })
279
+ return archiveNotification(this.db, notificationId, actor);
280
+ }
281
+
282
+ private async isVisible(
283
+ notificationId: string,
284
+ actor: Pick<RequestActor, "id" | "roleCodes" | "scopeContext">,
285
+ ) {
286
+ const [notification] = await this.db
287
+ .select({ id: platformNotifications.id })
288
+ .from(platformNotifications)
174
289
  .where(
175
290
  and(
176
291
  eq(platformNotifications.id, notificationId),
177
292
  eq(platformNotifications.status, "published"),
293
+ audienceWhere(actor),
178
294
  ),
179
295
  )
180
- .returning();
181
- return row ? toNotification(row) : undefined;
296
+ .limit(1);
297
+ return Boolean(notification);
182
298
  }
183
299
  }
184
-
185
- function toNotification(
186
- row: typeof platformNotifications.$inferSelect,
187
- ): PlatformNotification {
188
- return {
189
- id: row.id,
190
- title: row.title,
191
- summary: row.summary,
192
- content: row.content,
193
- category: row.category,
194
- status: row.status as PlatformNotification["status"],
195
- publishedAt: row.publishedAt.toISOString(),
196
- createdAt: row.createdAt.toISOString(),
197
- createdBy: row.createdBy,
198
- updatedAt: row.updatedAt.toISOString(),
199
- updatedBy: row.updatedBy,
200
- archivedAt: row.archivedAt?.toISOString(),
201
- archivedBy: row.archivedBy || undefined,
202
- target: row.target || undefined,
203
- recipientUserId: row.recipientUserId || undefined,
204
- recipientRoleCodes: row.recipientRoleCodes,
205
- sourceKey: row.sourceKey || undefined,
206
- };
207
- }
208
-
209
- function audienceWhere(actor: Pick<RequestActor, "id" | "roleCodes">): SQL {
210
- const roleClauses = actor.roleCodes.map(
211
- (role) =>
212
- sql`${platformNotifications.recipientRoleCodes} @> ${JSON.stringify([role])}::jsonb`,
213
- );
214
- return or(
215
- and(
216
- isNull(platformNotifications.recipientUserId),
217
- sql`jsonb_array_length(${platformNotifications.recipientRoleCodes}) = 0`,
218
- ),
219
- eq(platformNotifications.recipientUserId, actor.id),
220
- ...roleClauses,
221
- )!;
222
- }
223
-
224
- function searchWhere(query?: string): SQL | undefined {
225
- const keyword = query?.trim();
226
- return keyword
227
- ? or(
228
- ilike(platformNotifications.title, `%${keyword}%`),
229
- ilike(platformNotifications.summary, `%${keyword}%`),
230
- ilike(platformNotifications.category, `%${keyword}%`),
231
- )
232
- : undefined;
233
- }
@@ -0,0 +1,119 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { createFoundationSnapshot } from "../foundation.js";
3
+ import { createServerRuntime } from "../runtime.js";
4
+ import { InMemoryNotificationDeliveryRepository } from "./memory-delivery-repository.js";
5
+ import { InMemoryNotificationPreferenceRepository } from "./preference-repository.js";
6
+ import type { NotificationRecipientDirectory } from "./recipient-directory.js";
7
+ import { InMemoryNotificationRepository } from "./repository.js";
8
+ import { registerNotificationRoutes } from "./routes.js";
9
+ import { NotificationService } from "./service.js";
10
+
11
+ class FakeRouteApp {
12
+ readonly handlers = new Map<string, (context: unknown) => unknown>();
13
+ get(path: string, handler: (context: unknown) => unknown) {
14
+ this.handlers.set(`GET ${path}`, handler);
15
+ }
16
+ post(path: string, handler: (context: unknown) => unknown) {
17
+ this.handlers.set(`POST ${path}`, handler);
18
+ }
19
+ put(path: string, handler: (context: unknown) => unknown) {
20
+ this.handlers.set(`PUT ${path}`, handler);
21
+ }
22
+ delete(path: string, handler: (context: unknown) => unknown) {
23
+ this.handlers.set(`DELETE ${path}`, handler);
24
+ }
25
+ invoke(method: string, path: string, context: unknown) {
26
+ const handler = this.handlers.get(`${method} ${path}`);
27
+ if (!handler) throw new Error(`未注册路由 ${method} ${path}`);
28
+ return handler(context);
29
+ }
30
+ }
31
+
32
+ const directory: NotificationRecipientDirectory = {
33
+ async options() {
34
+ return {
35
+ users: [{ id: "user_dev_admin", label: "开发管理员" }],
36
+ roles: [{ id: "role_admin", label: "管理员", code: "developer" }],
37
+ departments: [{ id: "dept_platform", label: "平台部", code: "PLATFORM" }],
38
+ };
39
+ },
40
+ async resolve() {
41
+ return [{ id: "user_dev_admin", email: "admin@example.com" }];
42
+ },
43
+ async address() {
44
+ return "admin@example.com";
45
+ },
46
+ };
47
+
48
+ describe("通知扩展 API", () => {
49
+ test("偏好、受众、定时发布和 outbox 均经过通知 Guard", async () => {
50
+ const runtime = createServerRuntime({ WINDY_DEV_ADMIN_TOKEN: "token_1" });
51
+ const repository = new InMemoryNotificationRepository();
52
+ const preferences = new InMemoryNotificationPreferenceRepository();
53
+ const deliveries = new InMemoryNotificationDeliveryRepository();
54
+ const service = new NotificationService(
55
+ repository,
56
+ preferences,
57
+ deliveries,
58
+ directory,
59
+ );
60
+ const app = new FakeRouteApp();
61
+ registerNotificationRoutes(
62
+ app,
63
+ repository,
64
+ runtime,
65
+ createFoundationSnapshot().features,
66
+ service,
67
+ );
68
+ const guardContext = await runtime.createGuardContext(
69
+ new Request("http://localhost/api/notifications/preferences", {
70
+ headers: { authorization: "Bearer token_1" },
71
+ }),
72
+ );
73
+ const context = { guardContext, params: {}, query: {} };
74
+
75
+ expect(
76
+ await app.invoke(
77
+ "GET",
78
+ "/system/notifications/audience-options",
79
+ context,
80
+ ),
81
+ ).toMatchObject({
82
+ users: [{ id: "user_dev_admin" }],
83
+ departments: [{ id: "dept_platform" }],
84
+ });
85
+ expect(
86
+ await app.invoke("PUT", "/notifications/preferences", {
87
+ ...context,
88
+ body: {
89
+ enabledChannels: ["email"],
90
+ disabledCategories: ["营销"],
91
+ },
92
+ }),
93
+ ).toMatchObject({
94
+ userId: "user_dev_admin",
95
+ enabledChannels: ["email"],
96
+ disabledCategories: ["营销"],
97
+ });
98
+ const published = (await app.invoke("POST", "/system/notifications", {
99
+ ...context,
100
+ body: {
101
+ title: "定向通知",
102
+ summary: "摘要",
103
+ content: "正文",
104
+ category: "运营",
105
+ recipientUserIds: ["user_dev_admin"],
106
+ deliveryChannels: ["email"],
107
+ },
108
+ })) as { id: string };
109
+ expect(
110
+ await app.invoke("GET", "/system/notifications/:id/deliveries", {
111
+ ...context,
112
+ params: { id: published.id },
113
+ }),
114
+ ).toMatchObject([{ channel: "email", status: "pending" }]);
115
+ expect(runtime.auditSink.list().map(({ action }) => action)).toContain(
116
+ "notification.preference.update",
117
+ );
118
+ });
119
+ });
@@ -0,0 +1,111 @@
1
+ import type { FeatureFlagDefinition, HttpMethod } from "@southwind-ai/shared";
2
+ import { evaluateRouteGuards } from "../route-guards.js";
3
+ import type { createServerRuntime } from "../runtime.js";
4
+ import type { NotificationRouteApp } from "./routes.js";
5
+ import {
6
+ notificationEvent,
7
+ parsePreferenceInput,
8
+ type NotificationRouteContext,
9
+ } from "./route-support.js";
10
+ import type { NotificationService } from "./service.js";
11
+
12
+ type ServerRuntime = ReturnType<typeof createServerRuntime>;
13
+
14
+ export function registerNotificationExtensionRoutes(
15
+ app: NotificationRouteApp,
16
+ service: NotificationService,
17
+ runtime: ServerRuntime,
18
+ feature: FeatureFlagDefinition | undefined,
19
+ ) {
20
+ app.get("/notifications/preferences", (raw) =>
21
+ guarded(
22
+ raw,
23
+ "GET",
24
+ "/api/notifications/preferences",
25
+ "read",
26
+ feature,
27
+ runtime,
28
+ async (context) =>
29
+ (await service.getPreference(context.guardContext.actor.id)) || {
30
+ userId: context.guardContext.actor.id,
31
+ enabledChannels: [],
32
+ disabledCategories: [],
33
+ },
34
+ ),
35
+ );
36
+ app.put("/notifications/preferences", (raw) =>
37
+ guarded(
38
+ raw,
39
+ "PUT",
40
+ "/api/notifications/preferences",
41
+ "read",
42
+ feature,
43
+ runtime,
44
+ async (context) => {
45
+ const input = parsePreferenceInput(context.body);
46
+ if (input instanceof Response) return input;
47
+ const preference = await service.savePreference(
48
+ context.guardContext.actor.id,
49
+ input,
50
+ context.guardContext.actor.id,
51
+ );
52
+ await runtime.auditSink.recordCriticalEvent(
53
+ notificationEvent(
54
+ context,
55
+ "notification.preference.update",
56
+ context.guardContext.actor.id,
57
+ ),
58
+ );
59
+ return preference;
60
+ },
61
+ ),
62
+ );
63
+ app.get("/system/notifications/audience-options", (raw) =>
64
+ guarded(
65
+ raw,
66
+ "GET",
67
+ "/api/system/notifications/audience-options",
68
+ "manage",
69
+ feature,
70
+ runtime,
71
+ () => service.audienceOptions(),
72
+ ),
73
+ );
74
+ app.get("/system/notifications/:id/deliveries", (raw) =>
75
+ guarded(
76
+ raw,
77
+ "GET",
78
+ "/api/system/notifications/:id/deliveries",
79
+ "manage",
80
+ feature,
81
+ runtime,
82
+ (context) => service.listDeliveries(context.params.id || ""),
83
+ ),
84
+ );
85
+ }
86
+
87
+ async function guarded(
88
+ raw: unknown,
89
+ method: HttpMethod,
90
+ path: string,
91
+ action: "read" | "manage",
92
+ feature: FeatureFlagDefinition | undefined,
93
+ runtime: ServerRuntime,
94
+ handler: (context: NotificationRouteContext) => unknown,
95
+ ) {
96
+ const context = raw as NotificationRouteContext;
97
+ const decision = await evaluateRouteGuards(runtime, context.guardContext, {
98
+ permission: {
99
+ method,
100
+ path,
101
+ permissionKey: `system.notification.${action}`,
102
+ },
103
+ feature,
104
+ });
105
+ return decision.allowed
106
+ ? handler(context)
107
+ : Response.json(
108
+ { error: "FORBIDDEN", reason: decision.reason },
109
+ { status: 403 },
110
+ );
111
+ }
@@ -0,0 +1,137 @@
1
+ import type {
2
+ NotificationDelivery,
3
+ NotificationDeliveryStatus,
4
+ } from "@southwind-ai/shared";
5
+ import type {
6
+ ClaimedNotificationDelivery,
7
+ NotificationDeliveryDraft,
8
+ NotificationDeliveryRepository,
9
+ } from "./delivery-repository.js";
10
+
11
+ interface MemoryDelivery extends NotificationDeliveryDraft {
12
+ id: string;
13
+ status: NotificationDeliveryStatus;
14
+ attemptCount: number;
15
+ nextAttemptAt: string;
16
+ leaseToken?: string;
17
+ leaseExpiresAt?: string;
18
+ deliveredAt?: string;
19
+ lastErrorCode?: string;
20
+ createdAt: string;
21
+ updatedAt: string;
22
+ }
23
+
24
+ export class InMemoryNotificationDeliveryRepository implements NotificationDeliveryRepository {
25
+ private readonly items = new Map<string, MemoryDelivery>();
26
+ private readonly uniqueKeys = new Set<string>();
27
+
28
+ constructor(private readonly leaseMs = 30_000) {}
29
+
30
+ async enqueue(drafts: NotificationDeliveryDraft[]) {
31
+ let inserted = 0;
32
+ const now = new Date().toISOString();
33
+ for (const draft of drafts) {
34
+ const key = `${draft.notificationId}:${draft.userId}:${draft.channel}`;
35
+ if (this.uniqueKeys.has(key)) continue;
36
+ const id = Bun.randomUUIDv7();
37
+ this.items.set(id, {
38
+ id,
39
+ ...draft,
40
+ status: "pending",
41
+ attemptCount: 0,
42
+ nextAttemptAt: now,
43
+ createdAt: now,
44
+ updatedAt: now,
45
+ });
46
+ this.uniqueKeys.add(key);
47
+ inserted += 1;
48
+ }
49
+ return inserted;
50
+ }
51
+
52
+ async claim(now: Date, limit: number) {
53
+ const claimed: ClaimedNotificationDelivery[] = [];
54
+ for (const item of this.items.values()) {
55
+ const due =
56
+ ((item.status === "pending" || item.status === "retrying") &&
57
+ item.nextAttemptAt <= now.toISOString()) ||
58
+ (item.status === "processing" &&
59
+ Boolean(
60
+ item.leaseExpiresAt && item.leaseExpiresAt <= now.toISOString(),
61
+ ));
62
+ if (!due || claimed.length >= limit) continue;
63
+ const leaseToken = Bun.randomUUIDv7();
64
+ item.status = "processing";
65
+ item.attemptCount += 1;
66
+ item.leaseToken = leaseToken;
67
+ item.leaseExpiresAt = new Date(
68
+ now.getTime() + this.leaseMs,
69
+ ).toISOString();
70
+ item.updatedAt = now.toISOString();
71
+ claimed.push({
72
+ id: item.id,
73
+ notificationId: item.notificationId,
74
+ userId: item.userId,
75
+ channel: item.channel,
76
+ subject: item.subject,
77
+ content: item.content,
78
+ attemptCount: item.attemptCount,
79
+ leaseToken,
80
+ });
81
+ }
82
+ return claimed;
83
+ }
84
+
85
+ async complete(id: string, leaseToken: string) {
86
+ const item = this.activeLease(id, leaseToken);
87
+ if (!item) return false;
88
+ item.status = "delivered";
89
+ item.deliveredAt = new Date().toISOString();
90
+ item.updatedAt = item.deliveredAt;
91
+ item.leaseToken = undefined;
92
+ item.leaseExpiresAt = undefined;
93
+ item.lastErrorCode = undefined;
94
+ return true;
95
+ }
96
+
97
+ async fail(id: string, leaseToken: string, code: string, retryAt?: Date) {
98
+ const item = this.activeLease(id, leaseToken);
99
+ if (!item) return false;
100
+ item.status = retryAt ? "retrying" : "dead";
101
+ item.nextAttemptAt = (retryAt || new Date()).toISOString();
102
+ item.lastErrorCode = code;
103
+ item.updatedAt = new Date().toISOString();
104
+ item.leaseToken = undefined;
105
+ item.leaseExpiresAt = undefined;
106
+ return true;
107
+ }
108
+
109
+ async list(notificationId: string) {
110
+ return [...this.items.values()]
111
+ .filter((item) => item.notificationId === notificationId)
112
+ .map(toDelivery);
113
+ }
114
+
115
+ private activeLease(id: string, leaseToken: string) {
116
+ const item = this.items.get(id);
117
+ return item?.status === "processing" && item.leaseToken === leaseToken
118
+ ? item
119
+ : undefined;
120
+ }
121
+ }
122
+
123
+ function toDelivery(item: MemoryDelivery): NotificationDelivery {
124
+ return {
125
+ id: item.id,
126
+ notificationId: item.notificationId,
127
+ userId: item.userId,
128
+ channel: item.channel,
129
+ status: item.status,
130
+ attemptCount: item.attemptCount,
131
+ nextAttemptAt: item.nextAttemptAt,
132
+ deliveredAt: item.deliveredAt,
133
+ lastErrorCode: item.lastErrorCode,
134
+ createdAt: item.createdAt,
135
+ updatedAt: item.updatedAt,
136
+ };
137
+ }