inbox-navigation.test.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. import { App as AntApp, ConfigProvider } from 'antd';
  2. import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
  3. import userEvent from '@testing-library/user-event';
  4. import { createMemoryRouter, RouterProvider } from 'react-router-dom';
  5. import { afterEach, describe, expect, it, vi } from 'vitest';
  6. import { AppContext, type AppContextValue } from '../../src/frontend/app-context';
  7. import { I18nProvider } from '../../src/frontend/i18n/react';
  8. import { detailHistoryState } from '../../src/frontend/navigation-state';
  9. import { api } from '../../src/frontend/services/api';
  10. import { mailhubTheme } from '../../src/frontend/theme';
  11. import type { Domain, InboundMailbox, InboundMessage, RuntimeConfig, WebmailLogin } from '../../src/frontend/types';
  12. import Inbox from '../../src/pages/Inbox';
  13. describe('Inbox detail return path', () => {
  14. afterEach(() => vi.restoreAllMocks());
  15. it('keeps the original list history when another message is selected from an open detail', async () => {
  16. const user = userEvent.setup();
  17. const first = messageFixture(9, 1, 'Sent', 'First message');
  18. const second = messageFixture(10, 1, 'Sent', 'Second message');
  19. mockInboxApis([mailboxFixture(1)], [first, second]);
  20. vi.spyOn(api, 'inboundMessage').mockImplementation(async (id) => ({ message: id === second.id ? second : first }));
  21. const listPath = '/inbox?mailboxId=1&folder=Sent&page=2';
  22. const router = createInboxRouter(['/overview', listPath], 1);
  23. renderRouter(router);
  24. await user.click(await screen.findByRole('button', { name: 'First message · sender@example.test' }));
  25. await waitFor(() => expect(router.state.location.pathname).toBe('/inbox/messages/9'));
  26. expect(detailHistoryState(router.state.location.state)).toEqual({ listPath, depth: 1, origin: 'list' });
  27. fireEvent.click(screen.getByRole('button', { name: 'Second message · sender@example.test' }));
  28. await waitFor(() => expect(router.state.location.pathname).toBe('/inbox/messages/10'));
  29. expect(detailHistoryState(router.state.location.state)).toEqual({ listPath, depth: 2, origin: 'list' });
  30. fireEvent.click(screen.getByRole('button', { name: 'Close' }));
  31. await waitFor(() => expect(`${router.state.location.pathname}${router.state.location.search}`).toBe(listPath));
  32. await act(async () => {
  33. await router.navigate(-1);
  34. });
  35. expect(router.state.location.pathname).toBe('/overview');
  36. });
  37. it('keeps direct detail tabs navigable and closes them without reopening on Back', async () => {
  38. const user = userEvent.setup();
  39. const deepLinked = messageFixture(20, 2, 'Archive', 'Archived message');
  40. const messages = vi.fn(async () => ({ messages: [deepLinked], total: 1, page: 1, pageSize: 25 }));
  41. mockInboxApis([mailboxFixture(1), mailboxFixture(2)], [deepLinked]);
  42. vi.spyOn(api, 'inboundMessages').mockImplementation(messages);
  43. vi.spyOn(api, 'inboundMessage').mockResolvedValue({ message: deepLinked });
  44. const router = createInboxRouter(['/overview', '/inbox/messages/20'], 1);
  45. renderRouter(router);
  46. expect(await screen.findByText('Archived message')).toBeTruthy();
  47. await waitFor(() => {
  48. const params = new URLSearchParams(router.state.location.search);
  49. expect(params.get('mailboxId')).toBe('2');
  50. expect(params.get('folder')).toBe('Archive');
  51. });
  52. await waitFor(() => expect(messages).toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 2, folder: 'Archive' })));
  53. await user.click(screen.getByRole('tab', { name: 'HTML 预览' }));
  54. await waitFor(() => expect(new URLSearchParams(router.state.location.search).get('tab')).toBe('html'));
  55. expect(detailHistoryState(router.state.location.state)).toEqual({
  56. listPath: '/inbox?mailboxId=2&folder=Archive',
  57. depth: 1,
  58. origin: 'direct'
  59. });
  60. await act(async () => {
  61. await router.navigate(-1);
  62. });
  63. expect(router.state.location.pathname).toBe('/inbox/messages/20');
  64. expect(new URLSearchParams(router.state.location.search).has('tab')).toBe(false);
  65. expect(detailHistoryState(router.state.location.state)).toBeNull();
  66. await act(async () => {
  67. await router.navigate(1);
  68. });
  69. expect(new URLSearchParams(router.state.location.search).get('tab')).toBe('html');
  70. expect(detailHistoryState(router.state.location.state)?.origin).toBe('direct');
  71. fireEvent.click(screen.getByRole('button', { name: 'Close' }));
  72. await waitFor(() => expect(router.state.location.pathname).toBe('/inbox'));
  73. const params = new URLSearchParams(router.state.location.search);
  74. expect(params.get('mailboxId')).toBe('2');
  75. expect(params.get('folder')).toBe('Archive');
  76. await act(async () => {
  77. await router.navigate(-1);
  78. });
  79. expect(router.state.location.pathname).toBe('/overview');
  80. expect(router.state.location.pathname).not.toContain('/messages/');
  81. });
  82. it('uses a detail drawer below the 1280px product breakpoint', async () => {
  83. vi.spyOn(window, 'matchMedia').mockImplementation((query) => mediaQueryList(query === '(min-width: 992px)', query));
  84. const deepLinked = messageFixture(30, 1, 'INBOX', 'Compact detail');
  85. mockInboxApis([mailboxFixture(1)], [deepLinked]);
  86. vi.spyOn(api, 'inboundMessage').mockResolvedValue({ message: deepLinked });
  87. const router = createInboxRouter(['/inbox/messages/30'], 0);
  88. renderRouter(router);
  89. expect(await screen.findByRole('button', { name: 'Close' })).toBeTruthy();
  90. });
  91. it('renders HTML-only messages in a sandboxed preview while keeping the source tab available', async () => {
  92. const user = userEvent.setup();
  93. const htmlOnly = {
  94. ...messageFixture(31, 1, 'INBOX', 'HTML only'),
  95. textBody: '',
  96. htmlBody: '<html><body><h1>Rendered invoice</h1><script>window.parent.pwned = true</script></body></html>'
  97. };
  98. mockInboxApis([mailboxFixture(1)], [htmlOnly]);
  99. vi.spyOn(api, 'inboundMessage').mockResolvedValue({ message: htmlOnly });
  100. const router = createInboxRouter(['/inbox/messages/31?mailboxId=1&folder=INBOX'], 0);
  101. renderRouter(router);
  102. const preview = await screen.findByTitle('HTML 预览') as HTMLIFrameElement;
  103. expect(screen.getByRole('tab', { name: 'HTML 预览' }).getAttribute('aria-selected')).toBe('true');
  104. expect(preview.getAttribute('sandbox')).toBe('');
  105. expect(preview.getAttribute('referrerpolicy')).toBe('no-referrer');
  106. expect(preview.getAttribute('srcdoc')).toContain('<h1>Rendered invoice</h1>');
  107. expect(preview.getAttribute('srcdoc')).toContain("script-src 'none'");
  108. await user.click(screen.getByRole('tab', { name: 'HTML 源码' }));
  109. expect(screen.getByText(/Rendered invoice/)).toBeTruthy();
  110. await waitFor(() => expect(new URLSearchParams(router.state.location.search).get('tab')).toBe('source'));
  111. });
  112. });
  113. describe('Inbox request and mailbox behavior', () => {
  114. afterEach(() => vi.restoreAllMocks());
  115. it('keeps the search draft synchronized with browser history', async () => {
  116. mockInboxApis([mailboxFixture(1)], []);
  117. const router = createInboxRouter([
  118. '/inbox?mailboxId=1&folder=INBOX&q=first%20query',
  119. '/inbox?mailboxId=1&folder=INBOX&q=second%20query'
  120. ], 1);
  121. renderRouter(router);
  122. const searchInput = await screen.findByPlaceholderText('搜索发件人、主题或正文预览') as HTMLInputElement;
  123. expect(searchInput.value).toBe('second query');
  124. await act(async () => {
  125. await router.navigate(-1);
  126. });
  127. await waitFor(() => expect(searchInput.value).toBe('first query'));
  128. await act(async () => {
  129. await router.navigate(1);
  130. });
  131. await waitFor(() => expect(searchInput.value).toBe('second query'));
  132. });
  133. it('does not let an older message-list response replace the current mailbox', async () => {
  134. const first = messageFixture(41, 1, 'INBOX', 'Stale mailbox message');
  135. const second = messageFixture(42, 2, 'INBOX', 'Current mailbox message');
  136. let resolveFirst: ((value: { messages: InboundMessage[]; total: number; page: number; pageSize: number }) => void) | undefined;
  137. const firstResponse = new Promise<{ messages: InboundMessage[]; total: number; page: number; pageSize: number }>((resolve) => {
  138. resolveFirst = resolve;
  139. });
  140. mockInboxApis([mailboxFixture(1), mailboxFixture(2)], []);
  141. const list = vi.spyOn(api, 'inboundMessages').mockImplementation(async (filters) => {
  142. const mailboxId = typeof filters === 'number' ? filters : filters?.mailboxId;
  143. if (mailboxId === 1) return firstResponse;
  144. return { messages: [second], total: 1, page: 1, pageSize: 25 };
  145. });
  146. const router = createInboxRouter(['/inbox?mailboxId=1&folder=INBOX'], 0);
  147. renderRouter(router);
  148. await waitFor(() => expect(list).toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 1 })));
  149. await act(async () => {
  150. await router.navigate('/inbox?mailboxId=2&folder=INBOX');
  151. });
  152. expect(await screen.findByText('Current mailbox message')).toBeTruthy();
  153. await act(async () => {
  154. resolveFirst?.({ messages: [first], total: 1, page: 1, pageSize: 25 });
  155. await Promise.resolve();
  156. });
  157. expect(screen.queryByText('Stale mailbox message')).toBeNull();
  158. expect(screen.getByText('Current mailbox message')).toBeTruthy();
  159. });
  160. it('keeps message content visible when marking it as read fails', async () => {
  161. const unread = { ...messageFixture(50, 1, 'INBOX', 'Unread detail'), read: false };
  162. mockInboxApis([mailboxFixture(1, { unreadCount: 1 })], [unread]);
  163. vi.spyOn(api, 'inboundMessage').mockResolvedValue({ message: unread });
  164. vi.spyOn(api, 'markInboundMessageRead').mockRejectedValue(new Error('mark read failed'));
  165. const router = createInboxRouter(['/inbox/messages/50?mailboxId=1&folder=INBOX'], 0);
  166. renderRouter(router);
  167. expect(await screen.findByText('Unread detail body')).toBeTruthy();
  168. expect(await screen.findByText('mark read failed')).toBeTruthy();
  169. });
  170. it('shows unavailable folder counts and retries instead of displaying fake zeroes', async () => {
  171. vi.spyOn(window, 'matchMedia').mockImplementation((query) => mediaQueryList(query === '(min-width: 992px)' || query === '(min-width: 768px)', query));
  172. mockInboxApis([mailboxFixture(1)], []);
  173. const folders = vi.spyOn(api, 'inboundFolders')
  174. .mockRejectedValueOnce(new Error('folder request failed'))
  175. .mockResolvedValue({ folders: [{ name: 'INBOX', specialUse: null, messageCount: 3, unreadCount: 2 }] });
  176. const router = createInboxRouter(['/inbox?mailboxId=1&folder=INBOX'], 0);
  177. renderRouter(router);
  178. const warning = await screen.findByText('文件夹计数暂不可用。');
  179. expect(warning).toBeTruthy();
  180. expect(screen.getAllByLabelText('计数不可用').length).toBeGreaterThan(0);
  181. const alert = warning.closest('.ant-alert');
  182. expect(alert).toBeTruthy();
  183. await userEvent.click(within(alert as HTMLElement).getByRole('button', { name: /刷\s*新/ }));
  184. await waitFor(() => expect(folders).toHaveBeenCalledTimes(2));
  185. await waitFor(() => expect(screen.queryByText('文件夹计数暂不可用。')).toBeNull());
  186. });
  187. it('selects the mailbox with the most recent activity when the URL has no mailbox', async () => {
  188. const older = mailboxFixture(1, { lastMessageAt: '2026-07-14T00:00:00.000Z' });
  189. const recent = mailboxFixture(2, { lastMessageAt: '2026-07-15T00:00:00.000Z' });
  190. mockInboxApis([older, recent], []);
  191. const list = vi.spyOn(api, 'inboundMessages');
  192. const router = createInboxRouter(['/inbox'], 0);
  193. renderRouter(router);
  194. await waitFor(() => expect(list).toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 2 })));
  195. expect(new URLSearchParams(router.state.location.search).get('mailboxId')).toBe('2');
  196. });
  197. it('uses effective mailbox access and never loads messages for view-only assignments', async () => {
  198. const viewOnly = mailboxFixture(1, {
  199. userId: 2,
  200. ownerUserId: 2,
  201. access: { type: 'assigned', permissions: { view: true, receive: false, send: false } },
  202. messageCount: null,
  203. unreadCount: null,
  204. lastMessageAt: null
  205. });
  206. const receiving = mailboxFixture(2, {
  207. userId: 2,
  208. ownerUserId: 2,
  209. access: { type: 'assigned', permissions: { view: true, receive: true, send: false } }
  210. });
  211. mockInboxApis([viewOnly, receiving], []);
  212. const loadMailboxes = vi.spyOn(api, 'inboundMailboxes');
  213. const listMessages = vi.spyOn(api, 'inboundMessages');
  214. const router = createInboxRouter(['/inbox?mailboxId=1&folder=INBOX'], 0);
  215. renderRouter(router);
  216. await waitFor(() => expect(loadMailboxes).toHaveBeenCalledWith('effective'));
  217. await waitFor(() => expect(new URLSearchParams(router.state.location.search).get('mailboxId')).toBe('2'));
  218. await waitFor(() => expect(listMessages).toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 2 })));
  219. expect(listMessages).not.toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 1 }));
  220. });
  221. it('offers the Webmail shortcut in mailbox routing only to owners and assigned receivers', async () => {
  222. const user = userEvent.setup();
  223. const owner = mailboxFixture(1);
  224. const assigned = mailboxFixture(2, {
  225. userId: 2,
  226. ownerUserId: 2,
  227. access: { type: 'assigned', permissions: { view: true, receive: true, send: false } }
  228. });
  229. const viewOnly = mailboxFixture(3, {
  230. userId: 2,
  231. ownerUserId: 2,
  232. access: { type: 'assigned', permissions: { view: true, receive: false, send: false } },
  233. messageCount: null,
  234. unreadCount: null
  235. });
  236. mockInboxApis([owner, assigned, viewOnly], []);
  237. const webmailLogin: WebmailLogin = {
  238. action: 'https://mail.us.ss5.xyz/',
  239. ticket: 'mht_routing-ticket',
  240. expiresAt: '2026-07-18T01:00:00.000Z'
  241. };
  242. const login = vi.spyOn(api, 'createWebmailLogin').mockResolvedValue({ webmailLogin });
  243. const requestSubmit = vi.spyOn(HTMLFormElement.prototype, 'requestSubmit').mockImplementation(() => undefined);
  244. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  245. renderRouter(router);
  246. const ownerCard = (await screen.findByText(owner.address)).closest('.ant-card') as HTMLElement;
  247. const assignedCard = screen.getByText(assigned.address).closest('.ant-card') as HTMLElement;
  248. const viewOnlyCard = screen.getByText(viewOnly.address).closest('.ant-card') as HTMLElement;
  249. expect(within(ownerCard).getByRole('button', { name: /一键登录 Webmail/ })).toBeTruthy();
  250. expect(within(viewOnlyCard).queryByRole('button', { name: /一键登录 Webmail/ })).toBeNull();
  251. await user.click(within(assignedCard).getByRole('button', { name: /一键登录 Webmail/ }));
  252. await waitFor(() => expect(login).toHaveBeenCalledWith(assigned.id));
  253. expect(requestSubmit).toHaveBeenCalledTimes(1);
  254. });
  255. it('updates mailbox settings from the routing workspace edit drawer', async () => {
  256. const user = userEvent.setup();
  257. const mailbox = mailboxFixture(1);
  258. mockInboxApis([mailbox], [], [domainFixture(1)]);
  259. const update = vi.spyOn(api, 'updateInboundMailbox').mockResolvedValue({
  260. mailbox: { ...mailbox, displayName: 'Updated inbox', aliases: ['sales'] }
  261. });
  262. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  263. renderRouter(router);
  264. const mailboxTitle = await screen.findByText(mailbox.address);
  265. const card = mailboxTitle.closest('.ant-card');
  266. expect(card).toBeTruthy();
  267. await user.click(within(card as HTMLElement).getByRole('button', { name: /修改/ }));
  268. const displayName = await screen.findByLabelText('显示名称');
  269. await user.clear(displayName);
  270. await user.type(displayName, 'Updated inbox');
  271. await user.type(screen.getByLabelText('新密码'), 'new-password-123');
  272. await user.clear(screen.getByLabelText('别名'));
  273. await user.type(screen.getByLabelText('别名'), 'sales');
  274. await user.click(screen.getByRole('button', { name: /保\s*存/ }));
  275. await waitFor(() => expect(update).toHaveBeenCalledWith(1, expect.objectContaining({
  276. displayName: 'Updated inbox',
  277. password: 'new-password-123',
  278. aliases: 'sales',
  279. status: 'active'
  280. })));
  281. });
  282. it('migrates mail before deleting an owned mailbox and excludes shared mailboxes as targets', async () => {
  283. const user = userEvent.setup();
  284. const source = mailboxFixture(1, { messageCount: 5 });
  285. const target = mailboxFixture(2, { messageCount: 1 });
  286. const assigned = mailboxFixture(3, {
  287. ownerUserId: 1,
  288. access: { type: 'assigned', permissions: { view: true, receive: true, send: true } }
  289. });
  290. const disabled = mailboxFixture(4, { status: 'disabled' });
  291. const expired = mailboxFixture(5, {
  292. temporary: true,
  293. expiresAt: '2000-01-01T00:00:00.000Z'
  294. });
  295. mockInboxApis([source, target, assigned, disabled, expired], []);
  296. const loadMailboxes = vi.mocked(api.inboundMailboxes);
  297. let resolveDelete!: (value: {
  298. deletedMailbox: InboundMailbox;
  299. targetMailbox: InboundMailbox;
  300. migratedMessageCount: number;
  301. }) => void;
  302. const remove = vi.spyOn(api, 'deleteInboundMailbox').mockReturnValue(new Promise((resolve) => {
  303. resolveDelete = resolve;
  304. }));
  305. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  306. renderRouter(router);
  307. const sourceCard = (await screen.findByText(source.address)).closest('.ant-card') as HTMLElement;
  308. const assignedCard = screen.getByText(assigned.address).closest('.ant-card') as HTMLElement;
  309. expect(within(assignedCard).queryByRole('button', { name: `删除邮箱 ${assigned.address}` })).toBeNull();
  310. await user.click(within(sourceCard).getByRole('button', { name: `删除邮箱 ${source.address}` }));
  311. const dialog = await screen.findByRole('dialog', { name: '迁移邮件并删除邮箱' });
  312. expect(within(dialog).getByText(source.address)).toBeTruthy();
  313. expect(within(dialog).getByText('5')).toBeTruthy();
  314. const destructiveButton = within(dialog).getByRole('button', { name: '迁移邮件并删除' }) as HTMLButtonElement;
  315. expect(destructiveButton.disabled).toBe(true);
  316. await user.click(within(dialog).getByRole('combobox', { name: '目标邮箱' }));
  317. const listbox = await screen.findByRole('listbox');
  318. const targetLabel = `${target.address} · 1 封邮件`;
  319. expect(within(listbox).getByRole('option', { name: targetLabel })).toBeTruthy();
  320. expect(within(listbox).queryByRole('option', { name: new RegExp(source.address) })).toBeNull();
  321. expect(within(listbox).queryByRole('option', { name: new RegExp(assigned.address) })).toBeNull();
  322. expect(within(listbox).queryByRole('option', { name: new RegExp(disabled.address) })).toBeNull();
  323. expect(within(listbox).queryByRole('option', { name: new RegExp(expired.address) })).toBeNull();
  324. await user.click(screen.getByText(targetLabel));
  325. expect(destructiveButton.disabled).toBe(true);
  326. const confirmation = within(dialog).getByRole('textbox', { name: '输入完整邮箱地址确认' });
  327. await user.type(confirmation, 'wrong@example.test');
  328. expect(within(dialog).getByText('输入的邮箱地址与待删除邮箱不一致。')).toBeTruthy();
  329. expect(destructiveButton.disabled).toBe(true);
  330. await user.clear(confirmation);
  331. await user.type(confirmation, source.address);
  332. expect(destructiveButton.disabled).toBe(false);
  333. await user.click(destructiveButton);
  334. await waitFor(() => expect(remove).toHaveBeenCalledWith(source.id, {
  335. targetMailboxId: target.id,
  336. confirmAddress: source.address
  337. }));
  338. await waitFor(() => expect(destructiveButton.classList.contains('ant-btn-loading')).toBe(true));
  339. fireEvent.click(destructiveButton);
  340. expect(remove).toHaveBeenCalledTimes(1);
  341. await act(async () => {
  342. resolveDelete({ deletedMailbox: source, targetMailbox: target, migratedMessageCount: 5 });
  343. await Promise.resolve();
  344. });
  345. expect(await screen.findByText(`邮箱已删除,已将 5 封邮件迁移到 ${target.address}。`)).toBeTruthy();
  346. await waitFor(() => expect(loadMailboxes).toHaveBeenCalledTimes(2));
  347. expect(screen.queryByRole('dialog', { name: '迁移邮件并删除邮箱' })).toBeNull();
  348. });
  349. it('blocks deletion when no other owned mailbox can receive the messages', async () => {
  350. const user = userEvent.setup();
  351. const source = mailboxFixture(1);
  352. const assigned = mailboxFixture(2, {
  353. access: { type: 'assigned', permissions: { view: true, receive: true, send: true } }
  354. });
  355. mockInboxApis([source, assigned], []);
  356. const remove = vi.spyOn(api, 'deleteInboundMailbox');
  357. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  358. renderRouter(router);
  359. const sourceCard = (await screen.findByText(source.address)).closest('.ant-card') as HTMLElement;
  360. await user.click(within(sourceCard).getByRole('button', { name: `删除邮箱 ${source.address}` }));
  361. const dialog = await screen.findByRole('dialog', { name: '迁移邮件并删除邮箱' });
  362. expect(within(dialog).getByText('没有其他可管理的邮箱。请先创建一个目标邮箱,再删除当前邮箱。')).toBeTruthy();
  363. expect((within(dialog).getByRole('button', { name: '迁移邮件并删除' }) as HTMLButtonElement).disabled).toBe(true);
  364. expect(remove).not.toHaveBeenCalled();
  365. });
  366. it('deletes an empty owned mailbox without requiring a migration target', async () => {
  367. const user = userEvent.setup();
  368. const source = mailboxFixture(1, { messageCount: 0 });
  369. mockInboxApis([source], []);
  370. const remove = vi.spyOn(api, 'deleteInboundMailbox').mockResolvedValue({
  371. deletedMailbox: source,
  372. targetMailbox: null,
  373. migratedMessageCount: 0
  374. });
  375. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  376. renderRouter(router);
  377. const sourceCard = (await screen.findByText(source.address)).closest('.ant-card') as HTMLElement;
  378. await user.click(within(sourceCard).getByRole('button', { name: `删除邮箱 ${source.address}` }));
  379. const dialog = await screen.findByRole('dialog', { name: '删除邮箱' });
  380. expect(within(dialog).getByText('此邮箱中没有邮件,可以直接停用并移除邮箱账号。')).toBeTruthy();
  381. expect(within(dialog).queryByRole('combobox', { name: '目标邮箱' })).toBeNull();
  382. const destructiveButton = within(dialog).getByRole('button', { name: '删除邮箱' }) as HTMLButtonElement;
  383. expect(destructiveButton.disabled).toBe(true);
  384. await user.type(
  385. within(dialog).getByRole('textbox', { name: '输入完整邮箱地址确认' }),
  386. source.address
  387. );
  388. expect(destructiveButton.disabled).toBe(false);
  389. await user.click(destructiveButton);
  390. await waitFor(() => expect(remove).toHaveBeenCalledWith(source.id, {
  391. targetMailboxId: null,
  392. confirmAddress: source.address
  393. }));
  394. expect(await screen.findByText('邮箱已删除')).toBeTruthy();
  395. });
  396. it('refreshes an empty mailbox deletion dialog when mail arrives before deletion', async () => {
  397. const user = userEvent.setup();
  398. const source = mailboxFixture(1, { messageCount: 0 });
  399. const refreshedSource = mailboxFixture(1, { messageCount: 1 });
  400. const target = mailboxFixture(2, { messageCount: 0 });
  401. mockInboxApis([source, target], []);
  402. const loadMailboxes = vi.mocked(api.inboundMailboxes)
  403. .mockResolvedValueOnce({ mailboxes: [source, target] })
  404. .mockResolvedValue({ mailboxes: [refreshedSource, target] });
  405. const remove = vi.spyOn(api, 'deleteInboundMailbox').mockRejectedValue(
  406. new Error('Mailbox now contains messages and requires a migration target.')
  407. );
  408. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  409. renderRouter(router);
  410. const sourceCard = (await screen.findByText(source.address)).closest('.ant-card') as HTMLElement;
  411. await user.click(within(sourceCard).getByRole('button', { name: `删除邮箱 ${source.address}` }));
  412. const emptyDialog = await screen.findByRole('dialog', { name: '删除邮箱' });
  413. await user.type(
  414. within(emptyDialog).getByRole('textbox', { name: '输入完整邮箱地址确认' }),
  415. source.address
  416. );
  417. await user.click(within(emptyDialog).getByRole('button', { name: '删除邮箱' }));
  418. await waitFor(() => expect(remove).toHaveBeenCalledWith(source.id, {
  419. targetMailboxId: null,
  420. confirmAddress: source.address
  421. }));
  422. await waitFor(() => expect(loadMailboxes).toHaveBeenCalledTimes(2));
  423. const refreshedDialog = await screen.findByRole('dialog', { name: '迁移邮件并删除邮箱' });
  424. expect(within(refreshedDialog).getByRole('combobox', { name: '目标邮箱' })).toBeTruthy();
  425. expect((within(refreshedDialog).getByRole('textbox', { name: '输入完整邮箱地址确认' }) as HTMLInputElement).value)
  426. .toBe(source.address);
  427. expect((within(refreshedDialog).getByRole('button', { name: '迁移邮件并删除' }) as HTMLButtonElement).disabled)
  428. .toBe(true);
  429. });
  430. it('groups owned and shared domains when creating a mailbox', async () => {
  431. const user = userEvent.setup();
  432. const ownedDomain = domainFixture(1);
  433. const sharedDomain = { ...domainFixture(2), userId: 2, mailboxSignupEnabled: true };
  434. mockInboxApis([], [], [ownedDomain], [ownedDomain, sharedDomain]);
  435. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  436. renderRouter(router);
  437. const createButtons = await screen.findAllByRole('button', { name: /新增收信邮箱/ });
  438. await user.click(createButtons[0]);
  439. await user.click(screen.getByRole('combobox', { name: '域名' }));
  440. expect((await screen.findAllByText('我的域名')).length).toBeGreaterThan(0);
  441. expect(screen.getAllByText('共享域名').length).toBeGreaterThan(0);
  442. expect(screen.getAllByText(`@${ownedDomain.domain}`).length).toBeGreaterThan(0);
  443. expect(screen.getAllByText(`@${sharedDomain.domain}`).length).toBeGreaterThan(0);
  444. });
  445. });
  446. function mediaQueryList(matches: boolean, media: string): MediaQueryList {
  447. return {
  448. matches,
  449. media,
  450. onchange: null,
  451. addListener: () => undefined,
  452. removeListener: () => undefined,
  453. addEventListener: () => undefined,
  454. removeEventListener: () => undefined,
  455. dispatchEvent: () => false
  456. };
  457. }
  458. function createInboxRouter(initialEntries: string[], initialIndex: number) {
  459. return createMemoryRouter([
  460. { path: '/inbox', element: <Inbox /> },
  461. { path: '/inbox/messages/:messageId', element: <Inbox /> },
  462. { path: '*', element: <div>other</div> }
  463. ], { initialEntries, initialIndex });
  464. }
  465. function renderRouter(router: ReturnType<typeof createInboxRouter>) {
  466. return render(
  467. <ConfigProvider theme={{ ...mailhubTheme, token: { ...mailhubTheme.token, motion: false } }}>
  468. <AntApp>
  469. <I18nProvider>
  470. <AppContext.Provider value={appContext}>
  471. <RouterProvider router={router} />
  472. </AppContext.Provider>
  473. </I18nProvider>
  474. </AntApp>
  475. </ConfigProvider>
  476. );
  477. }
  478. function mockInboxApis(
  479. mailboxes: InboundMailbox[],
  480. messages: InboundMessage[],
  481. domains: Domain[] = [],
  482. mailboxDomains: Domain[] = domains
  483. ) {
  484. vi.spyOn(api, 'domains').mockResolvedValue({ domains });
  485. vi.spyOn(api, 'inboundMailboxDomains').mockResolvedValue({
  486. domains: mailboxDomains.map(({ id, userId, domain, mailboxSignupEnabled }) => ({
  487. id,
  488. userId,
  489. domain,
  490. mailboxSignupEnabled
  491. }))
  492. });
  493. vi.spyOn(api, 'inboundMailboxes').mockResolvedValue({ mailboxes });
  494. vi.spyOn(api, 'inboundFolders').mockImplementation(async (mailboxId) => ({
  495. folders: [
  496. { name: 'INBOX', specialUse: null, messageCount: 0, unreadCount: 0 },
  497. { name: 'Sent', specialUse: '\\Sent', messageCount: mailboxId === 1 ? messages.length : 0, unreadCount: 0 },
  498. { name: 'Archive', specialUse: '\\Archive', messageCount: mailboxId === 2 ? messages.length : 0, unreadCount: 0 }
  499. ]
  500. }));
  501. vi.spyOn(api, 'inboundMessages').mockResolvedValue({ messages, total: messages.length, page: 1, pageSize: 25 });
  502. }
  503. function domainFixture(id: number): Domain {
  504. return {
  505. id,
  506. userId: 1,
  507. ownerUserId: 1,
  508. dnsCredentialId: null,
  509. smtpRelayId: null,
  510. domain: `example-${id}.test`,
  511. selector: 'mail',
  512. verificationToken: 'verification',
  513. dkimPublic: 'public-key',
  514. senderHost: `mail.example-${id}.test`,
  515. sendingIp: '192.0.2.10',
  516. spfExtra: '',
  517. dmarcPolicy: 'none',
  518. dmarcRua: '',
  519. catchAllAddress: '',
  520. mailboxSignupEnabled: false,
  521. status: {},
  522. createdAt: '2026-07-14T00:00:00.000Z',
  523. updatedAt: '2026-07-14T00:00:00.000Z'
  524. };
  525. }
  526. function mailboxFixture(id: number, overrides: Partial<InboundMailbox> = {}): InboundMailbox {
  527. return {
  528. id,
  529. userId: 1,
  530. domainId: id,
  531. domain: `example-${id}.test`,
  532. address: `inbox-${id}@example-${id}.test`,
  533. localPart: `inbox-${id}`,
  534. displayName: `Inbox ${id}`,
  535. aliases: [],
  536. forwardTo: [],
  537. keepForwarded: true,
  538. quotaMb: 1024,
  539. passwordSet: true,
  540. passwordRecoverable: false,
  541. status: 'active',
  542. messageCount: 2,
  543. unreadCount: 0,
  544. access: { type: 'owner', permissions: { view: true, receive: true, send: true } },
  545. createdAt: '2026-07-14T00:00:00.000Z',
  546. updatedAt: '2026-07-14T00:00:00.000Z',
  547. ...overrides
  548. };
  549. }
  550. function messageFixture(id: number, mailboxId: number, folder: string, subject: string): InboundMessage {
  551. return {
  552. id,
  553. mailboxId,
  554. userId: 1,
  555. domainId: mailboxId,
  556. domain: `example-${mailboxId}.test`,
  557. mailboxAddress: `inbox-${mailboxId}@example-${mailboxId}.test`,
  558. folder,
  559. sender: 'sender@example.test',
  560. recipients: [`inbox-${mailboxId}@example-${mailboxId}.test`],
  561. subject,
  562. messageId: `<message-${id}@example.test>`,
  563. preview: `${subject} preview`,
  564. read: true,
  565. receivedAt: '2026-07-14T00:00:00.000Z',
  566. createdAt: '2026-07-14T00:00:00.000Z',
  567. updatedAt: '2026-07-14T00:00:00.000Z',
  568. textBody: `${subject} body`,
  569. htmlBody: `<p>${subject}</p>`,
  570. rawMessage: `Subject: ${subject}`
  571. };
  572. }
  573. const runtimeConfig: RuntimeConfig = {
  574. appBaseUrl: 'https://mail.example.test',
  575. webmailSsoEnabled: true,
  576. mailHostname: 'mail.example.test',
  577. sendingIp: '192.0.2.10',
  578. defaultSpfMechanisms: '',
  579. dmarcPolicy: 'none',
  580. dmarcRua: '',
  581. registrationRequiresApproval: false,
  582. sendRequiresVerified: true,
  583. engagementTrackingEnabled: true,
  584. listUnsubscribeMailto: '',
  585. listUnsubscribeUrl: '',
  586. listUnsubscribePostEnabled: false,
  587. feedbackIdEnabled: false,
  588. reportAbuseTo: '',
  589. csaComplaintsTo: '',
  590. bounceAddress: '',
  591. bounceEnvelopeEnabled: false
  592. };
  593. const appContext: AppContextValue = {
  594. user: { id: 1, username: 'admin', email: 'admin@example.test', role: 'admin', status: 'active' },
  595. config: runtimeConfig,
  596. refreshBootstrap: vi.fn(async () => undefined),
  597. logout: vi.fn(async () => undefined)
  598. };