File size: 12,295 Bytes
6822ee4
 
 
 
 
 
 
 
 
 
 
b207060
747e1c6
 
6822ee4
 
 
747e1c6
 
 
 
6822ee4
 
 
 
 
 
 
 
 
 
747e1c6
6822ee4
 
 
 
 
 
747e1c6
 
6822ee4
 
b207060
6822ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
b207060
747e1c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6822ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ccc0de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6822ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b207060
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6822ee4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'
import express from 'express'
import type { AddressInfo } from 'node:net'
import type { Server } from 'node:http'
import type { Request, Response, NextFunction } from 'express'

const getMock = vi.fn()
const deleteMock = vi.fn()
const setConfirmedMock = vi.fn()
const createExpenseMock = vi.fn()
const splitMock = vi.fn()
const applyMatchMock = vi.fn()
const listByStatusMock = vi.fn()
const countsByStatusMock = vi.fn()

vi.mock('../loader.js', () => ({
  container: {
    slipQueueService: {
      get: getMock, delete: deleteMock, setConfirmed: setConfirmedMock, applyMatch: applyMatchMock,
      listByStatus: listByStatusMock, countsByStatus: countsByStatusMock,
    },
    expenseService: { create: createExpenseMock },
    billShareService: { split: splitMock },
  },
}))

