feat(dm): 私信支持按用户名搜索开聊,并加入首轮发送条数限制

一、私信用户搜索

此前只能先进入对方个人主页、再点「私信」才能发起会话。现在私信窗口
顶部新增搜索框,输入用户名即可搜索并直接开聊。

- 新增 GET /api/users/search:按用户名模糊匹配,前缀匹配优先、其次按
  名字长度排序(更接近精确结果)。只返回用户名、头像、角色、签名,
  不暴露邮箱等隐私字段(已实测确认响应中不含 email)。
- 关键词转义 % 与 _,与帖子搜索同样处理,避免通配符被当作模式。
- 关键词长度上限 50 字,limit 上限 20。
- 搜索结果中排除自己;输入防抖 300ms,回车立即搜索,Esc 与清除按钮
  回到会话列表。
- 搜索框同样带上防密码管理器误填的属性,并在关闭窗口时清空关键词,
  避免下次打开残留上次的搜索状态。

二、首轮发送条数限制

对方尚未回复时,发起方最多先发 3 条消息;对方一旦回复过,限制永久
解除。仅对「对方从未回复」的会话生效,已正常交流过的会话不受影响。

- 判定放在事务中并对会话行加 FOR UPDATE 锁:限制依赖「我方已发几条、
  对方是否回过」两个计数,不加锁时并发发送可绕过。
- 达到上限返回 429,附带 limit_reached 与 limit 字段,前端据此给出
  针对性提示而非笼统的「发送失败」。
- 发送成功时在响应中返回 remaining(对方已回复时为 null)。
- 聊天窗口底部新增提示条,显示「对方回复前还可发送 N 条消息」,
  对方回复后自动隐藏。数字与文字分置于不同元素,使固定文案能被
  i18n 词典匹配(整句含动态数字时匹配不上)。

实测:
- 用户搜索:「dmtester」命中 2 个、「tester2」命中 1 个、无匹配返回 0,
  响应中 email 字段出现 0 次
- 连续发送 4 条:前 3 条成功且 remaining 依次为 2/1/0,
  第 4 条返回 429 与明确提示
- 对方回复后再发送:成功且 remaining 为 null,限制已解除
- 前端:搜索框正常显示,点击结果直接进入聊天窗口
- 全新会话提示条显示「对方回复前还可发送 3 条消息」,
  发送 1 条后更新为 2 条

完整测试套件 25/25 通过。
This commit is contained in:
Furrium Network committed 2026-09-22 22:12:05 +08:00
1 parent c26e834982
commit 5995efc7a0
6 files changed
+407 -7

No files matched your search

+15
View File
@@ -480,6 +480,19 @@
<h2 style="font-size:18px;margin:0;">✉️ 私信</h2>
<span class="close" data-modal="messageListModal" style="font-size:24px;cursor:pointer;color:var(--text-light);line-height:1;">&times;</span>
</div>
<!-- 用户搜索:此前只能从对方主页点「私信」才能发起会话,
这里提供按用户名搜索并直接开聊的入口 -->
<div class="dm-search-wrap">
<div class="dm-search">
<input type="search" id="dmUserSearchInput" name="dm-user-search"
placeholder="搜索用户名开始私信…" autocomplete="off"
role="searchbox" aria-label="搜索用户"
data-form-type="other" data-1p-ignore data-lpignore="true" />
<button type="button" id="dmUserSearchClear" class="dm-search-clear" title="清除搜索" style="display:none;">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
</div>
<div id="messageListContent" style="flex:1;overflow-y:auto;padding:0;">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</div>
@@ -499,6 +512,8 @@
<div id="chatMessages" style="flex:1;overflow-y:auto;padding:16px;min-height:300px;max-height:400px;">
<div style="text-align:center;color:#94a3b8;padding:40px 0;">加载中...</div>
</div>
<!-- 对方回复前的发送条数提示,由 JS 控制显示 -->
<div id="chatLimitNote" class="dm-limit-note" style="display:none;"></div>
<div style="display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border);flex-shrink:0;">
<input type="text" id="chatInput" placeholder="输入消息..." style="flex:1;padding:8px 12px;border:1px solid var(--border);border-radius:6px;font-size:14px;background:var(--bg);color:var(--text);outline:none;" />
<button onclick="sendMessage()" class="btn-primary" style="padding:8px 16px;">发送</button>