Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions apps/api/backend/plugin/notification/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)。
35 changes: 34 additions & 1 deletion apps/api/backend/plugin/notification/api/v1/sys/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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='发送站内通知',
Expand Down
54 changes: 53 additions & 1 deletion apps/api/backend/plugin/notification/crud/crud_notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
获取「我的通知」列表查询表达式
Expand All @@ -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:
Expand Down Expand Up @@ -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(只认广播行;同一来源有多行时取最新的)
Expand Down
10 changes: 10 additions & 0 deletions apps/api/backend/plugin/notification/schema/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
"""
获取「我的通知」分页列表
Expand All @@ -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,见模型注释),
Expand All @@ -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
Expand Down Expand Up @@ -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:
"""
Expand Down
Loading
Loading