describe('slip-queue.controller', () => {
  let server: Server
  let baseUrl: string

  beforeAll(async () => {
    const { confirmSlipQueueItem, deleteSlipQueueItem, applyMatchSlipQueueItem, getSlipQueue, getSlipQueueCounts } = await import('./slip-queue.controller.js')
    const app = express()
    app.use(express.json())
    app.use((req: Request, _res: Response, next: NextFunction) => {
      ;(req as Request & { auth: { tenantId: string } }).auth = { tenantId: 'tenant-1' }
      next()
    })
    app.get('/slip-queue', (req, res) => { void getSlipQueue(req, res) })
    app.get('/slip-queue/counts', (req, res) => { void getSlipQueueCounts(req, res) })
    app.post('/slip-queue/:id/confirm', (req, res) => { void confirmSlipQueueItem(req, res) })
    app.delete('/slip-queue/:id', (req, res) => { void deleteSlipQueueItem(req, res) })
    app.post('/slip-queue/:id/apply-match', (req, res) => { void applyMatchSlipQueueItem(req, res) })
    server = app.listen(0)
    await new Promise<void>((resolve) => server.once('listening', resolve))
    const { port } = server.address() as AddressInfo
    baseUrl = `http://localhost:${port}`
  })

  afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))

  beforeEach(() => {
    getMock.mockReset()
    deleteMock.mockReset()
    setConfirmedMock.mockReset()
    createExpenseMock.mockReset()
    splitMock.mockReset()
    applyMatchMock.mockReset()
    listByStatusMock.mockReset()
    countsByStatusMock.mockReset()
  })

  describe('getSlipQueue', () => {
    it('400s when status is missing', async () => {
      const res = await fetch(`${baseUrl}/slip-queue`)
      expect(res.status).toBe(400)
    })

    it('400s for an invalid status value', async () => {
      const res = await fetch(`${baseUrl}/slip-queue?status=bogus`)
      expect(res.status).toBe(400)
    })

    it('passes status/limit/cursor through to the service and returns its page as-is', async () => {
      listByStatusMock.mockResolvedValue({ items: [], hasMore: true })
      const res = await fetch(`${baseUrl}/slip-queue?status=needs_review&limit=10&after_created_at=2026-08-01T00:00:00.000Z&after_id=abc`)
      expect(res.status).toBe(200)
      expect(await res.json()).toEqual({ items: [], hasMore: true })
      expect(listByStatusMock).toHaveBeenCalledWith('tenant-1', 'needs_review', {
        limit: 10, after: { createdAt: '2026-08-01T00:00:00.000Z', id: 'abc' },
      })
    })

    it('defaults to a page size of 30 with no cursor when neither is supplied', async () => {
      listByStatusMock.mockResolvedValue({ items: [], hasMore: false })
      await fetch(`${baseUrl}/slip-queue?status=pending`)
      expect(listByStatusMock).toHaveBeenCalledWith('tenant-1', 'pending', { limit: 30, after: undefined })
    })

    it('caps limit at 100', async () => {
      listByStatusMock.mockResolvedValue({ items: [], hasMore: false })
      await fetch(`${baseUrl}/slip-queue?status=pending&limit=9999`)
      expect(listByStatusMock).toHaveBeenCalledWith('tenant-1', 'pending', { limit: 100, after: undefined })
    })
  })

  describe('getSlipQueueCounts', () => {
    it('returns the service\'s per-status counts', async () => {
      const counts = { pending: 1, processing: 0, success: 2, needs_review: 3, failed: 0, confirmed: 10 }
      countsByStatusMock.mockResolvedValue(counts)
      const res = await fetch(`${baseUrl}/slip-queue/counts`)
      expect(res.status).toBe(200)
      expect(await res.json()).toEqual(counts)
    })
  })

  describe('confirmSlipQueueItem (I8)', () => {
    it('passes slip_image_key and reference from the parsed slip into expenseService.create', async () => {
      getMock.mockResolvedValue({
        id: 'slip-1',
        status: 'success',
        image_key: 'slip-queue/slip-1.jpg',
        parsed_result: {
          amount: 250, currency: 'THB', date: '2026-08-01', merchant: 'Cafe X',
          category: 'food', confidence: 0.9, raw_description: 'coffee', reference: 'TXN-777',
        },
      })
      createExpenseMock.mockResolvedValue({ id: 'exp-1', amount: 250 })
      setConfirmedMock.mockResolvedValue({ id: 'slip-1', status: 'confirmed' })

      const res = await fetch(`${baseUrl}/slip-queue/slip-1/confirm`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ category_id: 'cat-1' }),
      })

      expect(res.status).toBe(201)
      expect(createExpenseMock).toHaveBeenCalledWith('tenant-1', expect.objectContaining({
        slip_image_key: 'slip-queue/slip-1.jpg',
        reference: 'TXN-777',
      }))
      expect(setConfirmedMock).toHaveBeenCalledWith('tenant-1', 'slip-1')
    })

    it('passes null slip_image_key/reference through when the slip has none', async () => {
      getMock.mockResolvedValue({
        id: 'slip-2',
        status: 'success',
        image_key: null,
        parsed_result: {
          amount: 80, currency: 'THB', date: '2026-08-01', merchant: null,
          category: 'other', confidence: 0.7, raw_description: 'cash note', reference: null,
        },
      })
      createExpenseMock.mockResolvedValue({ id: 'exp-2', amount: 80 })
      setConfirmedMock.mockResolvedValue({ id: 'slip-2', status: 'confirmed' })

      const res = await fetch(`${baseUrl}/slip-queue/slip-2/confirm`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ category_id: 'cat-1' }),
      })

      expect(res.status).toBe(201)
      expect(createExpenseMock).toHaveBeenCalledWith('tenant-1', expect.objectContaining({
        slip_image_key: null,
        reference: null,
      }))
    })

    it('surfaces the duplicate-guard error status/message instead of a generic 500', async () => {
      getMock.mockResolvedValue({
        id: 'slip-3',
        status: 'success',
        image_key: 'slip-queue/slip-3.jpg',
        parsed_result: {
          amount: 88.5, currency: 'THB', date: '2026-06-06', merchant: 'Line man',
          category: 'food', confidence: 0.9, raw_description: '', reference: 'TXN-DUP',
        },
      })
      createExpenseMock.mockRejectedValue(
        Object.assign(new Error('This looks like a duplicate of an existing expense from 2026-06-06 (THB 88.5)'), { status: 409 }),
      )

      const res = await fetch(`${baseUrl}/slip-queue/slip-3/confirm`, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ category_id: 'cat-1' }),
      })

      expect(res.status).toBe(409)
      const body = await res.json() as { error?: string }
      expect(body.error).toContain('duplicate of an existing expense')
      expect(setConfirmedMock).not.toHaveBeenCalled()
    })
  })

  describe('deleteSlipQueueItem (I5)', () => {
    it('rejects deleting a confirmed slip with a 400, without calling delete', async () => {
      getMock.mockResolvedValue({ id: 'slip-3', status: 'confirmed', image_key: 'slip-queue/slip-3.jpg' })

      const res = await fetch(`${baseUrl}/slip-queue/slip-3`, { method: 'DELETE' })

      expect(res.status).toBe(400)
      const body = await res.json() as { error: string }
      expect(body.error).toMatch(/confirmed/i)
      expect(deleteMock).not.toHaveBeenCalled()
    })

    it('allows deleting a non-confirmed (e.g. failed) slip', async () => {
      getMock.mockResolvedValue({ id: 'slip-4', status: 'failed', image_key: null })
      deleteMock.mockResolvedValue(undefined)

      const res = await fetch(`${baseUrl}/slip-queue/slip-4`, { method: 'DELETE' })

      expect(res.status).toBe(204)
      expect(deleteMock).toHaveBeenCalledWith('tenant-1', 'slip-4')
    })

    it('returns 404 when the slip does not exist', async () => {
      getMock.mockResolvedValue(null)

      const res = await fetch(`${baseUrl}/slip-queue/missing`, { method: 'DELETE' })

      expect(res.status).toBe(404)
      expect(deleteMock).not.toHaveBeenCalled()
    })
  })

  describe('applyMatchSlipQueueItem (slip-queue-match-review-ui)', () => {
    it('uses the slip\'s own stored match when no override body is sent ("use matched template")', async () => {
      getMock.mockResolvedValue({
        id: 'slip-nr-1', status: 'needs_review',
        match_confidence: 0.75, match_template_id: 'tpl-1',
        parsed_result: { amount: 100, currency: 'THB', date: null, merchant: 'X', category: 'food', confidence: 0.75, raw_description: 'r', reference: null },
      })
      applyMatchMock.mockResolvedValue({ id: 'slip-nr-1', status: 'success' })

      const res = await fetch(`${baseUrl}/slip-queue/slip-nr-1/apply-match`, {
        method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({}),
      })

      expect(res.status).toBe(200)
      expect(applyMatchMock).toHaveBeenCalledWith('tenant-1', 'slip-nr-1', {
        parsed_result: { amount: 100, currency: 'THB', date: null, merchant: 'X', category: 'food', confidence: 0.75, raw_description: 'r', reference: null },
        match_confidence: 0.75,
        match_template_id: 'tpl-1',
      })
    })

    it('uses the override body when a freshly-taught template result is sent ("set up a new template")', async () => {
      getMock.mockResolvedValue({ id: 'slip-nr-2', status: 'needs_review', match_confidence: 0, match_template_id: null, parsed_result: null })
      applyMatchMock.mockResolvedValue({ id: 'slip-nr-2', status: 'success' })

      const override = {
        parsed_result: { amount: 42, currency: 'THB', date: null, merchant: 'New', category: 'food', confidence: 1, raw_description: 'r', reference: null, template_id: 'tpl-new' },
        match_confidence: 1,
        match_template_id: 'tpl-new',
      }
      const res = await fetch(`${baseUrl}/slip-queue/slip-nr-2/apply-match`, {
        method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(override),
      })

      expect(res.status).toBe(200)
      expect(applyMatchMock).toHaveBeenCalledWith('tenant-1', 'slip-nr-2', override)
    })

    it('rejects with 400 when the slip has no stored match and no override is sent', async () => {
      getMock.mockResolvedValue({ id: 'slip-nr-3', status: 'needs_review', match_confidence: 0, match_template_id: null, parsed_result: null })

      const res = await fetch(`${baseUrl}/slip-queue/slip-nr-3/apply-match`, {
        method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({}),
      })

      expect(res.status).toBe(400)
      expect(applyMatchMock).not.toHaveBeenCalled()
    })

    it('rejects with 400 when the slip is not needs_review', async () => {
      getMock.mockResolvedValue({ id: 'slip-nr-4', status: 'success', match_confidence: 0.9, match_template_id: 'tpl-1' })

      const res = await fetch(`${baseUrl}/slip-queue/slip-nr-4/apply-match`, {
        method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({}),
      })

      expect(res.status).toBe(400)
      expect(applyMatchMock).not.toHaveBeenCalled()
    })

    it('returns 404 when the slip does not exist', async () => {
      getMock.mockResolvedValue(null)

      const res = await fetch(`${baseUrl}/slip-queue/missing/apply-match`, {
        method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({}),
      })

      expect(res.status).toBe(404)
      expect(applyMatchMock).not.toHaveBeenCalled()
    })
  })
})