Inbox UX overhaul + cross-currency supplier-invoice fixes (#444)
* feat(kpi): expense mix and top suppliers charts Replace the single monthly-trend chart with two additional compact visuals on /kpi: expense composition donut (BAS class 4-7) and top suppliers bar (supplier_invoices sum_sek over the fiscal period). KPIReport gains expenseComposition and topSuppliers fields, computed from the trial balance and supplier_invoices rows already fetched in the API. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(nav): swap Deadlines sidebar slot for Dokumentinkorg Sidebar main-menu slot now points to the invoice-inbox extension. The /deadlines page stays accessible via dashboard widgets and direct links — only the prominent nav entry changes. Most users open gnubok to act on incoming documents, not to read tax deadlines. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(supplier-invoices): cross-currency totals, FX residual, review SEK display Five fixes around foreign-currency supplier invoices: - Form layout: move Valuta / Växelkurs / Reverse charge from collapsed "Övrigt" into a visible row above the line-item table. Auto-fetch the Riksbanken rate when switching to a non-SEK currency; never clobber a user-typed rate; clear it when switching back to SEK. - Form submit: reset() the form on successful submit so the useUnsavedChanges hook detaches its beforeunload listener before the router.push, killing the "Are you sure you want to leave?" prompt that fired during Turbopack-mediated navigations. - BankTransactionPicker: drop the strict currency filter that hid every SEK transaction when the invoice was in EUR/USD. Cross-currency rows fall to the bottom with an "Annan valuta" hint instead of producing a meaningless numeric diff. - match-supplier-invoice route: when the bank transaction currency differs from the invoice currency, compute the FX diff against the AP-booked SEK and pass it to createSupplierInvoicePaymentEntry so 7960/3960 catches the residual instead of leaving a permanent stub on 2440. Fix also covers the "EUR transaction paying a SEK invoice" case that the first iteration missed. - Review dialog: buildJournalPreview now multiplies amounts by the exchange rate so the "Verifikation som bokförs" table shows the actual SEK numbers that hit the DB, not the EUR magnitudes labelled with no unit. Header gains an "(i SEK)" hint when foreign currency. Test coverage for the FX residual path covers SEK-SEK (no diff), SEK-into-EUR-invoice (loss), SEK-into-EUR-invoice (gain), foreign-tx- into-SEK-invoice, and the no-rate fallback. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(inbox): rate limits, multi-file UX, onboarding, retry, supplier autolink Big workspace pass on /e/general/invoice-inbox. Highlights: Backend - New table inbox_rate_counters + RPC check_and_increment_inbox_quota. Postgres-backed (no Upstash dep) per-company limit: 30/min, 500/day. Applied at /upload, /inbound, and /items/:id/retry-extraction. - POST /items/:id/retry-extraction — re-runs the deterministic extractor on a stored document when the previous attempt errored. - POST /items/:id/match-supplier — links a freshly-created supplier back to the inbox item so the next action prefills correctly. - POST /api/transactions/create-from-document — creates an uncategorized manual transaction from an inbox item for the "I have a receipt, no bank transaction" case. The user categorizes through the normal flow. - /inbound caps email at 20 attachments/email; truncated count goes to processing_history as AttachmentsTruncated. Rate-limit drops emit RateLimitedDropped and return 200 so Resend doesn't retry. - attach-document side effect: when the document came from an inbox item, the inbox row's matched_transaction_id is updated so the UI can flip it to "Kopplad till transaktion" without a round-trip. New migration: re-introduces matched_transaction_id on invoice_inbox_items as a plain FK (the AI metadata that the previous migration stripped doesn't come back). Workspace UI - Onboarding card replaces the thin empty-state with a 3-step checkmark guide (Aktivera adress → Ladda upp → Matcha eller bokför). Auto-hides when all three steps are done; localStorage-backed dismiss. Beta badge + link to gnubok.se/priser. - Responsive layout: 3-pane at lg, 2-pane at md, master-detail toggle on phone (list xor detail with a back button). - Filter pills (Alla / Behöver åtgärd / Bearbetade / Fel) + search input above the list — client-side over the existing items list. - Multi-file upload queue with "Laddar X av N…" progress counter on the button. Sequential to avoid hammering pdfjs. Selection stays put during a batch (only single-file drops auto-jump the detail pane). - Bulk select + delete with sticky action bar. Items linked to a supplier invoice are skipped with a count toast. - Retry button in the FieldsRail error branch. - "Skapa transaktion från underlag" CTA in the match dialog when no unmatched bank transactions exist. Prefills date/amount/description from the extracted data; user picks the sign. - "Skapa leverantör" inline CTA when the extractor caught a supplier name with no match against existing suppliers. POSTs /api/suppliers with the extracted fields, then auto-links via /items/:id/match-supplier. - Matched-state CTA renamed to "Bokför transaktionen" with link to /transactions?highlight=<id> so the categorize panel auto-opens. Tests - lib/rate-limits/__tests__/inbox.test.ts — RPC wrapper happy/error/scope - app/api/transactions/create-from-document/__tests__/route.test.ts — auth, validation, 404/409/200/500, inbox-link failure tolerated - extensions/general/invoice-inbox/__tests__/retry-extraction.test.ts — auth, rate limit, 404, 409, 400 no-doc, success, extraction failure - attach-document tests extend coverage to the new inbox-link side effect (both success and best-effort failure paths) - inbound-webhook test mocks the rate-limit module so the queued-mock sequence in each existing test doesn't have to know about it CLAUDE.md gains a row for lib/rate-limits/ so the new helper is discoverable. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(transactions): paperclip indicator and highlight-row param Close the feedback loop after a user attaches a receipt to a transaction from the inbox: the row in /transactions now shows a paperclip icon when transaction.document_id is set, with a click handler that fetches a signed download URL and opens the document in a new tab. Works for both uncategorized and history views. When the inbox sends a user to /transactions?highlight=<id>, the page now scrolls that row into view and auto-opens the categorize panel if the transaction is still uncategorized. Behind a double-rAF so the row DOM exists when scrollIntoView fires. QuickReviewDialog no longer prompts to upload underlag when the transaction already has a doc attached (which it does after the inbox match flow). Shows "Underlag bifogat — Visa" instead, opening the existing doc in a new tab. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(pr-444): address review feedback (Greptile + compliance bots) Migration rules - New migration 20260512092423: adds updated_at trigger on inbox_rate_counters (CLAUDE.md rule 2) and explicit USING (false) RLS policies for the four DML verbs to make the SECURITY DEFINER-only intent explicit (rule 1). - New pg-real test inbox-rate-limit.pg.test.ts covering happy path, minute-cap rejection, day-cap rejection, per-company isolation, and the updated_at trigger firing. CLAUDE.md mandates *.pg.test.ts for every new RPC because mocks pass on broken PL/pgSQL. Bugs - Stale exchange rate on currency switch (Greptile P1) — userTouchedRateRef was scoped per session, not per currency. Switching EUR (with a hand-edited rate) → USD kept the EUR rate. Now tracks the last fetched currency in a ref and resets the touched flag on currency change while still honoring manual edits within a single currency. - topSuppliersResult.error silently swallowed (Greptile P2) — failed queries used to render an empty chart matching the no-data state. Logged now. - Currency from extracted_data not validated (GDPR Art.25(2), OWASP V4.5, Swedish compliance bot) — extracted PDF currency was inserted into transactions.currency without sanitisation. Allowlisted against the six supported ISO 4217 codes; coerce to SEK otherwise. - Idempotency gap on create-from-document (OWASP V2.3) — two concurrent POSTs with the same inbox_item_id could each pass the matched_transaction_id IS NULL read and insert duplicate transactions. UPDATE now includes .is('matched_transaction_id', null) as an optimistic-lock release and returns 409 with an orphan-transaction rollback when the predicate doesn't match. - FX residual on cash-method match path (Swedish compliance bot) — createSupplierInvoiceCashEntry has no exchange_rate_difference path, so a cross-currency match would silently leave a 1930 reconciliation gap. Added a guard that returns MATCH_SI_CASH_FX_UNSUPPORTED (400) before the JE is created. Users on cash method can switch to accrual or book the FX diff manually. Design system - gap-y-1.5 / gap-1.5 in KPIExpenseMixChart — replaced with gap-y-2 / gap-2 (CLAUDE.md design tokens; 2.5/1.5/5/hardcoded pixels are forbidden spacing values). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(migrations): rename to match applied versions The mcp__plugin_supabase_supabase__apply_migration tool stamps its own timestamp when it applies a migration to the live project, so the version recorded in supabase_migrations.schema_migrations differs from my local generation-time filenames. Renaming the local files so a production CD run sees the migrations as already-applied (matching versions) instead of trying to re-apply them — which would fail for the trigger/RLS migration (CREATE TRIGGER and CREATE POLICY don't support IF NOT EXISTS). Follows the pattern from d854efcd ("chore(migration): rename to match applied version"). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(create-from-document): scope orphan rollback DELETE by company_id Defence in depth on the inbox-link race rollback. newTx.id is a fresh UUID from a company-scoped insert two statements above, so the existing single-key DELETE is already safe, but adding .eq('company_id', companyId) makes the cross-company invariant explicit on every write — addresses the OWASP ASVS V2.3 finding from the compliance swarm on PR #444. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(nav): mark Dokumentinkorg with Beta badge Same signal we use for Löner and Anställda — the inbox flow (AI extraction, supplier autolink, manual transaction creation) is in end-to-end customer testing. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
8f15f98687
commit
17c67fece0
@@ -19,6 +19,12 @@ vi.mock('@supabase/supabase-js', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
// Rate limiter is a thin RPC wrapper; bypass it so the queued-mock sequence
|
||||
// in each test doesn't have to account for the extra Supabase call.
|
||||
vi.mock('@/lib/rate-limits/inbox', () => ({
|
||||
checkInboxUploadRateLimit: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
import { verifyInboundWebhook, fetchReceivingEmail, fetchInboundAttachment } from '@/extensions/general/invoice-inbox/lib/resend-inbound'
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { invoiceInboxExtension } from '@/extensions/general/invoice-inbox'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
|
||||
vi.mock('@/extensions/general/invoice-inbox/lib/extract-invoice-fields', () => ({
|
||||
extractInvoiceFields: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/rate-limits/inbox', () => ({
|
||||
checkInboxUploadRateLimit: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
import { extractInvoiceFields } from '@/extensions/general/invoice-inbox/lib/extract-invoice-fields'
|
||||
import { checkInboxUploadRateLimit } from '@/lib/rate-limits/inbox'
|
||||
|
||||
function findRoute(method: string, path: string) {
|
||||
return invoiceInboxExtension.apiRoutes!.find(
|
||||
(r) => r.method === method && r.path === path,
|
||||
)!
|
||||
}
|
||||
|
||||
const retryRoute = findRoute('POST', '/items/:id/retry-extraction')
|
||||
|
||||
function buildCtx(supabase: unknown): ExtensionContext {
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'invoice-inbox',
|
||||
supabase: supabase as ExtensionContext['supabase'],
|
||||
emit: vi.fn(),
|
||||
settings: { get: vi.fn(), set: vi.fn() },
|
||||
storage: { from: vi.fn() } as unknown as ExtensionContext['storage'],
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as unknown as ExtensionContext['log'],
|
||||
services: {},
|
||||
} as ExtensionContext
|
||||
}
|
||||
|
||||
function makeReq() {
|
||||
return createMockRequest('/items/item-1/retry-extraction', {
|
||||
method: 'POST',
|
||||
searchParams: { _id: 'item-1' },
|
||||
})
|
||||
}
|
||||
|
||||
const EXTRACTION_SUCCESS = {
|
||||
data: {
|
||||
supplier: { name: 'Acme AB', orgNumber: null, vatNumber: null, address: null, bankgiro: null, plusgiro: null },
|
||||
invoice: { invoiceNumber: 'F-1', invoiceDate: '2026-05-01', dueDate: null, paymentReference: null, currency: 'SEK' },
|
||||
lineItems: [],
|
||||
totals: { subtotal: 100, vatAmount: 25, total: 125 },
|
||||
vatBreakdown: [],
|
||||
confidence: 1,
|
||||
},
|
||||
rawText: 'mock',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(checkInboxUploadRateLimit).mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('POST /items/:id/retry-extraction', () => {
|
||||
it('returns 401 when no context', async () => {
|
||||
const res = await retryRoute.handler(makeReq(), undefined)
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 429 when the per-company rate limit is exceeded', async () => {
|
||||
vi.mocked(checkInboxUploadRateLimit).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
scope: 'minute',
|
||||
retryAfterSec: 30,
|
||||
})
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
const res = await retryRoute.handler(makeReq(), buildCtx(supabase))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(429)
|
||||
expect(body.error).toMatch(/för många/i)
|
||||
expect(res.headers.get('Retry-After')).toBe('30')
|
||||
})
|
||||
|
||||
it('returns 404 when the inbox item is missing', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: null }) // item lookup
|
||||
const res = await retryRoute.handler(makeReq(), buildCtx(supabase))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 409 when already booked as supplier invoice', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: { id: 'item-1', document_id: 'doc-1', correlation_id: null, created_supplier_invoice_id: 'si-1' },
|
||||
error: null,
|
||||
})
|
||||
const res = await retryRoute.handler(makeReq(), buildCtx(supabase))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toMatch(/redan bokfört/i)
|
||||
})
|
||||
|
||||
it('returns 400 when the item has no attached document', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: { id: 'item-1', document_id: null, correlation_id: null, created_supplier_invoice_id: null },
|
||||
error: null,
|
||||
})
|
||||
const res = await retryRoute.handler(makeReq(), buildCtx(supabase))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toMatch(/Ingen bilaga/i)
|
||||
})
|
||||
|
||||
it('returns 200 with re-extracted data on the happy path', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: { id: 'item-1', document_id: 'doc-1', correlation_id: null, created_supplier_invoice_id: null },
|
||||
error: null,
|
||||
})
|
||||
enqueue({
|
||||
data: { storage_path: 'path/to.pdf', mime_type: 'application/pdf', file_name: 'invoice.pdf' },
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: null, error: null }) // inbox update on success
|
||||
|
||||
supabase.storage.from = vi.fn().mockReturnValue({
|
||||
download: vi.fn().mockResolvedValue({
|
||||
data: new Blob([new Uint8Array([1, 2, 3])], { type: 'application/pdf' }),
|
||||
error: null,
|
||||
}),
|
||||
})
|
||||
|
||||
vi.mocked(extractInvoiceFields).mockResolvedValueOnce(EXTRACTION_SUCCESS as never)
|
||||
|
||||
const res = await retryRoute.handler(makeReq(), buildCtx(supabase))
|
||||
const { status, body } = await parseJsonResponse<{ data: { extracted_data: { totals: { total: number } } } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.extracted_data.totals.total).toBe(125)
|
||||
})
|
||||
|
||||
it('marks the item as error and returns 500 when extraction throws', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: { id: 'item-1', document_id: 'doc-1', correlation_id: null, created_supplier_invoice_id: null },
|
||||
error: null,
|
||||
})
|
||||
enqueue({
|
||||
data: { storage_path: 'path/to.pdf', mime_type: 'application/pdf', file_name: 'invoice.pdf' },
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: null, error: null }) // error-state update
|
||||
|
||||
supabase.storage.from = vi.fn().mockReturnValue({
|
||||
download: vi.fn().mockResolvedValue({
|
||||
data: new Blob([new Uint8Array([1])], { type: 'application/pdf' }),
|
||||
error: null,
|
||||
}),
|
||||
})
|
||||
|
||||
vi.mocked(extractInvoiceFields).mockRejectedValueOnce(new Error('pdfjs blew up'))
|
||||
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
const res = await retryRoute.handler(makeReq(), buildCtx(supabase))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(500)
|
||||
expect(body.error).toBe('pdfjs blew up')
|
||||
spy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -20,9 +20,11 @@ import {
|
||||
import { createSupplierInvoiceRegistrationEntry } from '@/lib/bookkeeping/supplier-invoice-entries'
|
||||
import { CreateSupplierInvoiceSchema } from '@/lib/api/schemas'
|
||||
import { appendProcessingHistory } from '@/lib/processing-history/append'
|
||||
import { checkInboxUploadRateLimit } from '@/lib/rate-limits/inbox'
|
||||
import type { InvoiceExtractionResult, InvoiceInboxItem, SupplierInvoice, SupplierInvoiceItem } from '@/types'
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024
|
||||
const MAX_ATTACHMENTS_PER_EMAIL = 20
|
||||
|
||||
// Partial-update schema for the /items/:id/fields PATCH route. Only the
|
||||
// scalar fields the UI exposes for inline editing — line items and
|
||||
@@ -251,6 +253,23 @@ export const invoiceInboxExtension: Extension = {
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
// Per-company rate limit (30/min, 500/day). Defense against script
|
||||
// floods and compromised sessions; never hit by real users in normal
|
||||
// monthly receipt-clearing.
|
||||
const limit = await checkInboxUploadRateLimit(ctx.supabase, ctx.companyId)
|
||||
if (!limit.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
limit.scope === 'minute'
|
||||
? 'För många uppladdningar på kort tid. Försök igen om en stund.'
|
||||
: 'Dagsgränsen för uppladdningar är nådd. Försök igen imorgon.',
|
||||
retry_after: limit.retryAfterSec,
|
||||
},
|
||||
{ status: 429, headers: { 'Retry-After': String(limit.retryAfterSec ?? 60) } },
|
||||
)
|
||||
}
|
||||
|
||||
const formData = await request.formData()
|
||||
const file = formData.get('file') as File | null
|
||||
|
||||
@@ -547,6 +566,179 @@ export const invoiceInboxExtension: Extension = {
|
||||
},
|
||||
},
|
||||
|
||||
// ── Match a supplier to an inbox item ───────────────────
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/items/:id/match-supplier',
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const url = new URL(request.url)
|
||||
const id = url.searchParams.get('_id')
|
||||
if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 })
|
||||
|
||||
let body: { supplier_id?: string }
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
if (!body.supplier_id || typeof body.supplier_id !== 'string') {
|
||||
return NextResponse.json({ error: 'supplier_id required' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Confirm supplier exists in this company before linking.
|
||||
const { data: supplier } = await ctx.supabase
|
||||
.from('suppliers')
|
||||
.select('id')
|
||||
.eq('id', body.supplier_id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
if (!supplier) {
|
||||
return NextResponse.json({ error: 'Supplier not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const { error: updateError } = await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({ matched_supplier_id: body.supplier_id })
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
|
||||
if (updateError) {
|
||||
return NextResponse.json({ error: updateError.message }, { status: 500 })
|
||||
}
|
||||
return NextResponse.json({ data: { id, matched_supplier_id: body.supplier_id } })
|
||||
},
|
||||
},
|
||||
|
||||
// ── Retry extraction on a stored document ──────────────
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/items/:id/retry-extraction',
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
if (!ctx) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
// Retry runs pdfjs extraction synchronously and is CPU-heavy; counts
|
||||
// against the same per-company quota as a fresh upload so an
|
||||
// attacker can't burn server CPU by repeatedly re-extracting one doc.
|
||||
const limit = await checkInboxUploadRateLimit(ctx.supabase, ctx.companyId)
|
||||
if (!limit.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
limit.scope === 'minute'
|
||||
? 'För många tolkningsförsök på kort tid. Försök igen om en stund.'
|
||||
: 'Dagsgränsen för tolkningar är nådd. Försök igen imorgon.',
|
||||
retry_after: limit.retryAfterSec,
|
||||
},
|
||||
{ status: 429, headers: { 'Retry-After': String(limit.retryAfterSec ?? 60) } },
|
||||
)
|
||||
}
|
||||
|
||||
const url = new URL(request.url)
|
||||
const id = url.searchParams.get('_id')
|
||||
if (!id) return NextResponse.json({ error: 'Missing id' }, { status: 400 })
|
||||
|
||||
const { data: item } = await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.select('id, document_id, correlation_id, created_supplier_invoice_id')
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!item) return NextResponse.json({ error: 'Inbox item not found' }, { status: 404 })
|
||||
if (item.created_supplier_invoice_id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Redan bokfört — kan inte köra om tolkningen.' },
|
||||
{ status: 409 },
|
||||
)
|
||||
}
|
||||
if (!item.document_id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Ingen bilaga att tolka om.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const { data: doc } = await ctx.supabase
|
||||
.from('document_attachments')
|
||||
.select('storage_path, mime_type, file_name')
|
||||
.eq('id', item.document_id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!doc) {
|
||||
return NextResponse.json({ error: 'Bilagan kunde inte hittas.' }, { status: 404 })
|
||||
}
|
||||
|
||||
const { data: blob, error: dlError } = await ctx.supabase.storage
|
||||
.from('documents')
|
||||
.download(doc.storage_path)
|
||||
|
||||
if (dlError || !blob) {
|
||||
console.error('[invoice-inbox/retry-extraction] download failed:', dlError)
|
||||
return NextResponse.json(
|
||||
{ error: 'Kunde inte ladda ner bilagan.' },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const buffer = Buffer.from(await blob.arrayBuffer())
|
||||
const { data: extracted } = await extractInvoiceFields({
|
||||
buffer,
|
||||
mimeType: doc.mime_type,
|
||||
fileName: doc.file_name,
|
||||
})
|
||||
|
||||
const { error: updateError } = await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({
|
||||
status: 'received',
|
||||
error_message: null,
|
||||
extracted_data: extracted as unknown as Record<string, unknown>,
|
||||
})
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
|
||||
if (updateError) {
|
||||
return NextResponse.json({ error: updateError.message }, { status: 500 })
|
||||
}
|
||||
|
||||
if (item.correlation_id) {
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId: ctx.companyId,
|
||||
correlationId: item.correlation_id,
|
||||
aggregateType: 'Document',
|
||||
aggregateId: item.document_id,
|
||||
eventType: 'DocumentExtractionRetried',
|
||||
payload: {
|
||||
inbox_item_id: id,
|
||||
document_id: item.document_id,
|
||||
},
|
||||
actor: { type: 'user', id: ctx.userId },
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (logErr) {
|
||||
console.error('[invoice-inbox/retry-extraction] history append failed:', logErr)
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { extracted_data: extracted } })
|
||||
} catch (error) {
|
||||
console.error('[invoice-inbox/retry-extraction] extraction failed:', error)
|
||||
const message = error instanceof Error ? error.message : 'Tolkning misslyckades'
|
||||
await ctx.supabase
|
||||
.from('invoice_inbox_items')
|
||||
.update({ status: 'error', error_message: message })
|
||||
.eq('id', id)
|
||||
.eq('company_id', ctx.companyId)
|
||||
return NextResponse.json({ error: message }, { status: 500 })
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
// ── Get this company's inbox address ────────────────────
|
||||
{
|
||||
method: 'GET',
|
||||
@@ -692,7 +884,64 @@ export const invoiceInboxExtension: Extension = {
|
||||
}
|
||||
|
||||
const bodyText = fullEmail.text ?? null
|
||||
const attachments = fullEmail.attachments ?? []
|
||||
const rawAttachments = fullEmail.attachments ?? []
|
||||
|
||||
// Per-company rate limit (30/min, 500/day). Same Postgres-backed
|
||||
// RPC as /upload. Acknowledge + drop on cap — returning 429 to
|
||||
// Resend would just consume more budget via their retry.
|
||||
const limit = await checkInboxUploadRateLimit(serviceSupabase, inbox.company_id)
|
||||
if (!limit.ok) {
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId: inbox.company_id,
|
||||
correlationId: email_id,
|
||||
aggregateType: 'System',
|
||||
aggregateId: email_id,
|
||||
eventType: 'RateLimitedDropped',
|
||||
payload: {
|
||||
scope: limit.scope,
|
||||
retry_after_sec: limit.retryAfterSec,
|
||||
attachment_count: rawAttachments.length,
|
||||
from,
|
||||
subject,
|
||||
},
|
||||
actor: { type: 'system', id: 'resend-inbound' },
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('[invoice-inbox/inbound] RateLimitedDropped append failed:', err)
|
||||
}
|
||||
return NextResponse.json({ data: { processed: 0, reason: 'rate_limited' } })
|
||||
}
|
||||
|
||||
// Per-email attachment cap. 20 covers any legitimate batched
|
||||
// supplier email; an attacker stuffing 500 PDFs into one message
|
||||
// gets truncated and a single history event records the drop.
|
||||
const totalAttachments = rawAttachments.length
|
||||
const attachments = rawAttachments.slice(0, MAX_ATTACHMENTS_PER_EMAIL)
|
||||
const truncatedCount = totalAttachments - attachments.length
|
||||
if (truncatedCount > 0) {
|
||||
try {
|
||||
await appendProcessingHistory({
|
||||
companyId: inbox.company_id,
|
||||
correlationId: email_id,
|
||||
aggregateType: 'System',
|
||||
aggregateId: email_id,
|
||||
eventType: 'AttachmentsTruncated',
|
||||
payload: {
|
||||
total: totalAttachments,
|
||||
processed: attachments.length,
|
||||
dropped: truncatedCount,
|
||||
from,
|
||||
subject,
|
||||
},
|
||||
actor: { type: 'system', id: 'resend-inbound' },
|
||||
occurredAt: new Date(),
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('[invoice-inbox/inbound] AttachmentsTruncated append failed:', err)
|
||||
}
|
||||
}
|
||||
|
||||
if (attachments.length === 0) {
|
||||
await serviceSupabase.from('invoice_inbox_items').insert({
|
||||
|
||||
Reference in New Issue
Block a user