diff --git a/apps/api/backend/plugin/notification/AGENTS.md b/apps/api/backend/plugin/notification/AGENTS.md index 517a6e40..afcd1e58 100644 --- a/apps/api/backend/plugin/notification/AGENTS.md +++ b/apps/api/backend/plugin/notification/AGENTS.md @@ -236,3 +236,19 @@ SQL Server 上新表不是 IDENTITY;autogenerate 和迁移后的库比对没 ⚠️ **复核自己查不出来时照快照发**(`_recheck_recipient` 记 warning,同群机器人限流「数不出来就照发」):第一版复核在 `try` 外面, 查库一抛就冲出 `deliver_pending`,这一行停在 sending、被归成「结果未知」再也不发,同批后面的也不发。 `test_recheck_failing_still_sends_to_the_snapshot`:把兜底改成只接 `ZeroDivisionError` → 红。 + +## 🔴 删除只删「点名发给我本人」的那一行:按 `recipient_id` 判,不按 `category`(#449) + +**会怎么坏**:如果按「分类是不是公告」决定能不能删,全员广播里除了公告还有每日问候、手动发送时留空接收人的消息, +它们落库也是 `recipient_id IS NULL`、**全员共用的一行**。按分类放开的话这些都能删,一删就是**所有人一起看不到**, +而接口照样返回 200。 + +**规则**:能删 = `recipient_id = 我 AND deleted = 0`(`crud_notification.get_own_ids`)。**不要复用 `visible_to`**: +它包含广播那一半。定向发送是按收件人每人一行(`notification_service.send` 里 fan-out),删自己那行不影响别人。 +删除走的是现成的逻辑删除列(`deleted` / `deleted_time`),收件箱的每条查询本来就过滤 `deleted == 0`,所以不用新建表、不用迁移; +已读标记一起删掉(同 `retract_by_source`)。单条删不掉(广播 / 别人的 / 不存在)一律 404,不区分;批量删时静默跳过。 +列表上的 `deletable` 由 service 用同一个判据回填,前端只认这个字段。 + +**实测证据**:`tests/test_notification.py` 的 `test_delete_broadcast_or_others_is_404_and_untouched`(广播和别人的 → 404、库里 `deleted` 仍是 0)、 +`test_delete_own_targeted_leaves_others_copy`(同一次发给我和 test 账号,我删了之后 test 那一行 `deleted == 0`), +`test_batch_delete_skips_what_is_not_mine`(三条里混一条广播 → 返回 2)。 diff --git a/apps/api/backend/plugin/notification/api/v1/sys/notification.py b/apps/api/backend/plugin/notification/api/v1/sys/notification.py index 787def7a..b3d08986 100644 --- a/apps/api/backend/plugin/notification/api/v1/sys/notification.py +++ b/apps/api/backend/plugin/notification/api/v1/sys/notification.py @@ -10,6 +10,7 @@ from backend.database.db import CurrentSession, CurrentSessionTransaction from backend.plugin.notification.audience import viewer_of from backend.plugin.notification.schema.notification import ( + DeleteNotificationParam, GetNotificationDetail, GetNotificationUnreadDetail, SendNotificationParam, @@ -43,9 +44,12 @@ async def get_my_notifications_paginated( title: Annotated[str | None, Query(description='标题')] = None, category: Annotated[int | None, Query(description='分类(0:系统、1:公告、2:任务事件、3:审批)')] = None, unread: Annotated[bool | None, Query(description='只看未读 / 只看已读,不传则不筛')] = None, + # 消息中心拿 `mine=true&unread=false` 的 total 当「清空已读」能删几条(#451)。 + # 🔴 不放进 `/unread-count`:铃铛每次收件箱变动都重拉它,那里只许一条统计查询(`test_unread_count_is_one_scan`) + mine: Annotated[bool | None, Query(description='只看点名发给我本人的(能删除的),不传则不筛')] = None, ) -> ResponseSchemaModel[PageData[GetNotificationDetail]]: page_data = await notification_service.get_list( - db=db, viewer=await viewer_of(db, request.user), title=title, category=category, unread=unread + db=db, viewer=await viewer_of(db, request.user), title=title, category=category, unread=unread, mine=bool(mine) ) return response_base.success(data=page_data) @@ -78,6 +82,35 @@ async def mark_read( return response_base.success() +# 🔴 删除只删「点名发给我本人」的通知(#449)。公告和全员广播是全员共用的一行,不在可删范围内。 +# 三条的声明顺序同 `read-all`:`/read` 必须排在 `/{pk}` 前面 + + +@router.delete('/read', summary='清空我的已读通知', dependencies=[DependsJwtAuth]) +async def delete_my_read_notifications(request: Request, db: CurrentSessionTransaction) -> ResponseSchemaModel[int]: + count = await notification_service.delete_read(db=db, viewer=await viewer_of(db, request.user)) + return response_base.success(data=count) + + +@router.delete('', summary='批量删除我的通知', dependencies=[DependsJwtAuth]) +async def delete_my_notifications( + request: Request, db: CurrentSessionTransaction, obj: DeleteNotificationParam +) -> ResponseSchemaModel[int]: + # 返回实际删掉的条数:不是发给我本人的会被跳过,前端拿它提示「删除了 n 条」 + count = await notification_service.delete_many(db=db, viewer=await viewer_of(db, request.user), pks=obj.pks) + return response_base.success(data=count) + + +@router.delete('/{pk}', summary='删除我的通知', dependencies=[DependsJwtAuth]) +async def delete_my_notification( + request: Request, + db: CurrentSessionTransaction, + pk: Annotated[int, Path(description='通知 ID')], +) -> ResponseModel: + await notification_service.delete(db=db, viewer=await viewer_of(db, request.user), pk=pk) + return response_base.success() + + @router.post( '/send', summary='发送站内通知', diff --git a/apps/api/backend/plugin/notification/crud/crud_notification.py b/apps/api/backend/plugin/notification/crud/crud_notification.py index e4e85d5c..b29d4b6c 100644 --- a/apps/api/backend/plugin/notification/crud/crud_notification.py +++ b/apps/api/backend/plugin/notification/crud/crud_notification.py @@ -115,7 +115,7 @@ async def get_visible(self, db: AsyncSession, viewer: Viewer, pk: int) -> Notifi ) async def get_select( - self, viewer: Viewer, title: str | None, category: int | None, *, unread: bool | None + self, viewer: Viewer, title: str | None, category: int | None, *, unread: bool | None, mine: bool = False ) -> Select: """ 获取「我的通知」列表查询表达式 @@ -124,9 +124,12 @@ async def get_select( :param title: 标题(模糊匹配) :param category: 分类 :param unread: True 只看未读、False 只看已读、None 不筛 + :param mine: 只看点名发给我本人的(= 能删的,同 `get_own_ids`) :return: """ filters: list[ColumnElement[bool]] = [visible_to(viewer)] + if mine: + filters.append(Notification.recipient_id == viewer.id) if unread is True: filters.append(_unread(viewer)) elif unread is False: @@ -261,6 +264,55 @@ async def get_unread_ids(self, db: AsyncSession, viewer: Viewer) -> list[int]: stmt = select(Notification.id).where(*filters) return [row[0] for row in (await db.execute(stmt)).all()] + async def get_own_ids( + self, db: AsyncSession, viewer: Viewer, pks: Sequence[int] | None = None, *, read_only: bool = False + ) -> list[int]: + """ + 这个人**能删**的通知 ID:只有点名发给他本人的那几行(#449) + + 🔴 不能复用 `visible_to`:它包含广播(`recipient_id IS NULL`)—— 公告、每日问候、手动全员发都是 + **全员共用的一行**,删掉就是所有人一起看不到。定向发送按收件人每人一行(`notification_service.send` + 里 fan-out),删自己那一行不影响任何人 + + :param db: 数据库会话 + :param viewer: 看的人 + :param pks: 只在这批里挑;`None` 表示不限 + :param read_only: 只要已读的(「清空已读」) + :return: + """ + if pks is not None and not pks: + return [] + filters: list[ColumnElement[bool]] = [Notification.recipient_id == viewer.id, Notification.deleted == 0] + if pks is not None: + filters.append(Notification.id.in_(list(dict.fromkeys(pks)))) + if read_only: + filters.append(~_unread(viewer)) + stmt = select(Notification.id).where(*filters) + return list((await db.scalars(stmt)).all()) + + async def delete_own(self, db: AsyncSession, pks: Sequence[int]) -> int: + """ + 逻辑删除这批通知 + 清掉它们的已读标记。**调用方负责先用 `get_own_ids` 过滤** + + :param db: 数据库会话 + :param pks: 通知 ID 列表 + :return: 删除的行数 + """ + if not pks: + return 0 + await self.delete_reads(db, pks) + return await self.delete_model_by_column( + db, + allow_multiple=True, + logical_deletion=True, + deleted_flag_column='deleted', + deleted_flag_value=self.model.id, + deleted_at_column='deleted_time', + deleted_at_factory=timezone.now(), + id__in=list(pks), + deleted=0, + ) + async def get_ids_by_sources(self, db: AsyncSession, sources: Sequence[str]) -> dict[str, int]: """ 来源 → 收件箱里那一行的 ID(只认广播行;同一来源有多行时取最新的) diff --git a/apps/api/backend/plugin/notification/schema/notification.py b/apps/api/backend/plugin/notification/schema/notification.py index bec9fd37..15569d32 100644 --- a/apps/api/backend/plugin/notification/schema/notification.py +++ b/apps/api/backend/plugin/notification/schema/notification.py @@ -52,6 +52,16 @@ class GetNotificationDetail(NotificationSchemaBase): requires_ack: bool = Field( False, description='必须读者打开确认(如必须确认的公告):不能在列表里标已读,「全部已读」也会跳过它' ) + # 同上,service 回填。前端只认它决定摆不摆删除按钮,不要拿 `category` 去猜(#449) + deletable: bool = Field( + False, description='能否删除:只有点名发给我本人的才能删;公告和全员广播是全员共用的一行,不能删' + ) + + +class DeleteNotificationParam(SchemaBase): + """批量删除我的通知参数""" + + pks: list[int] = Field(description='通知 ID 列表(不是发给我本人的会被跳过)', max_length=500) class GetNotificationUnreadDetail(SchemaBase): diff --git a/apps/api/backend/plugin/notification/service/notification_service.py b/apps/api/backend/plugin/notification/service/notification_service.py index b2d19c71..92791f3c 100644 --- a/apps/api/backend/plugin/notification/service/notification_service.py +++ b/apps/api/backend/plugin/notification/service/notification_service.py @@ -153,7 +153,13 @@ class NotificationService: @staticmethod async def get_list( - *, db: AsyncSession, viewer: Viewer, title: str | None, category: int | None, unread: bool | None + *, + db: AsyncSession, + viewer: Viewer, + title: str | None, + category: int | None, + unread: bool | None, + mine: bool = False, ) -> dict[str, Any]: """ 获取「我的通知」分页列表 @@ -163,9 +169,10 @@ async def get_list( :param title: 标题(模糊匹配) :param category: 分类 :param unread: True 只看未读、False 只看已读、None 不筛 + :param mine: 只看点名发给我本人的(能删的) :return: """ - select = await notification_dao.get_select(viewer, title, category, unread=unread) + select = await notification_dao.get_select(viewer, title, category, unread=unread, mine=mine) page_data = await paging_data(db, select) # 已读状态**不是** `sys_notification` 上的列(广播不 fan-out,见模型注释), @@ -192,6 +199,8 @@ async def get_list( requires_ack=item['requires_ack'], ) item['attachment_count'] = attachments.get(item.get('source') or '') + # 与 `notification_dao.get_own_ids` 同一个判据:点名给我本人的才能删(#449) + item['deletable'] = item['recipient_id'] == viewer.id return page_data @staticmethod @@ -243,6 +252,57 @@ async def mark_all_read(*, db: AsyncSession, viewer: Viewer) -> int: pks = await notification_dao.get_unread_ids(db, viewer) return await notification_dao.mark_read(db, viewer.id, pks) + @staticmethod + async def delete(*, db: AsyncSession, viewer: Viewer, pk: int) -> int: + """ + 删除一条我的通知(#449)。只有点名发给我本人的能删 + + 🔴 广播、发给别人的、不存在的、已删的**一律 404**,不区分:区分开就是用一个写接口告诉调用方 + 「这条 ID 存在,只是不归你」(同 `mark_read`) + + :param db: 数据库会话 + :param viewer: 看的人 + :param pk: 通知 ID + :return: + """ + pks = await notification_dao.get_own_ids(db, viewer, [pk]) + if not pks: + raise errors.NotFoundError(msg=t('error.notification.not_found')) + return await NotificationService._delete(db, viewer, pks) + + @staticmethod + async def delete_many(*, db: AsyncSession, viewer: Viewer, pks: Sequence[int]) -> int: + """ + 批量删除我的通知。不是发给我本人的静默跳过(批量勾选里混进一条广播,不该整批失败) + + :param db: 数据库会话 + :param viewer: 看的人 + :param pks: 通知 ID 列表 + :return: 实际删除的条数 + """ + own = await notification_dao.get_own_ids(db, viewer, pks) + return await NotificationService._delete(db, viewer, own) + + @staticmethod + async def delete_read(*, db: AsyncSession, viewer: Viewer) -> int: + """ + 清空已读:删掉发给我本人、且已读的全部通知。公告和全员广播不动 + + :param db: 数据库会话 + :param viewer: 看的人 + :return: 实际删除的条数 + """ + own = await notification_dao.get_own_ids(db, viewer, read_only=True) + return await NotificationService._delete(db, viewer, own) + + @staticmethod + async def _delete(db: AsyncSession, viewer: Viewer, pks: Sequence[int]) -> int: + count = await notification_dao.delete_own(db, pks) + if count: + # 同一个人开着的其他标签页 / 设备:红点和列表跟着变。挂在提交之后,不然那边重拉到的还是旧数 + run_after_commit(db, f'notification.push_user:{viewer.id}', lambda: _push(viewer.id)) + return count + @staticmethod async def send(*, db: AsyncSession, obj: SendNotificationParam) -> int: """ diff --git a/apps/api/backend/plugin/notification/tests/test_notification.py b/apps/api/backend/plugin/notification/tests/test_notification.py index 16dcb29f..9e572f93 100644 --- a/apps/api/backend/plugin/notification/tests/test_notification.py +++ b/apps/api/backend/plugin/notification/tests/test_notification.py @@ -291,3 +291,133 @@ def test_hidden_notice_does_not_notify(client: TestClient, token_headers: dict[s assert _find(_list(client, token_headers, category=1), title) is None finally: client.request('DELETE', NOTICES, headers=token_headers, json={'pks': [notice_id]}) + + +# ─── 删除(#449):只删点名发给我本人的 ───────────────────────────────────────── + + +def _rows_by_title(title: str) -> list[tuple[int, int | None, int]]: + """(id, recipient_id, deleted):直接看库,接口只能看见自己那一份""" + + async def _rows(db: AsyncSession) -> list[tuple[int, int | None, int]]: + stmt = select(Notification.id, Notification.recipient_id, Notification.deleted).where( + Notification.title == title + ) + return [(r[0], r[1], r[2]) for r in (await db.execute(stmt)).all()] + + return _run_on_test_db(_rows) + + +def _my_id(client: TestClient, headers: dict[str, str]) -> str: + """当前登录用户的 ID(字符串,硬纪律 6)""" + res = client.get('/sys/users/me', headers=headers) + assert res.status_code == 200, res.text + return str(res.json()['data']['id']) + + +def test_list_marks_only_targeted_as_deletable( + client: TestClient, token_headers: dict[str, str], cleanup: list[str] +) -> None: + """列表的 `deletable`:点名给我的 true,广播 false —— 前端只认它摆不摆删除按钮""" + me = _my_id(client, token_headers) + _send(client, token_headers, cleanup, title='pytest 可删 定向', recipient_ids=[me]) + _send(client, token_headers, cleanup, title='pytest 可删 广播') + items = _list(client, token_headers) + targeted = _find(items, 'pytest 可删 定向') + broadcast = _find(items, 'pytest 可删 广播') + assert targeted is not None + assert broadcast is not None + assert targeted['deletable'] is True + assert broadcast['deletable'] is False + + +def test_delete_own_targeted_leaves_others_copy( + client: TestClient, token_headers: dict[str, str], cleanup: list[str] +) -> None: + """🔴 同一次发给我和别人:定向发送是每人一行,我删我那行,别人那行原样在""" + me = _my_id(client, token_headers) + other_id = '2049946297615646720' + title = 'pytest 删除 不影响别人' + _send(client, token_headers, cleanup, title=title, recipient_ids=[me, other_id]) + item = _find(_list(client, token_headers), title) + assert item is not None + + before = _unread_total(client, token_headers) + res = client.delete(f'{NOTIFICATIONS}/{item["id"]}', headers=token_headers) + assert res.status_code == 200, res.text + + assert _find(_list(client, token_headers), title) is None + # 删的是一条未读:红点跟着减 + assert _unread_total(client, token_headers) == before - 1 + rows = {str(rid): deleted for _, rid, deleted in _rows_by_title(title)} + assert rows[me] != 0 + assert rows[other_id] == 0 + + +def test_delete_broadcast_or_others_is_404_and_untouched( + client: TestClient, token_headers: dict[str, str], cleanup: list[str] +) -> None: + """🔴 广播(公告 / 全员发)和发给别人的:一律 404,库里不动 + + 广播是全员共用的一行,删掉就是所有人一起看不到;发给别人的 404 而不是 403,不泄漏「这条存在」 + """ + _send(client, token_headers, cleanup, title='pytest 删除 广播') + _send(client, token_headers, cleanup, title='pytest 删除 别人的', recipient_ids=['2049946297615646720']) + for title in ('pytest 删除 广播', 'pytest 删除 别人的'): + [(pk, _, _)] = _rows_by_title(title) + res = client.delete(f'{NOTIFICATIONS}/{pk}', headers=token_headers) + assert res.status_code == 404, res.text + assert _rows_by_title(title)[0][2] == 0 + + +def test_batch_delete_skips_what_is_not_mine( + client: TestClient, token_headers: dict[str, str], cleanup: list[str] +) -> None: + """批量里混进广播:只删我本人的那几条,返回实际删除数,广播不动、整批不失败""" + me = _my_id(client, token_headers) + _send(client, token_headers, cleanup, title='pytest 批量 A', recipient_ids=[me]) + _send(client, token_headers, cleanup, title='pytest 批量 B', recipient_ids=[me]) + _send(client, token_headers, cleanup, title='pytest 批量 广播') + pks = [str(_rows_by_title(t)[0][0]) for t in ('pytest 批量 A', 'pytest 批量 B', 'pytest 批量 广播')] + + res = client.request('DELETE', NOTIFICATIONS, headers=token_headers, json={'pks': pks}) + assert res.status_code == 200, res.text + assert res.json()['data'] == 2 + items = _list(client, token_headers) + assert _find(items, 'pytest 批量 A') is None + assert _find(items, 'pytest 批量 B') is None + assert _find(items, 'pytest 批量 广播') is not None + + +def test_delete_read_only_clears_my_read_targeted( + client: TestClient, token_headers: dict[str, str], cleanup: list[str] +) -> None: + """清空已读:只删「点名给我 + 已读」的;未读的、已读的广播都留着""" + me = _my_id(client, token_headers) + _send(client, token_headers, cleanup, title='pytest 清空 已读', recipient_ids=[me]) + _send(client, token_headers, cleanup, title='pytest 清空 未读', recipient_ids=[me]) + _send(client, token_headers, cleanup, title='pytest 清空 已读广播') + items = _list(client, token_headers) + for title in ('pytest 清空 已读', 'pytest 清空 已读广播'): + item = _find(items, title) + assert item is not None + assert client.put(f'{NOTIFICATIONS}/{item["id"]}/read', headers=token_headers).status_code == 200 + + def _clearable() -> int: + """消息中心「清空已读」按钮读的那个数:`mine=true&unread=false` 的 total""" + res = client.get(NOTIFICATIONS, headers=token_headers, params={'mine': True, 'unread': False, 'size': 1}) + assert res.status_code == 200, res.text + return res.json()['data']['total'] + + counted = _clearable() + assert counted >= 1 + + res = client.delete(f'{NOTIFICATIONS}/read', headers=token_headers) + assert res.status_code == 200, res.text + # 「能清几条」的列表 total = 实际删掉的条数(前端拿它灰掉按钮、写进确认框) + assert res.json()['data'] == counted + assert _clearable() == 0 + items = _list(client, token_headers) + assert _find(items, 'pytest 清空 已读') is None + assert _find(items, 'pytest 清空 未读') is not None + assert _find(items, 'pytest 清空 已读广播') is not None diff --git a/apps/mobile/src/app/(app)/notifications.tsx b/apps/mobile/src/app/(app)/notifications.tsx index 4249ee0d..6b63deef 100644 --- a/apps/mobile/src/app/(app)/notifications.tsx +++ b/apps/mobile/src/app/(app)/notifications.tsx @@ -7,12 +7,14 @@ import { Pressable, RefreshControl, ScrollView, View } from 'react-native' import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert' import { Button } from '@/components/ui/button' +import { ConfirmDialog } from '@/components/ui/confirm-dialog' import { Chevron, Group, HeaderAction } from '@/components/grouped' import { AttachmentCount } from '@/components/notice' import { Icon } from '@/components/ui/icon' import { Skeleton } from '@/components/ui/skeleton' import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs' import { Text } from '@/components/ui/text' +import { toast } from '@/components/ui/toast' import { api } from '@/lib/api' import { NOTIFICATION_CATEGORY, type Notification } from '@/lib/contract' import { relativeTime } from '@/lib/datetime' @@ -33,6 +35,8 @@ export default function NotificationsScreen() { const router = useRouter() const { refresh: refreshUnread, unread, known: unreadKnown } = useUnread() const [filter, setFilter] = React.useState('all') + /** 长按要删的那一条(#449)。只有发给我本人的(`deletable`)长按才有反应 */ + const [deleting, setDeleting] = React.useState(null) /** * 🔴 **筛选条件进 query key,竞态就从结构上消失了。** @@ -122,6 +126,23 @@ export default function NotificationsScreen() { }, }) + /* + * 删除(#449):只有发给我本人的能删,公告和全员广播是全员共用的一行、后端不让删。 + * 🔴 写失败走 `toast.error`(components 分册那张表):确认框关掉之后屏上没有位置可占,那条还在列表里就是对的 + */ + const del = useMutation({ + mutationFn: (n: Notification) => + api.DELETE('/api/v1/sys/notifications/{pk}', { params: { path: { pk: n.id } } }), + onError: (e) => toast.error(t('删除失败'), { description: e instanceof Error ? e.message : String(e) }), + onSettled: async () => { + setDeleting(null) + await Promise.all([ + qc.invalidateQueries({ queryKey: ['notifications'] }), + qc.invalidateQueries({ queryKey: noticesKey.feeds }), + ]) + }, + }) + const total = unread?.total ?? 0 /* * 「全部已读」标得掉的条数:必须确认的公告(#190)后端会跳过,只能在详情屏点「我已阅读」。 @@ -200,16 +221,51 @@ export default function NotificationsScreen() { ) : ( {items.map((n, i) => ( - onPressRow(n)} /> + onPressRow(n)} + onLongPress={n.deletable ? () => setDeleting(n) : undefined} + /> ))} )} + {/* 长按没有视觉入口,不说就只有作者知道。只在这一屏真有能删的行时说 */} + {items?.some((n) => n.deletable) ? ( + {t('长按发给你个人的通知可以删除')} + ) : null} + + { + if (!o) setDeleting(null) + }} + title={t('删除通知')} + description={deleting ? t('确定删除「{{title}}」吗?此操作不可撤销。', { title: deleting.title }) : undefined} + confirmLabel={t('删除')} + cancelLabel={t('取消')} + busy={del.isPending} + onConfirm={() => deleting && del.mutate(deleting)} + testID="notification-delete-confirm" + /> ) } -function NotifRow({ n, first, onPress }: { n: Notification; first?: boolean; onPress: () => void }) { +function NotifRow({ + n, + first, + onPress, + onLongPress, +}: { + n: Notification + first?: boolean + onPress: () => void + /** 只有能删的行才传(#449);不传 = 长按没反应,公告不会弹一个注定失败的确认框 */ + onLongPress?: () => void +}) { const { t } = useTranslation() const unread = !n.read_time // 公告来的那一行能点进详情 —— 给一枚 chevron,否则它和「只标已读」的行长得一样,没人知道能点进去 @@ -219,6 +275,7 @@ function NotifRow({ n, first, onPress }: { n: Notification; first?: boolean; onP {first ? null : } diff --git a/apps/web/e2e/tests/notification.spec.ts b/apps/web/e2e/tests/notification.spec.ts index 95148495..90577572 100644 --- a/apps/web/e2e/tests/notification.spec.ts +++ b/apps/web/e2e/tests/notification.spec.ts @@ -109,4 +109,85 @@ test.describe("消息通知中心", () => { // 少了失效就会出现「列表全是已读、红点还挂着 2」这种自相矛盾的界面 await expect(page.getByTestId("notification-badge")).toBeHidden() }) + + // ─── 删除(#449):只删点名发给我本人的 ──────────────────────────────────────── + + /** 按标题从接口拿这一行的 ID(列表页的 testid 都带 ID) */ + async function idOf(api: { get: (p: string) => Promise }, title: string): Promise { + const page = (await api.get( + `/api/v1/sys/notifications?page=1&size=5&title=${encodeURIComponent(title)}` + )) as { items: { id: string }[] } + expect(page.items).toHaveLength(1) + return page.items[0]!.id + } + + test("🔴 消息中心删除一条:列表和红点一起变;公告(全员共用的一行)没有删除按钮、也勾不上", async ({ + authedPage: page, + api, + }) => { + const me = (await api.get("/api/v1/sys/users/me")) as Me + const tag = uniqueCode("D") + const mine = `E2E删除-${tag}-我的` + const everyone = `E2E删除-${tag}-公告` + await api.post("/api/v1/sys/notifications/send", { + title: mine, content: "端到端测试用", category: 0, link: null, recipient_ids: [me.id], + }) + // 公告:收件箱里是全员共用的一行,删了就是所有人一起看不到 —— 后端不让删,前端也不该给入口。 + // 🔴 用公告不用「手动全员发」:全员发的那一行谁都删不掉,每跑一次就在 fba_test 里永久多一条(#451 评审); + // 公告删掉时会把收件箱那一行一起撤回(`retract_by_source`),结尾删公告就收干净了 + const notice = (await api.post("/api/v1/sys/notices", { + title: everyone, type: 1, status: 1, content: "

