* feat: multi-series SIE import, reusable FiscalYearSelector, library templates in picker - SIE import preserves each voucher's source series (B/C/I/V/...), essential for Fortnox migrations where series carry semantic meaning (kundfakturor, inbetalningar, etc.). Target numbering still goes through next_voucher_number per series; source (series, number) is stored in the migration mapping for BFNAR 2013:2 audit trail. - Execute route reads company_settings.default_voucher_series as the fallback for vouchers arriving without a series (SIE4I). - Extract shared FiscalYearSelector component; adopt in /reports and /bookkeeping. - Transaction TemplatePicker now surfaces user-created library templates (company + team scope) alongside the static registry, with a helper to convert simple library templates into the BookingTemplate shape. - Exclude 8999 "Årets resultat" from income statement financial section and monthly breakdown so year-end closing entries don't cancel the net result. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: skip Bokio SIE regression when fixtures are absent /dev_docs is gitignored (contains anonymised customer exports), so the integration test can't find its input files in CI. Gate the suite on fixture presence so it still runs locally. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: address Greptile review feedback - convertLibraryToBookingTemplate: default entity_applicability to 'all' when the source template has no entity_type, so TemplatePicker doesn't silently hide it for companies with a set entity type. - FiscalYearSelector: fire onReady in the no-company early-return branch so consumers (e.g. ReportsPage) don't get stuck in a loading skeleton while the company context is still hydrating. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat: arcim inbox + smart-match extension + commit metadata Three threads, all gated off in extensions.config.json (invoice-inbox and inbox-smart-match are not in the enabled list for this PR). invoice-inbox: Gmail OAuth -> Resend Inbound (v2.0.0) - Remove gmail-scanner / gmail-helpers - Add resend-inbound.ts (webhook verify, attachment fetch) and inbox-provisioning.ts (per-company @arcim.io address with rotation) - Replace /gmail/* routes with /inbox/address and admin-only /inbox/rotate - Workspace UI: card layout + MatchBlock surfacing AI transaction matches - classify-document: tightened discount/total prompt; cap confidence at 50% when line items do not reconcile with amount_incl_vat - Manifest requires RESEND_API_KEY, RESEND_INBOUND_DOMAIN, RESEND_INBOUND_WEBHOOK_SECRET inbox-smart-match (new extension) - Event-driven AI matching of receipts to bank transactions - Listens on inbox_item.classified (match now) and transaction.synced (retro-match receipts waiting for a transaction) - Uses service-role client; processing_history append is scoped by company_id from the event payload commit metadata + audit plumbing - journal_entries gains commit_method and rubric_version columns - commit_journal_entry RPC accepts both (BFNAR 2013:2 behandlingshistorik) - processing-history PII detector strips UUID-shaped substrings before personnummer pattern matching (UUIDs were triggering false positives) - New generic inbox_item.classified event Migrations - arcim_inbox: company_inboxes table, resend_email_id, email_body_text, auto-provision trigger, drops obsolete email_connections - journal_entry_commit_metadata: new columns + updated RPC - inbox_attachment_composite: resend_attachment_id + composite unique index - inbox_smart_match: correlation_id, match_reasoning, expanded match_method CHECK, pending-match and correlation indexes Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
100 lines
3.5 KiB
TypeScript
100 lines
3.5 KiB
TypeScript
import { Resend } from 'resend'
|
|
import type { EmailReceivedEvent, GetReceivingEmailResponseSuccess, WebhookEventPayload } from 'resend'
|
|
|
|
export type ResendInboundEvent = EmailReceivedEvent
|
|
|
|
export type ResendReceivedEmail = GetReceivingEmailResponseSuccess
|
|
|
|
export interface ResendAttachmentDownload {
|
|
id: string
|
|
filename: string
|
|
contentType: string
|
|
buffer: ArrayBuffer
|
|
}
|
|
|
|
function getResend(): Resend {
|
|
const apiKey = process.env.RESEND_API_KEY
|
|
if (!apiKey) throw new Error('RESEND_API_KEY is required')
|
|
return new Resend(apiKey)
|
|
}
|
|
|
|
export class ResendSignatureError extends Error {
|
|
constructor(message: string) {
|
|
super(message)
|
|
this.name = 'ResendSignatureError'
|
|
}
|
|
}
|
|
|
|
// Verifies the Svix-signed webhook payload using the RESEND_INBOUND_WEBHOOK_SECRET.
|
|
// Throws ResendSignatureError on failure, returns the parsed event on success.
|
|
export function verifyInboundWebhook(rawBody: string, requestHeaders: Headers): WebhookEventPayload {
|
|
const secret = process.env.RESEND_INBOUND_WEBHOOK_SECRET
|
|
if (!secret) throw new Error('RESEND_INBOUND_WEBHOOK_SECRET is required')
|
|
|
|
// Resend's verify() expects Svix headers in a specific shape, not the raw Fetch Headers.
|
|
const svixHeaders = {
|
|
id: requestHeaders.get('svix-id') ?? '',
|
|
timestamp: requestHeaders.get('svix-timestamp') ?? '',
|
|
signature: requestHeaders.get('svix-signature') ?? '',
|
|
}
|
|
|
|
const resend = getResend()
|
|
try {
|
|
return resend.webhooks.verify({ payload: rawBody, headers: svixHeaders, webhookSecret: secret })
|
|
} catch (err) {
|
|
throw new ResendSignatureError(err instanceof Error ? err.message : 'Invalid signature')
|
|
}
|
|
}
|
|
|
|
// Fetches the full received email (body, headers, attachment metadata) by email_id.
|
|
export async function fetchReceivingEmail(emailId: string): Promise<ResendReceivedEmail> {
|
|
const resend = getResend()
|
|
const { data, error } = await resend.emails.receiving.get(emailId)
|
|
if (error || !data) {
|
|
throw new Error(`Failed to fetch received email ${emailId}: ${error?.message ?? 'no data'}`)
|
|
}
|
|
return data
|
|
}
|
|
|
|
// Fetches a single attachment's bytes via its short-lived download_url.
|
|
export async function fetchInboundAttachment(
|
|
emailId: string,
|
|
attachmentId: string
|
|
): Promise<ResendAttachmentDownload> {
|
|
const resend = getResend()
|
|
const { data, error } = await resend.emails.receiving.attachments.get({ emailId, id: attachmentId })
|
|
if (error || !data) {
|
|
throw new Error(`Failed to fetch attachment ${attachmentId}: ${error?.message ?? 'no data'}`)
|
|
}
|
|
|
|
const response = await fetch(data.download_url)
|
|
if (!response.ok) {
|
|
throw new Error(`Download URL returned ${response.status} for attachment ${attachmentId}`)
|
|
}
|
|
const buffer = await response.arrayBuffer()
|
|
|
|
return {
|
|
id: data.id,
|
|
filename: data.filename ?? `attachment-${data.id}`,
|
|
contentType: data.content_type,
|
|
buffer,
|
|
}
|
|
}
|
|
|
|
// Parses the first recipient whose domain matches our configured inbound domain,
|
|
// returning just the local_part. Returns null if no match.
|
|
export function extractLocalPartForDomain(recipients: string[], domain: string): string | null {
|
|
const normalized = domain.toLowerCase()
|
|
for (const addr of recipients) {
|
|
const match = addr.match(/^\s*([^@\s]+)@([^@\s]+?)\s*$/)
|
|
if (!match) continue
|
|
const [, localPart, addrDomain] = match
|
|
if (addrDomain.toLowerCase() === normalized) return localPart.toLowerCase()
|
|
}
|
|
return null
|
|
}
|
|
|
|
export function isEmailReceivedEvent(event: WebhookEventPayload): event is EmailReceivedEvent {
|
|
return event.type === 'email.received'
|
|
}
|