import { afterEach, expect, test, vi } from 'vitest'; import { addAccount, cancelPasswordLogin, checkPasswordLoginStatus, createNotificationChannel, getAccountDetails, getItems, getOrders, getReplyRules, getShippingRules, getSystemSettings, getValidOrders, logout, passwordLogin, updateReplyRule, updateAccountCookie, updateAccountLoginInfo, updateItem, updateNotificationChannel, updateShippingRule, } from './api'; afterEach(() => vi.unstubAllGlobals()); const jsonResponse = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, }); test('getOrders normalizes backend order fields', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ orders: [{ order_id: 'o1', order_status: 'shipped', quantity: '2' }], total: 1, }))); const result = await getOrders(undefined, 'all', 1, 20); expect(result.data[0]).toMatchObject({ id: 'o1', status: 'shipped', quantity: 2 }); expect(result.total).toBe(1); }); test('getValidOrders accepts wrapped responses', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ orders: [{ order_id: 'o2', order_status: 'completed', quantity: '3' }], }))); const result = await getValidOrders({ start_date: '2026-01-01', end_date: '2026-01-02' }); expect(result).toEqual([expect.objectContaining({ id: 'o2', status: 'completed', quantity: 3 })]); }); test('getItems normalizes multi-spec flags from backend values', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{ cookie_id: 'cookie-1', item_id: 'item-1', item_title: '普通商品', is_multi_spec: '0', multi_quantity_delivery: 0, }, { cookie_id: 'cookie-1', item_id: 'item-2', item_title: '多规格商品', is_multi_spec: '1', multi_quantity_delivery: 1, }]))); const items = await getItems(); expect(items[0]).toMatchObject({ id: 'cookie-1-item-1', is_multi_spec: false, is_multi_qty_ship: false, multi_quantity_delivery: false, }); expect(items[1]).toMatchObject({ id: 'cookie-1-item-2', is_multi_spec: true, is_multi_qty_ship: true, multi_quantity_delivery: true, }); }); test('getSystemSettings normalizes numeric renewal retention', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse({ ai_model: 'qwen-plus', renewal_log_retention_days: 'invalid', }))); const settings = await getSystemSettings(); expect(settings.ai_model).toBe('qwen-plus'); expect(settings.renewal_log_retention_days).toBe(10); }); test('logout calls backend session invalidation route', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await logout(); expect(fetchMock).toHaveBeenCalledWith('/logout', expect.objectContaining({ method: 'POST', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({}); }); test('account cookie APIs include login_method when provided', async () => { const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(jsonResponse({ success: true }))); vi.stubGlobal('fetch', fetchMock); await addAccount('acc1', 'unb=acc1', 'qr_scan'); expect(fetchMock).toHaveBeenCalledWith('/cookies', expect.objectContaining({ method: 'POST', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ id: 'acc1', value: 'unb=acc1', login_method: 'qr_scan', }); await updateAccountCookie('acc1', 'unb=acc1; x=1', 'qr_scan'); expect(fetchMock).toHaveBeenCalledWith('/cookies/acc1', expect.objectContaining({ method: 'PUT', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ id: 'acc1', value: 'unb=acc1; x=1', login_method: 'qr_scan', }); }); test('getAccountDetails normalizes show_browser and never exposes password', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{ id: 'acc1', enabled: true, auto_confirm: true, remark: '主账号', pause_duration: 0, username: 'login-user', show_browser: '1', login_password: 'should-not-leak', }]))); const accounts = await getAccountDetails(); expect(accounts[0]).toMatchObject({ id: 'acc1', username: 'login-user', show_browser: true, login_password: '', }); }); test('updateAccountLoginInfo sends exactly provided fields', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await updateAccountLoginInfo('acc1', { username: 'login-user', show_browser: false }); expect(fetchMock).toHaveBeenCalledWith('/cookies/acc1/login-info', expect.objectContaining({ method: 'PUT', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ username: 'login-user', show_browser: false, }); }); test('updateAccountLoginInfo can request explicit password clearing', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await updateAccountLoginInfo('acc1', { username: 'login-user', clear_password: true, show_browser: false }); expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ username: 'login-user', clear_password: true, show_browser: false, }); }); test('updateItem sends only the fields selected by the editor', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await updateItem('acc1', 'item1', { item_title: '改名商品' }); expect(fetchMock).toHaveBeenCalledWith('/items/acc1/item1', expect.objectContaining({ method: 'PUT', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ item_title: '改名商品', }); }); test('password login service uses upstream-compatible routes', async () => { const fetchMock = vi.fn() .mockResolvedValueOnce(jsonResponse({ success: true, session_id: 'sid', status: 'processing' })) .mockResolvedValueOnce(jsonResponse({ status: 'success', account_id: 'acc1', cookie_count: 2 })) .mockResolvedValueOnce(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await passwordLogin({ account_id: 'acc1', account: 'u', password: 'p' }); expect(fetchMock).toHaveBeenNthCalledWith(1, '/password-login', expect.objectContaining({ method: 'POST', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ account_id: 'acc1', account: 'u', password: 'p', }); const status = await checkPasswordLoginStatus('sid'); expect(status.status).toBe('success'); expect(fetchMock).toHaveBeenNthCalledWith(2, '/password-login/check/sid', expect.objectContaining({ method: 'GET' })); await cancelPasswordLogin('sid'); expect(fetchMock).toHaveBeenNthCalledWith(3, '/password-login/cancel/sid', expect.objectContaining({ method: 'DELETE' })); }); test('getShippingRules exposes buyer reviewed gift rules as automation rules', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse([{ id: 12, cookie_id: 'cookie-1', item_id: 'item-1', item_title: '测试商品', name: '评价后发送赠品 - 测试商品', trigger_type: 'buyer_reviewed', enabled: true, priority: 90, config_json: '{}', actions: [{ id: 33, action_type: 'send_card', card_id: 7, card_name: '赠品库存', delivery_count: 1, config_json: '{"spec_name":"套餐","spec_value":"赠品"}', enabled: true, sort_order: 1, }], }]))); const rules = await getShippingRules(); expect(rules[0]).toMatchObject({ id: '12', trigger_type: 'buyer_reviewed', card_group_id: 7, card_group_name: '赠品库存', }); expect(rules[0].variants[0]).toMatchObject({ spec_name: '套餐', spec_value: '赠品', card_id: 7, }); }); test('getReplyRules labels keyword matching according to engine contains behavior', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse([{ keyword: '发货', reply: '马上安排', type: 'image', image_url: 'https://img.example/reply.png', }])); vi.stubGlobal('fetch', fetchMock); const rules = await getReplyRules('acc1'); expect(fetchMock).toHaveBeenCalledWith('/keywords-with-type/acc1', expect.objectContaining({ method: 'GET' })); expect(rules[0]).toMatchObject({ keyword: '发货', reply_content: '马上安排', match_type: 'fuzzy', type: 'image', image_url: 'https://img.example/reply.png', }); }); test('updateReplyRule preserves keyword image metadata when saving text edits', async () => { const fetchMock = vi.fn() .mockResolvedValueOnce(jsonResponse([ { keyword: '图', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/a.png' }, { keyword: '发货', reply: '马上安排', item_id: 'item-1', type: 'text', image_url: '' }, ])) .mockResolvedValueOnce(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await updateReplyRule({ id: '1', keyword: '发货', reply_content: '稍后安排' }, 'acc1'); expect(fetchMock).toHaveBeenNthCalledWith(1, '/keywords-with-type/acc1', expect.objectContaining({ method: 'GET' })); expect(fetchMock).toHaveBeenNthCalledWith(2, '/keywords-with-item-id/acc1', expect.objectContaining({ method: 'POST', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ keywords: [ { keyword: '图', reply: '', item_id: '', type: 'image', image_url: 'https://img.example/a.png' }, { keyword: '发货', reply: '稍后安排', item_id: 'item-1', type: 'text', image_url: '' }, ], }); }); test('createNotificationChannel persists email recipient as to_email config', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await createNotificationChannel({ name: '邮件通知', type: 'email', config: { smtp_server: 'smtp.example.com', smtp_port: 587, smtp_user: 'from@example.com', smtp_password: 'secret', to_email: 'to@example.com', }, }); const body = JSON.parse(fetchMock.mock.calls[0][1].body); expect(body.type).toBe('email'); expect(JSON.parse(body.config)).toMatchObject({ to_email: 'to@example.com', }); expect(JSON.parse(body.config)).not.toHaveProperty('from'); }); test('createNotificationChannel allows email channel to rely on system SMTP settings', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await createNotificationChannel({ name: '邮件通知', type: 'email', config: { to_email: 'to@example.com', }, }); const body = JSON.parse(fetchMock.mock.calls[0][1].body); expect(body.type).toBe('email'); expect(JSON.parse(body.config)).toEqual({ to_email: 'to@example.com', }); }); test('updateNotificationChannel supports partial enabled updates', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); vi.stubGlobal('fetch', fetchMock); await updateNotificationChannel('7', { enabled: false }); expect(fetchMock).toHaveBeenCalledWith('/notification-channels/7', expect.objectContaining({ method: 'PUT', credentials: 'include', })); expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ enabled: false, }); }); test('updateShippingRule posts buyer reviewed gift payload to automation-rules', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 1 })); vi.stubGlobal('fetch', fetchMock); await updateShippingRule({ cookie_id: 'cookie-1', item_id: 'item-1', trigger_type: 'buyer_reviewed', enabled: true, variants: [{ spec_name: '', spec_value: '', card_id: 7, delivery_count: 1, enabled: true, }], }); expect(fetchMock).toHaveBeenCalledWith('/automation-rules', expect.objectContaining({ method: 'POST', credentials: 'include', })); const body = JSON.parse(fetchMock.mock.calls[0][1].body); expect(body).toMatchObject({ cookie_id: 'cookie-1', item_id: 'item-1', name: '评价后发送赠品 - item-1', trigger_type: 'buyer_reviewed', }); expect(body.actions).toEqual([ expect.objectContaining({ action_type: 'send_card', card_id: 7, sort_order: 1, }), ]); }); test('updateShippingRule posts every matching card action before confirm shipment', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 3 })); vi.stubGlobal('fetch', fetchMock); await updateShippingRule({ cookie_id: 'cookie-1', item_id: 'item-1', trigger_type: 'order_paid', enabled: true, variants: [ { spec_name: '套餐', spec_value: '30天', card_id: 8, delivery_count: 1, enabled: true, }, { spec_name: '套餐', spec_value: '30天', card_id: 9, delivery_count: 2, enabled: true, }, ], }); const body = JSON.parse(fetchMock.mock.calls[0][1].body); expect(body.trigger_type).toBe('order_paid'); expect(body.actions).toEqual([ expect.objectContaining({ action_type: 'send_card', card_id: 8, sort_order: 1, }), expect.objectContaining({ action_type: 'send_card', card_id: 9, delivery_count: 2, sort_order: 2, }), expect.objectContaining({ action_type: 'confirm_shipment', sort_order: 3, }), ]); expect(JSON.parse(body.actions[0].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天' }); expect(JSON.parse(body.actions[1].config_json)).toEqual({ spec_name: '套餐', spec_value: '30天' }); }); test('updateShippingRule posts review request text action without card requirement', async () => { const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, id: 2 })); vi.stubGlobal('fetch', fetchMock); await updateShippingRule({ cookie_id: 'cookie-1', item_id: 'item-1', trigger_type: 'review_missing_timeout', enabled: true, config_json: '{"after_shipped_hours":48,"max_attempts":2}', actions: [{ action_type: 'send_text', message_template: '亲,方便的话麻烦给个评价~', enabled: true, sort_order: 1, }], }); const body = JSON.parse(fetchMock.mock.calls[0][1].body); expect(body.trigger_type).toBe('review_missing_timeout'); expect(body.actions).toEqual([ expect.objectContaining({ action_type: 'send_text', card_id: 0, message_template: '亲,方便的话麻烦给个评价~', }), ]); });