端到端测试用

", + })) as { id: string } + try { + await deleteFlow() + } finally { + await api.del("/api/v1/sys/notices", { pks: [notice.id] }) + } + + async function deleteFlow() { + const mineId = await idOf(api, mine) + const everyoneId = await idOf(api, everyone) + + await page.goto(`/notification?title=${encodeURIComponent(`E2E删除-${tag}`)}`) + await expect(page.getByTestId("notification-badge")).toHaveText("2") + await expect(page.getByTestId(`open-notification-${everyoneId}`)).toBeVisible() + + // 不能删的行:没有删除按钮、复选框禁用(「全选本页」也不会把它勾进去,见 `enableRowSelection`) + await expect(page.getByTestId(`notification-delete-${everyoneId}`)).toHaveCount(0) + await expect(page.getByTestId(`select-row-${everyoneId}`)).toBeDisabled() + // 「全选本页」也不能把它勾进去:只禁单元格的复选框不够,表上要 `enableRowSelection` + await page.getByTestId("select-all").click() + await expect(page.getByTestId("bulk-count")).toHaveText(/\b1\b/) + await page.getByTestId("select-all").click() + + await page.getByTestId(`notification-delete-${mineId}`).click() + await expect(page.getByTestId("confirm-dialog")).toBeVisible() + await page.getByTestId("confirm-ok").click() + + await expect(page.getByTestId(`open-notification-${mineId}`)).toBeHidden() + await expect(page.getByTestId(`open-notification-${everyoneId}`)).toBeVisible() + // 删的是一条未读:外壳里的红点跟着少 1(同一个 query,少了失效就是「列表没了、红点还在」) + await expect(page.getByTestId("notification-badge")).toHaveText("1") + } + }) + + test("铃铛里悬停删除发给我的那条,红点跟着消失", async ({ authedPage: page, api }) => { + const me = (await api.get("/api/v1/sys/users/me")) as Me + const title = `E2E铃铛删除-${uniqueCode("D")}` + await api.post("/api/v1/sys/notifications/send", { + title, content: "端到端测试用", category: 0, link: null, recipient_ids: [me.id], + }) + + await page.goto("/dashboard") + await expect(page.getByTestId("notification-badge")).toHaveText("1") + await page.getByTestId("notification-bell").click() + const item = page.locator("li").filter({ has: page.getByTestId("notification-item").filter({ hasText: title }) }) + // 🔴 没悬停时按钮透明,而且必须点不到:只有 `opacity-0` 的话,触屏上点那一行右上角就直接删了(#451 评审) + await expect(item.getByTestId("notification-item-delete")).toHaveCSS("pointer-events", "none") + await item.hover() + await item.getByTestId("notification-item-delete").click() + + await expect(page.getByTestId("notification-item").filter({ hasText: title })).toBeHidden() + await expect(page.getByTestId("notification-badge")).toBeHidden() + }) }) diff --git a/packages/api/src/schema.d.ts b/packages/api/src/schema.d.ts index 0ddf29b1..9bbe224a 100644 --- a/packages/api/src/schema.d.ts +++ b/packages/api/src/schema.d.ts @@ -1993,7 +1993,8 @@ export interface paths { get: operations["get_my_notifications_paginated_api_v1_sys_notifications_get"]; put?: never; post?: never; - delete?: never; + /** 批量删除我的通知 */ + delete: operations["delete_my_notifications_api_v1_sys_notifications_delete"]; options?: never; head?: never; patch?: never; @@ -2050,6 +2051,40 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/sys/notifications/read": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** 清空我的已读通知 */ + delete: operations["delete_my_read_notifications_api_v1_sys_notifications_read_delete"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/sys/notifications/{pk}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** 删除我的通知 */ + delete: operations["delete_my_notification_api_v1_sys_notifications__pk__delete"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/sys/notifications/send": { parameters: { query?: never; @@ -5793,6 +5828,17 @@ export interface components { */ pks: number[]; }; + /** + * DeleteNotificationParam + * @description 批量删除我的通知参数 + */ + DeleteNotificationParam: { + /** + * Pks + * @description 通知 ID 列表(不是发给我本人的会被跳过) + */ + pks: number[]; + }; /** * DeleteOperaLogParam * @description 删除操作日志参数 @@ -8054,6 +8100,12 @@ export interface components { * @default false */ requires_ack: boolean; + /** + * Deletable + * @description 能否删除:只有点名发给我本人的才能删;公告和全员广播是全员共用的一行,不能删 + * @default false + */ + deletable: boolean; }; /** * GetNotificationUnreadDetail @@ -13021,6 +13073,23 @@ export interface components { [key: string]: unknown; }; }; + /** ResponseSchemaModel[int] */ + ResponseSchemaModel_int_: { + /** + * Code + * @description 返回状态码 + * @default 200 + */ + code: number; + /** + * Msg + * @description 返回信息 + * @default 请求成功 + */ + msg: string; + /** Data */ + data: number; + }; /** ResponseSchemaModel[list[GetBotDetail]] */ ResponseSchemaModel_list_GetBotDetail__: { /** @@ -20046,6 +20115,8 @@ export interface operations { category?: number | null; /** @description 只看未读 / 只看已读,不传则不筛 */ unread?: boolean | null; + /** @description 只看点名发给我本人的(能删除的),不传则不筛 */ + mine?: boolean | null; /** @description 页码 */ page?: number; /** @description 每页数量 */ @@ -20077,6 +20148,39 @@ export interface operations { }; }; }; + delete_my_notifications_api_v1_sys_notifications_delete: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["DeleteNotificationParam"]; + }; + }; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_int_"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; get_my_unread_count_api_v1_sys_notifications_unread_count_get: { parameters: { query?: never; @@ -20149,6 +20253,58 @@ export interface operations { }; }; }; + delete_my_read_notifications_api_v1_sys_notifications_read_delete: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseSchemaModel_int_"]; + }; + }; + }; + }; + delete_my_notification_api_v1_sys_notifications__pk__delete: { + parameters: { + query?: never; + header?: never; + path: { + /** @description 通知 ID */ + pk: number; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ResponseModel"]; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; send_notification_api_v1_sys_notifications_send_post: { parameters: { query?: never; diff --git a/packages/i18n/src/locales/en-US.json b/packages/i18n/src/locales/en-US.json index 27019992..eb916f3f 100644 --- a/packages/i18n/src/locales/en-US.json +++ b/packages/i18n/src/locales/en-US.json @@ -419,6 +419,8 @@ "任务调度": "Task schedulers", "企业微信": "WeCom", "优先级 {{n}}": "Priority {{n}}", + "会删除发给你个人的 {{n}} 条已读通知,公告和全员通知不受影响。此操作不可撤销。": "Deletes the {{n}} read notifications sent to you personally. Announcements and all-staff messages are kept. This can't be undone.", + "会删除发给你个人的全部已读通知,公告和全员通知不受影响。此操作不可撤销。": "Deletes every read notification sent to you personally. Announcements and all-staff messages are kept. This can't be undone.", "会把 {{n}} 条未读通知标记为已读,此操作不可撤销。另有 {{m}} 条必须确认的公告不会被标记,要打开读完后点「我已阅读」。": "This marks {{n}} unread notifications as read. It can't be undone. {{m}} announcements that require acknowledgement stay unread — open each one and click \"I've read this\".", "会把你当前全部 {{n}} 条未读通知标记为已读,此操作不可撤销。": "This marks all {{n}} of your unread notifications as read. It can't be undone.", "会替换现在的表单和流程(基础信息和 AI 预审设置不动)。不满意可以不保存,返回列表时放弃修改。": "This replaces the current form and flow (basic info and AI pre-review settings stay). If you don't like it, don't save, and discard the changes when going back to the list.", @@ -723,6 +725,7 @@ "删除这个字段?": "Delete this field?", "删除这个条件": "Delete this condition", "删除选项": "Delete option", + "删除通知": "Delete notification", "删除通知公告": "Delete notice", "删除部门": "Delete department", "判断不了": "Unknown", @@ -1241,6 +1244,7 @@ "已关闭": "Off", "已写入": "Saved", "已删除": "Deleted", + "已删除 {{n}} 条通知": "Deleted {{n}} notifications", "已删除「{{name}}」": "Deleted “{{name}}”", "已办": "Done", "已加签": "Approver added", @@ -1510,6 +1514,7 @@ "批量删除登录日志": "Bulk delete sign-in logs", "批量删除短信发送日志": "Delete SMS logs", "批量删除角色": "Bulk delete roles", + "批量删除通知": "Delete notifications", "批量删除通知公告": "Bulk delete notices", "批量导入": "Bulk import", "批量更新参数配置": "Bulk update parameters", @@ -2136,6 +2141,7 @@ "没有匹配的部门": "No matching departments", "没有匹配项": "No matches", "没有发现问题": "No problems found", + "没有可清空的已读通知": "No read notifications to clear", "没有可用来验证身份的第三方账号,请联系管理员为你重置密码。": "No linked third-party account is available to verify you. Ask an administrator to reset your password.", "没有可读取的分区": "No readable partitions", "没有地址(邮箱 / 手机号)": "No address (email / phone)", @@ -2221,6 +2227,7 @@ "清空回收站": "Empty recycle bin", "清空失败": "Could not clear", "清空已保存的密钥": "Clear the saved secret", + "清空已读": "Clear read", "清空操作日志": "Clear operation logs", "清空登录日志": "Clear sign-in logs", "清空短信发送日志": "Clear SMS logs", @@ -2376,6 +2383,7 @@ "确定删除选中的 {{n}} 个文件(共 {{size}})吗?磁盘文件与业务关联会一并删除,此操作不可撤销。": "Delete the {{n}} selected files ({{size}} total)? The stored files and their attachment links are removed too. This cannot be undone.", "确定删除选中的 {{n}} 个用户吗?此操作不可撤销。": "Delete the {{n}} selected users? This cannot be undone.", "确定删除选中的 {{n}} 条通知公告吗?此操作不可撤销。": "Delete the {{n}} selected notices? This cannot be undone.", + "确定删除选中的 {{n}} 条通知吗?此操作不可撤销。": "Delete the {{n}} selected notifications? This can't be undone.", "确定卸载「{{summary}}({{name}})」吗?": "Uninstall “{{summary}} ({{name}})”?", "确定把「{{who}}」设为超级管理员吗?": "Make “{{who}}” a superuser?", "确定重置": "Reset", @@ -2477,7 +2485,7 @@ "系统上传文件的统一入口,支持预览、下载与批量清理。": "One place for every uploaded file — preview, download and bulk cleanup.", "系统发信用的 SMTP 服务器。密码以密文展示。": "The SMTP server the system sends from. The password is masked.", "系统架构": "Architecture", - "系统消息与公告的收件箱。已读状态只属于你自己。": "Your inbox for system messages and announcements. Read state is yours alone.", + "系统消息与公告的收件箱。已读和删除只影响你自己;公告和全员通知不能删除。": "Your inbox for system messages and announcements. Read status and deletions only affect you; announcements and all-staff messages can't be deleted.", "系统现在正常吗?": "Is the system healthy right now?", "系统管理": "System", "系统级动态参数。登录与口令策略是活的 —— 改完立刻对所有人生效。": "System-wide dynamic parameters. Sign-in and password policies are live — changes apply to everyone immediately.", @@ -3155,6 +3163,7 @@ "键名请用大写字母、数字和下划线,且以字母开头": "Use uppercase letters, digits and underscores, starting with a letter", "键总数": "Keys", "长任务": "Long-task worker", + "长按发给你个人的通知可以删除": "Long-press a notification sent to you to delete it", "长时间未操作,已自动退出,请重新登录": "You were signed out after a period of inactivity. Please sign in again.", "问点什么…": "Ask something…", "问点关于这套系统的事": "Ask anything about this system", diff --git a/packages/i18n/src/locales/zh-CN.json b/packages/i18n/src/locales/zh-CN.json index 792426ae..5e80372f 100644 --- a/packages/i18n/src/locales/zh-CN.json +++ b/packages/i18n/src/locales/zh-CN.json @@ -419,6 +419,8 @@ "任务调度": "任务调度", "企业微信": "企业微信", "优先级 {{n}}": "优先级 {{n}}", + "会删除发给你个人的 {{n}} 条已读通知,公告和全员通知不受影响。此操作不可撤销。": "会删除发给你个人的 {{n}} 条已读通知,公告和全员通知不受影响。此操作不可撤销。", + "会删除发给你个人的全部已读通知,公告和全员通知不受影响。此操作不可撤销。": "会删除发给你个人的全部已读通知,公告和全员通知不受影响。此操作不可撤销。", "会把 {{n}} 条未读通知标记为已读,此操作不可撤销。另有 {{m}} 条必须确认的公告不会被标记,要打开读完后点「我已阅读」。": "会把 {{n}} 条未读通知标记为已读,此操作不可撤销。另有 {{m}} 条必须确认的公告不会被标记,要打开读完后点「我已阅读」。", "会把你当前全部 {{n}} 条未读通知标记为已读,此操作不可撤销。": "会把你当前全部 {{n}} 条未读通知标记为已读,此操作不可撤销。", "会替换现在的表单和流程(基础信息和 AI 预审设置不动)。不满意可以不保存,返回列表时放弃修改。": "会替换现在的表单和流程(基础信息和 AI 预审设置不动)。不满意可以不保存,返回列表时放弃修改。", @@ -723,6 +725,7 @@ "删除这个字段?": "删除这个字段?", "删除这个条件": "删除这个条件", "删除选项": "删除选项", + "删除通知": "删除通知", "删除通知公告": "删除通知公告", "删除部门": "删除部门", "判断不了": "判断不了", @@ -1241,6 +1244,7 @@ "已关闭": "已关闭", "已写入": "已写入", "已删除": "已删除", + "已删除 {{n}} 条通知": "已删除 {{n}} 条通知", "已删除「{{name}}」": "已删除「{{name}}」", "已办": "已办", "已加签": "已加签", @@ -1510,6 +1514,7 @@ "批量删除登录日志": "批量删除登录日志", "批量删除短信发送日志": "批量删除短信发送日志", "批量删除角色": "批量删除角色", + "批量删除通知": "批量删除通知", "批量删除通知公告": "批量删除通知公告", "批量导入": "批量导入", "批量更新参数配置": "批量更新参数配置", @@ -2136,6 +2141,7 @@ "没有匹配的部门": "没有匹配的部门", "没有匹配项": "没有匹配项", "没有发现问题": "没有发现问题", + "没有可清空的已读通知": "没有可清空的已读通知", "没有可用来验证身份的第三方账号,请联系管理员为你重置密码。": "没有可用来验证身份的第三方账号,请联系管理员为你重置密码。", "没有可读取的分区": "没有可读取的分区", "没有地址(邮箱 / 手机号)": "没有地址(邮箱 / 手机号)", @@ -2221,6 +2227,7 @@ "清空回收站": "清空回收站", "清空失败": "清空失败", "清空已保存的密钥": "清空已保存的密钥", + "清空已读": "清空已读", "清空操作日志": "清空操作日志", "清空登录日志": "清空登录日志", "清空短信发送日志": "清空短信发送日志", @@ -2376,6 +2383,7 @@ "确定删除选中的 {{n}} 个文件(共 {{size}})吗?磁盘文件与业务关联会一并删除,此操作不可撤销。": "确定删除选中的 {{n}} 个文件(共 {{size}})吗?磁盘文件与业务关联会一并删除,此操作不可撤销。", "确定删除选中的 {{n}} 个用户吗?此操作不可撤销。": "确定删除选中的 {{n}} 个用户吗?此操作不可撤销。", "确定删除选中的 {{n}} 条通知公告吗?此操作不可撤销。": "确定删除选中的 {{n}} 条通知公告吗?此操作不可撤销。", + "确定删除选中的 {{n}} 条通知吗?此操作不可撤销。": "确定删除选中的 {{n}} 条通知吗?此操作不可撤销。", "确定卸载「{{summary}}({{name}})」吗?": "确定卸载「{{summary}}({{name}})」吗?", "确定把「{{who}}」设为超级管理员吗?": "确定把「{{who}}」设为超级管理员吗?", "确定重置": "确定重置", @@ -2477,7 +2485,7 @@ "系统上传文件的统一入口,支持预览、下载与批量清理。": "系统上传文件的统一入口,支持预览、下载与批量清理。", "系统发信用的 SMTP 服务器。密码以密文展示。": "系统发信用的 SMTP 服务器。密码以密文展示。", "系统架构": "系统架构", - "系统消息与公告的收件箱。已读状态只属于你自己。": "系统消息与公告的收件箱。已读状态只属于你自己。", + "系统消息与公告的收件箱。已读和删除只影响你自己;公告和全员通知不能删除。": "系统消息与公告的收件箱。已读和删除只影响你自己;公告和全员通知不能删除。", "系统现在正常吗?": "系统现在正常吗?", "系统管理": "系统管理", "系统级动态参数。登录与口令策略是活的 —— 改完立刻对所有人生效。": "系统级动态参数。登录与口令策略是活的 —— 改完立刻对所有人生效。", @@ -3155,6 +3163,7 @@ "键名请用大写字母、数字和下划线,且以字母开头": "键名请用大写字母、数字和下划线,且以字母开头", "键总数": "键总数", "长任务": "长任务", + "长按发给你个人的通知可以删除": "长按发给你个人的通知可以删除", "长时间未操作,已自动退出,请重新登录": "长时间未操作,已自动退出,请重新登录", "问点什么…": "问点什么…", "问点关于这套系统的事": "问点关于这套系统的事", diff --git a/packages/platform/src/pages/notification/AGENTS.md b/packages/platform/src/pages/notification/AGENTS.md index 7e4c6dbb..271de772 100644 --- a/packages/platform/src/pages/notification/AGENTS.md +++ b/packages/platform/src/pages/notification/AGENTS.md @@ -14,7 +14,7 @@ |---|---| | `api.ts` | query key 工厂 + queryOptions + mutation。**铃铛和页面共用它** —— 任一处标记已读,另一处的红点立刻跟着变,不用互相通知 | | `bell.tsx` | 顶栏铃铛:红点 + 下拉预览(最近 8 条 / 三个页签 / 全部已读 / 查看全部) | -| `index.tsx` + `columns.tsx` | 完整列表页(翻历史 / 筛已读未读 / 全部已读),标准三件套 | +| `index.tsx` + `columns.tsx` | 完整列表页(翻历史 / 筛已读未读 / 全部已读 / 删除 · 批量删除 · 清空已读),标准三件套 | | `use-open.ts` | 「点开一条通知」的唯一实现(校验 `link` + 未读才标已读),两处共用 | | `shared.tsx` | 分类的图标/配色/标签 + 相对时间(「2 分钟前」) | @@ -162,3 +162,17 @@ ⚠️ 选人 / 部门 / 角色的下拉绑的是底座接口(`/sys/users` · `/sys/depts` · `/sys/roles/all`),各要 `sys:user:list` / `sys:dept:list` / `sys:role:list`。 只有发公告权限、没有这三个码的人,下拉下面是一行「没有权限查看这些数据」(不是空列表,硬纪律 9)—— 这是**已知限制**; E2E 只用 admin 验过表单,「有公告权限、没这三个码」的角色没实测过。 + +## 🔴 能不能删只认 `deletable`,选择也要在表上禁(#449) + +公告和全员广播是全员共用的一行,后端不让删(判据见后端 [`plugin/notification` 分册](../../../../../apps/api/backend/plugin/notification/AGENTS.md))。 +前端只看接口回填的 `deletable`,**不要拿 `category` 去猜**:全员广播不止公告一种。 + +勾选要禁两处:`buildSelectColumn` 的 `canSelect` 只禁那一格的复选框,**表头的「全选本页」照样会把公告勾进去** +(`toggleAllPageRowsSelected` 不看单元格的 `disabled`),所以 `useTable` 上还要 `enableRowSelection: (row) => row.original.deletable`。 +批量删除时后端会静默跳过不能删的,漏了这一条不会报错,只是「已选 3 项」删完只少了 2 条。 + +**实测证据**:`e2e/tests/notification.spec.ts` 的「消息中心删除一条」:一条我的 + 一条全员广播,点「全选本页」应是「已选 1 项」。 +把 `enableRowSelection` 注释掉重跑,收到的是 **「已选 2 项」**(2026-11-26,PostgreSQL)—— 单元格复选框照样是禁用的。 +同一条还断言了广播那一行没有 `notification-delete-*`,删掉自己那条之后红点从 2 变成 1。 + diff --git a/packages/platform/src/pages/notification/api.ts b/packages/platform/src/pages/notification/api.ts index 372cbfb7..4e244c28 100644 --- a/packages/platform/src/pages/notification/api.ts +++ b/packages/platform/src/pages/notification/api.ts @@ -36,6 +36,11 @@ export type Notification = { * 只能在读者抽屉 / 弹窗里点「我已阅读」。查询时现算,不是数据库列 */ requires_ack: boolean + /** + * 能不能删(#449):只有点名发给我本人的能删。公告和全员广播是**全员共用的一行**,删了就是所有人一起看不到, + * 后端不让删。前端只认这个字段摆不摆删除按钮 / 能不能勾选,**不要拿 `category` 去猜**(全员广播不止公告一种) + */ + deletable: boolean } /** @@ -67,6 +72,8 @@ export type NotificationListParams = { category?: number /** true 只看未读 · false 只看已读 · undefined 不筛 */ unread?: boolean + /** 只看点名发给我本人的(= 能删的)。消息中心拿 `mine + unread=false` 的 total 当「清空已读」能删几条 */ + mine?: boolean } export type UnreadCount = { @@ -101,6 +108,7 @@ function qs(p: NotificationListParams): string { if (p.title) s.set('title', p.title) if (p.category !== undefined) s.set('category', String(p.category)) if (p.unread !== undefined) s.set('unread', String(p.unread)) + if (p.mine) s.set('mine', 'true') return s.toString() } @@ -169,3 +177,30 @@ export function useMarkAllNotificationsRead() { onSuccess: () => invalidateInbox(qc), }) } + +/** 删除一条我的通知(#449)。只能删 `deletable` 的;别的后端一律 404 */ +export function useDeleteNotification() { + const qc = useQueryClient() + return useMutation({ + mutationFn: (id: string) => api.DELETE(`/api/v1/sys/notifications/${id}`), + onSuccess: () => invalidateInbox(qc), + }) +} + +/** 批量删除。不是发给我本人的后端静默跳过,返回**实际删掉的条数** */ +export function useDeleteNotifications() { + const qc = useQueryClient() + return useMutation({ + mutationFn: (pks: string[]) => api.DELETE('/api/v1/sys/notifications', { body: { pks } }), + onSuccess: () => invalidateInbox(qc), + }) +} + +/** 清空已读:删掉发给我本人、且已读的全部通知(公告和全员广播不动),返回删掉的条数 */ +export function useDeleteReadNotifications() { + const qc = useQueryClient() + return useMutation({ + mutationFn: () => api.DELETE('/api/v1/sys/notifications/read'), + onSuccess: () => invalidateInbox(qc), + }) +} diff --git a/packages/platform/src/pages/notification/bell.tsx b/packages/platform/src/pages/notification/bell.tsx index 4f58d4cd..247b7418 100644 --- a/packages/platform/src/pages/notification/bell.tsx +++ b/packages/platform/src/pages/notification/bell.tsx @@ -2,7 +2,7 @@ import * as React from 'react' import { useTranslation } from 'react-i18next' import { Link } from '@tanstack/react-router' import { useQuery, useQueryClient } from '@tanstack/react-query' -import { IconBell, IconChevronRight } from '@tabler/icons-react' +import { IconBell, IconChevronRight, IconX } from '@tabler/icons-react' import { Badge } from '@admin/ui/components/badge' import { Button, buttonVariants } from '@admin/ui/components/button' @@ -10,6 +10,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@admin/ui/components/po import { QueryError } from '@admin/ui/components/query-error' import { Skeleton } from '@admin/ui/components/skeleton' import { Tabs, TabsList, TabsTrigger } from '@admin/ui/components/tabs' +import { toast } from '@admin/ui/components/toast' import { Tooltip, TooltipContent, TooltipTrigger } from '@admin/ui/components/tooltip' import { cn } from '@admin/ui/lib/utils' @@ -23,6 +24,7 @@ import { noticeIdOf, notificationsQuery, unreadCountQuery, + useDeleteNotification, useMarkAllNotificationsRead, } from './api' import { categoryMeta, relativeTime } from './shared' @@ -65,6 +67,7 @@ export function NotificationBell() { const unread = useQuery(unreadCountQuery) const markAll = useMarkAllNotificationsRead() + const del = useDeleteNotification() const { linkOf, readIfUnread } = useNotificationOpen() // 服务端推来「有新的」时重新拉未读数和列表。 @@ -222,7 +225,9 @@ export function NotificationBell() { const to = noticeId ? null : linkOf(n) const rowClass = cn( 'flex w-full items-start gap-3 px-4 py-3 text-start transition-colors hover:bg-muted/60', - !n.read_time && 'bg-muted/30' + !n.read_time && 'bg-muted/30', + // 能删的行右边留出删除按钮的宽度:不留的话按钮一出现就盖住未读红点(#451 评审) + n.deletable && 'pe-10' ) const onActivate = () => { setOpen(false) @@ -274,7 +279,7 @@ export function NotificationBell() { ) return ( -
  • +
  • {to ? ( )} + {/* 删除(#449):只有发给我本人的才有,悬停 / 键盘聚焦时出现。不弹二次确认 —— + 下拉里一条一条清理是高频小动作,确认框会把它变成三次点击;消息中心的批量 / 清空才确认。 + 和整行的链接 / 按钮是兄弟不是子孙:`` / ` + )}
  • ) })} diff --git a/packages/platform/src/pages/notification/columns.tsx b/packages/platform/src/pages/notification/columns.tsx index edb08b9b..7d3403a0 100644 --- a/packages/platform/src/pages/notification/columns.tsx +++ b/packages/platform/src/pages/notification/columns.tsx @@ -1,6 +1,6 @@ import { Link } from '@tanstack/react-router' import { createColumnHelper } from '@tanstack/react-table' -import { IconCheck, IconExternalLink, IconEyeCheck } from '@tabler/icons-react' +import { IconCheck, IconExternalLink, IconEyeCheck, IconTrash } from '@tabler/icons-react' import { formatDateTime } from '@admin/i18n' import { ACTIONS_COLUMN_ID } from '@admin/ui/components/data-table' @@ -10,6 +10,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@admin/ui/components/to import { cn } from '@admin/ui/lib/utils' import { TimeCell } from '../_shared/cells' +import { buildSelectColumn } from '../_shared/select-column' import { StatusPill } from '../_shared/status' import { AttachmentCount } from '../notice/shared' import { noticeIdOf, type Notification } from './api' @@ -27,10 +28,76 @@ export function buildColumns( onMarkRead: (n: Notification) => void, /** 公告那一行就地打开详情(写进本页 search 的 `notice`,见 `index.tsx`) */ onOpenNotice: (noticeId: string) => void, + /** 删除一条(只有 `deletable` 的行会摆这个按钮,#449) */ + onDelete: (n: Notification) => void, /** 普通函数不能自己调 hook —— 由组件传进来(i18n 分册第 5 条) */ t: TFn ) { + /** 「已读 / 需确认 / 标记已读」那一格 */ + function readCell(n: Notification) { + // 已读的行不摆一个禁用的按钮 —— 「标记已读」对它没有任何意义, + // 禁用态还会因为 `disabled:pointer-events-none` 连 tooltip 都打不开 + // ([ui 分册](../../../../ui/AGENTS.md) 那条)。 + // 阅读时间收进 tooltip 而不是直接摊在单元格里:它只有偶尔要看, + // 摊开会让这一列宽到把整张表推出视口。 + if (n.read_time) { + return ( + + } + > + + + + {t('已读于 {{at}}', { at: formatDateTime(n.read_time) })} + + + ) + } + // 🔴 必须确认的公告(#190)不给「标记已读」:那个 PUT 就是后端认的「我已阅读」, + // 在这里点一下等于替人确认了(弹窗不再弹、阅读统计里成了已读)。只能点标题打开抽屉、看完点「我已阅读」。 + // 不摆禁用按钮的理由同上(禁用态打不开 tooltip),换成一个说明原因的标记 + if (n.requires_ack) { + return ( + + + } + > + + + {t('必须确认:点标题打开,读完点「我已阅读」')} + + ) + } + return ( + + onMarkRead(n)} + /> + } + > + + + {t('标记已读')} + + ) + } + return [ + // 公告 / 全员广播不能删,也就不能勾(同 `index.tsx` 的 `enableRowSelection`) + buildSelectColumn(col, { canSelect: (n: Notification) => n.deletable }, t), col.accessor('title', { header: t('标题'), cell: ({ row, getValue }) => { @@ -138,63 +205,34 @@ export function buildColumns( header: () => {t('操作')}, cell: ({ row }) => { const n = row.original - // 已读的行不摆一个禁用的按钮 —— 「标记已读」对它没有任何意义, - // 禁用态还会因为 `disabled:pointer-events-none` 连 tooltip 都打不开 - // ([ui 分册](../../../../ui/AGENTS.md) 那条)。 - // 阅读时间收进 tooltip 而不是直接摊在单元格里:它只有偶尔要看, - // 摊开会让这一列宽到把整张表推出视口。 - if (n.read_time) { - return ( - - } - > - - - - {t('已读于 {{at}}', { at: formatDateTime(n.read_time) })} - - - ) - } - // 🔴 必须确认的公告(#190)不给「标记已读」:那个 PUT 就是后端认的「我已阅读」, - // 在这里点一下等于替人确认了(弹窗不再弹、阅读统计里成了已读)。只能点标题打开抽屉、看完点「我已阅读」。 - // 不摆禁用按钮的理由同上(禁用态打不开 tooltip),换成一个说明原因的标记 - if (n.requires_ack) { - return ( - - - } - > - - - {t('必须确认:点标题打开,读完点「我已阅读」')} - - ) - } + // 「已读 / 需确认 / 标记已读」那一格 + 删除(只有发给我本人的才有,#449)。 + // 不能删的行不摆禁用按钮(禁用态打不开 tooltip,同 `readCell`),留一格同宽的空位: + // 不留的话「已读」那个勾在可删 / 不可删的行之间左右跳,同一列对不齐 return ( - - onMarkRead(n)} - /> - } - > - - - {t('标记已读')} - +
    + {readCell(n)} + {n.deletable ? ( + + onDelete(n)} + /> + } + > + + + {t('删除')} + + ) : ( + + )} +
    ) }, }), diff --git a/packages/platform/src/pages/notification/index.tsx b/packages/platform/src/pages/notification/index.tsx index cb46aee1..26173002 100644 --- a/packages/platform/src/pages/notification/index.tsx +++ b/packages/platform/src/pages/notification/index.tsx @@ -1,17 +1,18 @@ import * as React from 'react' import { useTranslation } from 'react-i18next' import { useQuery } from '@tanstack/react-query' -import { useTable, type ColumnVisibilityState } from '@tanstack/react-table' -import { IconChecks } from '@tabler/icons-react' +import { useTable, type ColumnVisibilityState, type RowSelectionState } from '@tanstack/react-table' +import { IconChecks, IconTrashX } from '@tabler/icons-react' import { Button } from '@admin/ui/components/button' import { DataTable, DataTableColumnVisibility } from '@admin/ui/components/data-table' import { QueryBar, countActive, type FilterField } from '@admin/ui/components/query-bar' +import { toast } from '@admin/ui/components/toast' import { ConfirmDialog } from '../../shell/confirm-dialog' import { NoticeReaderSheet } from '../notice/reader-sheet' import { PageHeader } from '../../shell/page-header' -import { RefreshButton } from '../_shared/filters' +import { BulkBar, RefreshButton } from '../_shared/filters' import { listState, usePageRecovery } from '../_shared/list-query' import { DEFAULT_PAGE_SIZE } from '../_shared/pagination' import { useQuerySearch } from '../_shared/use-query-search' @@ -21,6 +22,9 @@ import { notificationKeys, notificationsQuery, unreadCountQuery, + useDeleteNotification, + useDeleteNotifications, + useDeleteReadNotifications, useMarkAllNotificationsRead, useMarkNotificationRead, type Notification, @@ -113,8 +117,37 @@ export function NotificationPage({ const [columnVisibility, setColumnVisibility] = React.useState({}) const [markAllOpen, setMarkAllOpen] = React.useState(false) + const [rowSelection, setRowSelection] = React.useState({}) + const [pendingDelete, setPendingDelete] = React.useState(null) + const [deleteError, setDeleteError] = React.useState(null) + const [bulkOpen, setBulkOpen] = React.useState(false) + const [clearReadOpen, setClearReadOpen] = React.useState(false) + // 批量 / 清空失败时的原因:确认框留着、原因写在问题下面(同单条删除)。原来 `finally` 里直接关框, + // 异常从 `void onConfirm()` 漏成一次没人接的 rejection,界面上什么都没有(硬纪律 9,#451 评审) + const [bulkError, setBulkError] = React.useState(null) + const [clearError, setClearError] = React.useState(null) + + // 换页 / 换筛选清掉选中:分页在服务端,留着的选中项已不在可见行里,批量删除会打到看不见的记录上 + const patch = React.useCallback( + (next: Partial) => { + setRowSelection({}) + onSearchChange?.({ ...search, ...next }) + }, + [onSearchChange, search] + ) const q = useQuerySearch({ fields: FIELDS, search, onSearchChange, refreshKey: notificationKeys.all }) + const submitQuery = React.useCallback( + (v: Parameters[0]) => { + setRowSelection({}) + q.submit(v) + }, + [q] + ) + const resetQuery = React.useCallback(() => { + setRowSelection({}) + q.reset() + }, [q]) const raw = q.params as { title?: string; category?: number; unread?: number } const params: NotificationListParams = { @@ -130,7 +163,7 @@ export function NotificationPage({ const listQuery = useQuery(notificationsQuery(params)) const { data, isFetching } = listQuery const list = listState(listQuery) - usePageRecovery(listQuery, { page, size, onPageChange: (page) => onSearchChange?.({ ...search, page: page === 1 ? undefined : page }) }) + usePageRecovery(listQuery, { page, size, onPageChange: (page) => patch({ page: page === 1 ? undefined : page }) }) const rows = data?.items ?? [] const total = data?.total ?? 0 const totalPages = data?.total_pages ?? 1 @@ -138,6 +171,9 @@ export function NotificationPage({ const unread = useQuery(unreadCountQuery) const markRead = useMarkNotificationRead() const markAll = useMarkAllNotificationsRead() + const delOne = useDeleteNotification() + const delMany = useDeleteNotifications() + const delRead = useDeleteReadNotifications() const { linkOf, readIfUnread } = useNotificationOpen() const handleMarkRead = React.useCallback((n: Notification) => markRead.mutate(n.id), [markRead]) @@ -149,7 +185,7 @@ export function NotificationPage({ // 标已读一律由抽屉做(点那一行 / 地址栏深链都一样):它看得到这条是不是「必须确认」(#190)。 // 原来点行时先 `readIfUnread`、抽屉再按 `rowAlreadyMarked` 跳过,必须确认的就被那一下替人确认了 const columns = React.useMemo( - () => buildColumns(linkOf, readIfUnread, handleMarkRead, openNotice, t), + () => buildColumns(linkOf, readIfUnread, handleMarkRead, openNotice, setPendingDelete, t), [linkOf, readIfUnread, handleMarkRead, openNotice, t] ) @@ -159,23 +195,33 @@ export function NotificationPage({ // v9 的列定义数组混用不同 TValue 会形成联合类型,与 useTable 期望的 // ColumnDef<..., unknown>[] 不兼容(库的类型方差限制) columns: columns as never, - state: { columnVisibility }, + state: { columnVisibility, rowSelection }, getRowId: (row) => row.id, manualPagination: true, rowCount: total, + // 只有发给我本人的能删(#449)。「全选本页」也认它 —— 只在复选框上禁用的话,表头一勾就把公告也勾进去了 + enableRowSelection: (row) => row.original.deletable, onColumnVisibilityChange: setColumnVisibility, + onRowSelectionChange: setRowSelection, }) + const selectedIds = Object.keys(rowSelection).filter((k) => rowSelection[k]) // 「全部已读」标得掉的条数:必须确认的公告后端会跳过(#190),按总数判的话只剩它们时按钮还亮着、点了什么都不变 const markable = markableUnread(unread.data) const mustAck = unread.data?.requires_ack_count ?? 0 + // 「清空已读」能删几条(#451 评审:原来按钮一直亮,没东西可清也让人确认一次)= 发给我本人的已读条数。 + // 🔴 单独查一页 size=1 只拿 total,**不塞进 `/unread-count`**:铃铛每次收件箱变动都重拉那个接口,后端只许它一条统计查询 + // (`test_unread_count_is_one_scan`,第一版就是塞进去被它拦下的)。key 在 `notificationKeys.all` 下,删除 / 标已读后跟着失效。 + // 🔴 只在**确实知道是 0** 时禁用:这条查询挂了 `clearable` 是 undefined,按钮照旧能点(硬纪律 9,同移动端「全部已读」) + const clearableQuery = useQuery(notificationsQuery({ page: 1, size: 1, unread: false, mine: true })) + const clearable = clearableQuery.data?.total const hasFilter = countActive(q.applied, FIELDS) > 0 return ( @@ -183,8 +229,8 @@ export function NotificationPage({ fields={FIELDS} value={q.value} onChange={q.setValue} - onSearch={q.submit} - onReset={q.reset} + onSearch={submitQuery} + onReset={resetQuery} applied={q.applied} loading={isFetching} viewsStorageKey="qb:notification" @@ -200,8 +246,20 @@ export function NotificationPage({ {markable > 0 ? t('全部已读({{n}})', { n: markable }) : t('全部已读')} + + {/* 批量条放左组末尾:它随选中行出现 / 消失,放右组会让「搜索 / 重置」横向位移 */} + setBulkOpen(true)} /> } /> @@ -226,10 +284,10 @@ export function NotificationPage({ pageIndex: page - 1, pageCount: totalPages, pageSize: size, + selectedCount: selectedIds.length, totalCount: total, - onPageChange: (i) => - onSearchChange?.({ ...search, page: i === 0 ? undefined : i + 1 }), - onPageSizeChange: (s) => onSearchChange?.({ ...search, size: s, page: undefined }), + onPageChange: (i) => patch({ page: i === 0 ? undefined : i + 1 }), + onPageSizeChange: (s) => patch({ size: s, page: undefined }), }} /> @@ -262,6 +320,90 @@ export function NotificationPage({ setMarkAllOpen(false) }} /> + + { + if (o) return + setPendingDelete(null) + setDeleteError(null) + }} + title={t('删除通知')} + description={pendingDelete ? t('确定删除「{{title}}」吗?此操作不可撤销。', { title: pendingDelete.title }) : ''} + error={deleteError} + confirmText={t('删除')} + destructive + pending={delOne.isPending} + onConfirm={async () => { + if (!pendingDelete) return + setDeleteError(null) + try { + await delOne.mutateAsync(pendingDelete.id) + setRowSelection((s) => { + const { [pendingDelete.id]: _, ...rest } = s + return rest + }) + setPendingDelete(null) + } catch (e) { + setDeleteError(e instanceof Error ? e.message : t('删除失败')) + } + }} + /> + + { + setBulkOpen(o) + if (!o) setBulkError(null) + }} + title={t('批量删除通知')} + description={t('确定删除选中的 {{n}} 条通知吗?此操作不可撤销。', { n: selectedIds.length })} + error={bulkError} + confirmText={t('删除')} + destructive + pending={delMany.isPending} + onConfirm={async () => { + setBulkError(null) + try { + const n = await delMany.mutateAsync(selectedIds) + setRowSelection({}) + setBulkOpen(false) + toast.success(t('已删除 {{n}} 条通知', { n })) + } catch (e) { + setBulkError(e instanceof Error ? e.message : t('删除失败')) + } + }} + /> + + {/* 条数来自 `clearableQuery`:已读的可能在别的页,前端自己数不出来 */} + { + setClearReadOpen(o) + if (!o) setClearError(null) + }} + title={t('清空已读')} + description={ + clearable === undefined + ? t('会删除发给你个人的全部已读通知,公告和全员通知不受影响。此操作不可撤销。') + : t('会删除发给你个人的 {{n}} 条已读通知,公告和全员通知不受影响。此操作不可撤销。', { n: clearable }) + } + error={clearError} + confirmText={t('清空')} + destructive + pending={delRead.isPending} + onConfirm={async () => { + setClearError(null) + try { + const n = await delRead.mutateAsync() + setRowSelection({}) + setClearReadOpen(false) + toast.success(n > 0 ? t('已删除 {{n}} 条通知', { n }) : t('没有可清空的已读通知')) + } catch (e) { + setClearError(e instanceof Error ? e.message : t('删除失败')) + } + }} + /> ) } diff --git a/packages/platform/src/pages/notification/table-features.ts b/packages/platform/src/pages/notification/table-features.ts index 56fdcd1b..82a907c1 100644 --- a/packages/platform/src/pages/notification/table-features.ts +++ b/packages/platform/src/pages/notification/table-features.ts @@ -1,11 +1,15 @@ -import { columnVisibilityFeature, rowPaginationFeature, tableFeatures } from '@tanstack/react-table' +import { + columnVisibilityFeature, + rowPaginationFeature, + rowSelectionFeature, + tableFeatures, +} from '@tanstack/react-table' /** * TanStack Table v9 是 tree-shaken 的 —— 用到哪个特性就要显式注册。 * - * **不注册 `rowSelectionFeature`**:收件箱没有批量动作。接口只有「标记一条」和 - * 「全部已读」两个动作,摆一列复选框却没有任何按钮能作用于选中项, - * 是个点了没反应的空控件。 + * 注册 `rowSelectionFeature`:批量删除(#449)。只有 `deletable` 的行能勾(`index.tsx` 的 + * `enableRowSelection`)—— 公告和全员广播删不掉,让人勾上再被后端静默跳过是个骗人的控件。 * * 也不注册排序:`crud_notification.py` 固定 `select_order('id', 'desc')`, * 接口没有排序入参。 @@ -13,4 +17,5 @@ import { columnVisibilityFeature, rowPaginationFeature, tableFeatures } from '@t export const features = tableFeatures({ columnVisibilityFeature, rowPaginationFeature, + rowSelectionFeature, })