feat(woocommerce): store order/refund feed extension (#1442)

* feat(woocommerce): store order/refund feed extension

Connect a WooCommerce store via the wc-auth key handshake (manual key
fallback) with per-store consumer key/secret AES-256-GCM encrypted at rest,
and import paid orders and refunds into the transactions inbox as a
bank-style feed on the 1680 cash account. Feed-only: nothing auto-books,
gateway fees/payouts are out of scope (core wc/v3 does not expose them).

Sync is cursor-paginated on modified_after (offset pages only inside
same-second date_modified ties), terminates on an empty page, holds the
cursor below failed refund fetches / ingest errors / deadline-skipped work,
checks the time budget between refund fetches, and drops rows dated on or
before bookkeeping_locked_through on every run. Nightly cron gated on the
extension registry + new paid capability woocommerce_sync (backfilled to
existing bank_sync grant holders).

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(migrations): move woocommerce migrations past main's 20260806090000

origin/main gained 20260806090000_recurring_schedule_interval_months while
this branch was in flight; identical version timestamps abort the Supabase
apply, so the two new migrations move to 20260806170000/20260806170100.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(woocommerce): resolve CodeRabbit review findings

- callback 503s early when WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY is
  unset: encryptCredential would otherwise throw after the probe and
  strand the pending row without error_message
- disconnect and upstream-revoke clear the encrypted consumer key/secret:
  nothing reads them after revoke and keeping decryptable dead
  credentials is unnecessary retention
- manual sync gets a 240s time budget and the panel reports a truncated
  run as 'partial, sync again' instead of a normal completion
- listOrderRefunds terminates on an empty batch (hosts may cap per_page),
  dedupes by id against hosts that ignore page, and caps total pages
- unparseable money strings count as errors and log instead of being
  silently identical to a zero total
- pg test uses per-run unique store URLs so committed rows cannot hit
  the store_url partial unique index across pg-real runs

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(woocommerce): resolve CodeRabbit cycle-2 findings

- listOrderRefunds throws when the page cap is exhausted with data still
  flowing, instead of returning a silently partial list the sync cursor
  would advance past; the error routes into the existing held-cursor
  refund-retry path
- partial sync results keep the row-error count, and the partial toast
  string surfaces it (ICU plural, hidden at zero) in both locales

Co-Authored-By: Claude Fable 5 <[email protected]>

* chore: retrigger CI after dropped push event

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Mattsson
2026-08-06 23:30:00 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent cd344b6dbb
commit 707d597b2e
41 changed files with 4335 additions and 9 deletions
@@ -0,0 +1,73 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { listOrderRefunds, type WooCredentials } from '../lib/api-client'
const CREDS: WooCredentials = {
storeUrl: 'https://shop.example.se',
consumerKey: 'ck_test',
consumerSecret: 'cs_test',
}
function jsonResponse(body: unknown): Response {
return new Response(JSON.stringify(body), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
function makeRefunds(startId: number, count: number) {
return Array.from({ length: count }, (_, i) => ({
id: startId + i,
amount: '10.00',
reason: '',
date_created_gmt: '2026-08-01T10:00:00',
}))
}
const fetchMock = vi.fn()
beforeEach(() => {
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
})
afterEach(() => {
vi.unstubAllGlobals()
})
describe('listOrderRefunds', () => {
it('terminates on an empty page, not a short one (hosts may cap per_page)', async () => {
fetchMock
.mockResolvedValueOnce(jsonResponse(makeRefunds(1, 50))) // short but non-empty
.mockResolvedValueOnce(jsonResponse(makeRefunds(51, 50)))
.mockResolvedValueOnce(jsonResponse([]))
const refunds = await listOrderRefunds(CREDS, 42)
expect(refunds).toHaveLength(100)
expect(fetchMock).toHaveBeenCalledTimes(3)
})
it('stops when a host ignoring `page` repeats the same rows', async () => {
// Fresh Response per call: a Response body is single-use.
fetchMock.mockImplementation(async () => jsonResponse(makeRefunds(1, 100)))
const refunds = await listOrderRefunds(CREDS, 42)
expect(refunds).toHaveLength(100)
// Page 1 full of fresh rows, page 2 identical → zero fresh → stop.
expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('throws instead of returning a silently partial list when the page cap is exhausted', async () => {
// Ten full pages of genuinely fresh rows: the cap trips with data still
// flowing, and a partial return would let the sync cursor pass unseen
// refunds. The thrown error routes into the caller's held-cursor retry.
fetchMock.mockImplementation(async (url: string | URL) => {
const page = Number(new URL(String(url)).searchParams.get('page'))
return jsonResponse(makeRefunds(page * 1000, 100))
})
await expect(listOrderRefunds(CREDS, 42)).rejects.toThrow(
/Refund pagination cap exceeded/,
)
expect(fetchMock).toHaveBeenCalledTimes(10)
})
})
@@ -0,0 +1,355 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
// Force the capability gate to run but stub requireCapability so entitlement
// is controlled per test. Mirrors the stripe/enable-banking suites.
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
return { ...actual, requireCapability: vi.fn().mockResolvedValue(null) }
})
// Never let a unit test reach a real WooCommerce host: the credential probe
// is mocked, the pure helpers (normalizeStoreUrl) stay real.
vi.mock('../lib/api-client', async (importOriginal) => {
const actual = await importOriginal<typeof import('../lib/api-client')>()
return { ...actual, testConnectionAndFetchStoreInfo: vi.fn() }
})
// The sync engine has its own suite; here it only needs to be callable.
vi.mock('../lib/order-sync', async (importOriginal) => {
const actual = await importOriginal<typeof import('../lib/order-sync')>()
return { ...actual, syncWooCommerceOrders: vi.fn() }
})
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => ({ service: true })),
}))
import { woocommerceExtension } from '../index'
import { requireCapability, capabilityBlockedResponse } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { testConnectionAndFetchStoreInfo } from '../lib/api-client'
import { syncWooCommerceOrders } from '../lib/order-sync'
import { decryptCredential } from '../lib/credentials'
import { createQueuedMockSupabase } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
function findRoute(method: string, path: string) {
const route = woocommerceExtension.apiRoutes?.find(
(r) => r.method === method && r.path === path,
)
expect(route, `${method} ${path} must be registered`).toBeDefined()
return route!
}
function makeRequest(method: string, body?: unknown): Request {
return new Request('https://test.local/api/extensions/ext/woocommerce/x', {
method,
headers: { 'Content-Type': 'application/json' },
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
})
}
function makeContext(supabase: unknown): ExtensionContext {
return {
userId: 'user-1',
companyId: 'company-1',
extensionId: 'woocommerce',
requestId: 'req_test',
supabase,
emit: vi.fn().mockResolvedValue(undefined),
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
settings: {
get: vi.fn().mockResolvedValue(null),
set: vi.fn().mockResolvedValue(undefined),
clear: vi.fn().mockResolvedValue(undefined),
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
}
const USER = { id: 'user-1', is_anonymous: false }
describe('woocommerce extension routes', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(requireCapability).mockResolvedValue(null)
vi.stubEnv('WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY', 'test-key')
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'http://localhost:3000')
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('GET /status', () => {
it('returns 401 without a user', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: null }, error: null })
const res = await findRoute('GET', '/status').handler(
makeRequest('GET'),
makeContext(supabase),
)
expect(res.status).toBe(401)
})
it('prefers the active connection and reports configured', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({
data: [
{ id: 'c2', status: 'revoked' },
{ id: 'c1', status: 'active', store_url: 'https://shop.example.se' },
],
})
const res = await findRoute('GET', '/status').handler(
makeRequest('GET'),
makeContext(supabase),
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.configured).toBe(true)
expect(body.connection.id).toBe('c1')
})
})
describe('POST /connect', () => {
it('returns 401 without a user', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: null }, error: null })
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', {}),
makeContext(supabase),
)
expect(res.status).toBe(401)
})
it('blocks anonymous (sandbox) users before any external call', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({
data: { user: { id: 'user-1', is_anonymous: true } },
error: null,
})
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', {}),
makeContext(supabase),
)
expect(res.status).toBe(403)
const body = await res.json()
expect(body.sandbox_blocked).toBe(true)
})
it('returns 403 capability_blocked when not entitled', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { is_sandbox: false } })
vi.mocked(requireCapability).mockResolvedValue(
capabilityBlockedResponse(CAPABILITY.woocommerce_sync),
)
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', { store_url: 'https://shop.example.se' }),
makeContext(supabase),
)
expect(res.status).toBe(403)
})
it('rejects an invalid or http store URL with 400', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { is_sandbox: false } })
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', { store_url: 'http://insecure.se' }),
makeContext(supabase),
)
expect(res.status).toBe(400)
})
it('stages a pending row and returns the wc-auth authorize URL', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { is_sandbox: false } }) // guardSandbox
enqueue({ data: [] }) // no existing active/pending
enqueue({ data: { id: 'conn-1' } }) // insert pending
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', { store_url: 'Shop.Example.se/' }),
makeContext(supabase),
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.url).toMatch(/^https:\/\/shop\.example\.se\/wc-auth\/v1\/authorize\?/)
expect(body.url).toContain('scope=read')
expect(body.url).toContain(
encodeURIComponent('http://localhost:3000/api/extensions/woocommerce/callback'),
)
const inserted = findCall('woocommerce_connections', 'insert')?.[0] as Record<
string,
unknown
>
expect(inserted.store_url).toBe('https://shop.example.se')
expect(inserted.status).toBe('pending')
expect(inserted.oauth_state).toBeTruthy()
})
})
describe('POST /manual-connect', () => {
it('rejects missing keys with 400', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { is_sandbox: false } })
const res = await findRoute('POST', '/manual-connect').handler(
makeRequest('POST', { store_url: 'https://shop.example.se', consumer_key: 'ck_x' }),
makeContext(supabase),
)
expect(res.status).toBe(400)
})
it('rejects with 400 when the credential probe fails', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { is_sandbox: false } })
enqueue({ data: [] }) // no existing connection
vi.mocked(testConnectionAndFetchStoreInfo).mockRejectedValue(new Error('401'))
const res = await findRoute('POST', '/manual-connect').handler(
makeRequest('POST', {
store_url: 'https://shop.example.se',
consumer_key: 'ck_x',
consumer_secret: 'cs_y',
}),
makeContext(supabase),
)
expect(res.status).toBe(400)
})
it('verifies, encrypts and activates on the happy path', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { is_sandbox: false } })
enqueue({ data: [] }) // no existing connection
enqueue({ data: { id: 'conn-1', store_url: 'https://shop.example.se' } }) // insert
vi.mocked(testConnectionAndFetchStoreInfo).mockResolvedValue({
name: 'Testbutiken',
currency: 'SEK',
prices_include_tax: true,
wc_version: '9.9.5',
})
const ctx = makeContext(supabase)
const res = await findRoute('POST', '/manual-connect').handler(
makeRequest('POST', {
store_url: 'https://shop.example.se',
consumer_key: 'ck_x',
consumer_secret: 'cs_y',
}),
ctx,
)
expect(res.status).toBe(200)
const inserted = findCall('woocommerce_connections', 'insert')?.[0] as Record<
string,
string
>
expect(inserted.status).toBe('active')
expect(inserted.store_name).toBe('Testbutiken')
// Secrets never stored in plaintext, and they decrypt back.
expect(inserted.consumer_key_encrypted).not.toContain('ck_x')
expect(decryptCredential(inserted.consumer_key_encrypted)).toBe('ck_x')
expect(decryptCredential(inserted.consumer_secret_encrypted)).toBe('cs_y')
expect(ctx.emit).toHaveBeenCalledWith(
expect.objectContaining({ type: 'woocommerce.connected' }),
)
})
})
describe('POST /sync', () => {
it('returns 404 without an active connection', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: null })
const res = await findRoute('POST', '/sync').handler(
makeRequest('POST'),
makeContext(supabase),
)
expect(res.status).toBe(404)
})
it('runs the sync on the service client and returns the summary', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { id: 'conn-1', status: 'active' } })
vi.mocked(syncWooCommerceOrders).mockResolvedValue({
fetched: 3,
refundsFetched: 1,
imported: 4,
duplicates: 0,
errors: 0,
})
const res = await findRoute('POST', '/sync').handler(
makeRequest('POST'),
makeContext(supabase),
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.transactions.imported).toBe(4)
expect(vi.mocked(syncWooCommerceOrders).mock.calls[0][0]).toEqual({ service: true })
})
})
describe('POST /transaction-sync', () => {
it('rejects a non-boolean enabled with 400', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
const res = await findRoute('POST', '/transaction-sync').handler(
makeRequest('POST', { enabled: 'yes' }),
makeContext(supabase),
)
expect(res.status).toBe(400)
})
it('persists the toggle for the active connection', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: [{ id: 'conn-1' }] })
const res = await findRoute('POST', '/transaction-sync').handler(
makeRequest('POST', { enabled: false }),
makeContext(supabase),
)
expect(res.status).toBe(200)
expect(findCall('woocommerce_connections', 'update')?.[0]).toEqual({
transaction_sync_enabled: false,
})
})
})
describe('DELETE /disconnect', () => {
it('returns 404 when no connection exists', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: [] })
const res = await findRoute('DELETE', '/disconnect').handler(
makeRequest('DELETE', {}),
makeContext(supabase),
)
expect(res.status).toBe(404)
})
it('revokes (never deletes) and emits the audit event', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({
data: [{ id: 'conn-1', status: 'active', store_url: 'https://shop.example.se' }],
})
enqueue({ data: null }) // update
const ctx = makeContext(supabase)
const res = await findRoute('DELETE', '/disconnect').handler(
makeRequest('DELETE', {}),
ctx,
)
expect(res.status).toBe(200)
const updated = findCall('woocommerce_connections', 'update')?.[0] as Record<
string,
unknown
>
expect(updated.status).toBe('revoked')
expect(ctx.emit).toHaveBeenCalledWith(
expect.objectContaining({ type: 'woocommerce.disconnected' }),
)
})
})
})
@@ -0,0 +1,69 @@
import { describe, it, expect, beforeEach } from 'vitest'
import {
encryptCredential,
decryptCredential,
isWooCommerceConfigured,
} from '../lib/credentials'
import { normalizeStoreUrl } from '../lib/api-client'
describe('credential codec', () => {
beforeEach(() => {
process.env.WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY = 'test-key'
})
it('round-trips a consumer key', () => {
const ciphertext = encryptCredential('ck_1234567890abcdef')
expect(ciphertext).not.toContain('ck_1234567890abcdef')
expect(decryptCredential(ciphertext)).toBe('ck_1234567890abcdef')
})
it('produces a fresh IV per encryption (no ciphertext reuse)', () => {
expect(encryptCredential('cs_secret')).not.toBe(encryptCredential('cs_secret'))
})
it('rejects tampered ciphertext (GCM auth tag)', () => {
const ciphertext = encryptCredential('cs_secret')
const tampered = ciphertext.slice(0, -2) + (ciphertext.endsWith('AA') ? 'BB' : 'AA')
expect(() => decryptCredential(tampered)).toThrow()
})
it('requires the env key', () => {
delete process.env.WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY
expect(isWooCommerceConfigured()).toBe(false)
expect(() => encryptCredential('x')).toThrow(/WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY/)
})
})
describe('normalizeStoreUrl', () => {
it('normalizes bare domains, case, and trailing slashes', () => {
expect(normalizeStoreUrl('MinButik.se')).toBe('https://minbutik.se')
expect(normalizeStoreUrl('https://Shop.Example.se/')).toBe('https://shop.example.se')
expect(normalizeStoreUrl(' https://shop.example.se ')).toBe('https://shop.example.se')
})
it('keeps subdirectory installs', () => {
expect(normalizeStoreUrl('https://example.se/butik/')).toBe('https://example.se/butik')
})
it('refuses private and internal hosts (SSRF guard)', () => {
expect(normalizeStoreUrl('https://localhost')).toBeNull()
expect(normalizeStoreUrl('https://foo.localhost')).toBeNull()
expect(normalizeStoreUrl('https://intranet.local')).toBeNull()
expect(normalizeStoreUrl('https://db.internal')).toBeNull()
expect(normalizeStoreUrl('https://127.0.0.1')).toBeNull()
expect(normalizeStoreUrl('https://10.0.0.5')).toBeNull()
expect(normalizeStoreUrl('https://172.20.1.1')).toBeNull()
expect(normalizeStoreUrl('https://192.168.1.10')).toBeNull()
expect(normalizeStoreUrl('https://169.254.169.254')).toBeNull()
expect(normalizeStoreUrl('https://[::1]')).toBeNull()
})
it('refuses http, credentials, queries and garbage', () => {
expect(normalizeStoreUrl('http://insecure.se')).toBeNull()
expect(normalizeStoreUrl('https://user:[email protected]')).toBeNull()
expect(normalizeStoreUrl('https://shop.se/?a=1')).toBeNull()
expect(normalizeStoreUrl('https://shop.se/#frag')).toBeNull()
expect(normalizeStoreUrl('not a url at all')).toBeNull()
expect(normalizeStoreUrl('')).toBeNull()
})
})
@@ -0,0 +1,450 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
const listOrdersPage = vi.fn()
const listOrderRefunds = vi.fn()
vi.mock('../lib/api-client', () => ({
listOrdersPage: (...args: unknown[]) => listOrdersPage(...args),
listOrderRefunds: (...args: unknown[]) => listOrderRefunds(...args),
isRevokedCredentialsError: (error: unknown) =>
error instanceof Error && error.message === 'REVOKED',
WC_PAGE_SIZE: 100,
}))
vi.mock('@/lib/transactions/ingest', () => ({
ingestTransactions: vi.fn(),
}))
vi.mock('@/lib/cash-accounts/service', () => ({
ensureManualCashAccount: vi.fn().mockResolvedValue('cash-account-1'),
}))
vi.mock('@/lib/import/account-sync', () => ({
syncMappedAccounts: vi.fn().mockResolvedValue({ error: null }),
}))
import { ingestTransactions } from '@/lib/transactions/ingest'
import { ensureManualCashAccount } from '@/lib/cash-accounts/service'
import { encryptCredential } from '../lib/credentials'
import {
WOOCOMMERCE_IMPORT_SOURCE,
WOOCOMMERCE_LEDGER_ACCOUNT,
mapOrder,
mapRefund,
orderQualifies,
rowBehindLock,
syncWooCommerceOrders,
wooOrderExternalId,
wooRefundExternalId,
wooStoreScope,
} from '../lib/order-sync'
import type { WooCommerceConnection, WooOrder, WooRefund } from '../types'
process.env.WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY = 'test-key'
function makeConnection(overrides: Partial<WooCommerceConnection> = {}): WooCommerceConnection {
return {
id: 'conn-1',
company_id: 'company-1',
user_id: 'user-1',
store_url: 'https://shop.example.se',
store_name: 'Testbutiken',
consumer_key_encrypted: encryptCredential('ck_test'),
consumer_secret_encrypted: encryptCredential('cs_test'),
key_permissions: 'read',
status: 'active',
oauth_state: null,
currency: 'SEK',
prices_include_tax: true,
wc_version: '9.9.5',
transaction_sync_enabled: true,
last_order_synced_at: null,
error_message: null,
connected_at: '2026-07-01T00:00:00.000Z',
disconnected_at: null,
created_at: '2026-07-01T00:00:00.000Z',
updated_at: '2026-07-01T00:00:00.000Z',
...overrides,
}
}
function makeOrder(overrides: Partial<WooOrder> = {}): WooOrder {
return {
id: 1042,
number: '1042',
status: 'processing',
currency: 'sek',
total: '1250.00',
total_tax: '250.00',
prices_include_tax: true,
date_created_gmt: '2026-08-01T09:00:00',
date_modified_gmt: '2026-08-01T09:05:00',
date_paid_gmt: '2026-08-01T09:04:30',
payment_method: 'stripe',
payment_method_title: 'Kortbetalning',
transaction_id: 'pi_abc123',
refunds: [],
...overrides,
}
}
/** Minimal chainable supabase mock covering the sync's query patterns. */
function makeSupabaseMock(options: { lockThrough?: string | null } = {}) {
const updates: Array<{ table: string; values: Record<string, unknown> }> = []
const client = {
from(table: string) {
const builder = {
select: () => builder,
eq: () => builder,
maybeSingle: async () => ({
data:
table === 'company_settings'
? { bookkeeping_locked_through: options.lockThrough ?? null }
: null,
error: null,
}),
update: (values: Record<string, unknown>) => {
updates.push({ table, values })
return builder
},
}
return builder
},
}
return { client: client as unknown as SupabaseClient, updates }
}
function cursorUpdates(updates: Array<{ table: string; values: Record<string, unknown> }>) {
return updates.filter(
(u) => u.table === 'woocommerce_connections' && 'last_order_synced_at' in u.values,
)
}
beforeEach(() => {
vi.clearAllMocks()
// Termination is an empty page; every test starts from a quiet store and
// enqueues its pages with mockResolvedValueOnce.
listOrdersPage.mockResolvedValue([])
listOrderRefunds.mockResolvedValue([])
vi.mocked(ingestTransactions).mockResolvedValue({
imported: 0,
duplicates: 0,
errors: 0,
} as Awaited<ReturnType<typeof ingestTransactions>>)
})
describe('frozen external_id formats', () => {
// ⚠️ These assert the exact persisted formats. If this test fails, you are
// about to orphan every previously imported WooCommerce row: do not update
// the expectation without a coordinated backfill (see order-sync.ts).
it('order id format is frozen', () => {
expect(wooOrderExternalId('shop.example.se', 1042)).toBe(
'woo_shop.example.se_order_1042',
)
})
it('refund id format is frozen', () => {
expect(wooRefundExternalId('shop.example.se', 77)).toBe(
'woo_shop.example.se_refund_77',
)
})
it('store scope strips exactly the https prefix and keeps host + path', () => {
expect(wooStoreScope('https://shop.example.se')).toBe('shop.example.se')
expect(wooStoreScope('https://example.se/butik')).toBe('example.se/butik')
})
it('import source and ledger account are frozen', () => {
expect(WOOCOMMERCE_IMPORT_SOURCE).toBe('woocommerce')
expect(WOOCOMMERCE_LEDGER_ACCOUNT).toBe('1680')
})
})
describe('orderQualifies', () => {
it('requires date_paid and excludes trashed orders', () => {
expect(orderQualifies(makeOrder())).toBe(true)
expect(orderQualifies(makeOrder({ status: 'refunded' }))).toBe(true)
expect(orderQualifies(makeOrder({ date_paid_gmt: null }))).toBe(false)
expect(orderQualifies(makeOrder({ status: 'trash' }))).toBe(false)
})
})
describe('mapOrder', () => {
it('maps a paid order to one gross row dated by date_paid', () => {
const rows = mapOrder('shop.example.se', makeOrder())
expect(rows).toEqual([
{
date: '2026-08-01',
description: 'WooCommerce-order #1042',
amount: 1250,
currency: 'SEK',
external_id: 'woo_shop.example.se_order_1042',
import_source: 'woocommerce',
reference: 'pi_abc123',
},
])
})
it('rounds string money to two decimals', () => {
const rows = mapOrder('s', makeOrder({ total: '99.995' }))
expect(rows[0].amount).toBe(100)
})
it('skips unpaid, trashed, zero-total and unparseable orders', () => {
expect(mapOrder('s', makeOrder({ date_paid_gmt: null }))).toEqual([])
expect(mapOrder('s', makeOrder({ status: 'trash' }))).toEqual([])
expect(mapOrder('s', makeOrder({ total: '0.00' }))).toEqual([])
expect(mapOrder('s', makeOrder({ total: 'not-a-number' }))).toEqual([])
})
})
describe('mapRefund', () => {
const refund: WooRefund = {
id: 77,
amount: '250.00',
reason: 'Retur',
date_created_gmt: '2026-08-03T10:00:00',
}
it('maps a refund to one negative row dated by the refund date', () => {
const rows = mapRefund('shop.example.se', makeOrder(), refund)
expect(rows).toEqual([
{
date: '2026-08-03',
description: 'WooCommerce-återbetalning order #1042',
amount: -250,
currency: 'SEK',
external_id: 'woo_shop.example.se_refund_77',
import_source: 'woocommerce',
reference: null,
},
])
})
it('skips zero-amount refunds', () => {
expect(mapRefund('s', makeOrder(), { ...refund, amount: '0' })).toEqual([])
})
})
describe('rowBehindLock', () => {
it('drops dates on/before the lock and keeps later ones', () => {
expect(rowBehindLock('2026-06-30', '2026-06-30')).toBe(true)
expect(rowBehindLock('2026-06-15', '2026-06-30')).toBe(true)
expect(rowBehindLock('2026-07-01', '2026-06-30')).toBe(false)
expect(rowBehindLock('2026-06-15', null)).toBe(false)
})
})
describe('syncWooCommerceOrders', () => {
it('ingests order and refund rows against the 1680 cash account and advances the cursor', async () => {
const { client, updates } = makeSupabaseMock()
const order = makeOrder({
refunds: [{ id: 77, reason: 'Retur', total: '-250.00' }],
})
listOrdersPage.mockResolvedValueOnce([order])
listOrderRefunds.mockResolvedValueOnce([
{ id: 77, amount: '250.00', reason: 'Retur', date_created_gmt: '2026-08-03T10:00:00' },
])
vi.mocked(ingestTransactions).mockResolvedValueOnce({
imported: 2,
duplicates: 0,
errors: 0,
} as Awaited<ReturnType<typeof ingestTransactions>>)
const summary = await syncWooCommerceOrders(client, makeConnection())
expect(summary).toMatchObject({ fetched: 1, refundsFetched: 1, imported: 2, duplicates: 0 })
expect(ensureManualCashAccount).toHaveBeenCalledWith(
client,
'company-1',
'1680',
'SEK',
'WooCommerce-saldo',
)
expect(ingestTransactions).toHaveBeenCalledTimes(1)
const [, companyId, userId, rows, ingestOptions] =
vi.mocked(ingestTransactions).mock.calls[0]
expect(companyId).toBe('company-1')
expect(userId).toBe('user-1')
expect((rows as Array<{ external_id: string }>).map((r) => r.external_id)).toEqual([
'woo_shop.example.se_order_1042',
'woo_shop.example.se_refund_77',
])
expect(ingestOptions).toEqual({ settlementAccount: '1680', skipAutoCategorization: true })
// Cursor persisted from the page's max date_modified_gmt, branded UTC,
// and any stale error_message is cleared on progress.
const cursors = cursorUpdates(updates)
expect(cursors).toHaveLength(1)
expect(cursors[0].values.last_order_synced_at).toBe('2026-08-01T09:05:00.000Z')
expect(cursors[0].values.error_message).toBeNull()
// Second list call proves cursor pagination: modified_after advanced to
// the last row's timestamp, page reset to 1, terminated by the empty page.
expect(listOrdersPage).toHaveBeenCalledTimes(2)
expect(listOrdersPage.mock.calls[1][1]).toEqual({
modifiedAfter: '2026-08-01T09:05:00.000Z',
page: 1,
})
})
it('drops rows dated on/before the bookkeeping lock on every run', async () => {
const { client, updates } = makeSupabaseMock({ lockThrough: '2026-08-02' })
// Order paid 2026-08-01 (behind lock), refund created 2026-08-03 (after).
const order = makeOrder({ refunds: [{ id: 77, reason: '', total: '-250.00' }] })
listOrdersPage.mockResolvedValueOnce([order])
listOrderRefunds.mockResolvedValueOnce([
{ id: 77, amount: '250.00', reason: '', date_created_gmt: '2026-08-03T10:00:00' },
])
const summary = await syncWooCommerceOrders(client, makeConnection())
expect(summary.skippedLocked).toBe(1)
const [, , , rows] = vi.mocked(ingestTransactions).mock.calls[0]
expect((rows as Array<{ external_id: string }>).map((r) => r.external_id)).toEqual([
'woo_shop.example.se_refund_77',
])
// The cursor still advances: the drop is by design, not a failure.
expect(cursorUpdates(updates)).toHaveLength(1)
})
it('holds the cursor below an order whose refund fetch failed', async () => {
const { client, updates } = makeSupabaseMock()
const order = makeOrder({ refunds: [{ id: 77, reason: '', total: '-250.00' }] })
listOrdersPage.mockResolvedValueOnce([order])
listOrderRefunds.mockRejectedValueOnce(new Error('502 from host'))
const summary = await syncWooCommerceOrders(client, makeConnection())
expect(summary.errors).toBe(1)
// date_modified 09:05:00 minus 1s: the next run re-lists this order.
const cursors = cursorUpdates(updates)
expect(cursors).toHaveLength(1)
expect(cursors[0].values.last_order_synced_at).toBe('2026-08-01T09:04:59.000Z')
})
it('pages through a full same-timestamp tie by offset, then resumes cursor pagination', async () => {
const { client } = makeSupabaseMock()
const tie = Array.from({ length: 100 }, (_, i) =>
makeOrder({ id: i + 1, number: String(i + 1) }),
)
const later = makeOrder({
id: 500,
number: '500',
date_modified_gmt: '2026-08-01T10:00:00',
})
listOrdersPage.mockResolvedValueOnce(tie).mockResolvedValueOnce([later])
const summary = await syncWooCommerceOrders(client, makeConnection())
expect(summary.fetched).toBe(101)
expect(listOrdersPage).toHaveBeenCalledTimes(3)
const [firstArgs, secondArgs, thirdArgs] = listOrdersPage.mock.calls.map((c) => c[1])
// Full page, all one timestamp: same cursor, next offset page.
expect(secondArgs).toEqual({ modifiedAfter: firstArgs.modifiedAfter, page: 2 })
// Progress within the tie page: cursor moves, offset resets.
expect(thirdArgs).toEqual({ modifiedAfter: '2026-08-01T10:00:00.000Z', page: 1 })
})
it('falls back to the first order currency when store settings were unreadable', async () => {
const { client } = makeSupabaseMock()
listOrdersPage.mockResolvedValueOnce([makeOrder({ currency: 'eur' })])
await syncWooCommerceOrders(client, makeConnection({ currency: null }))
expect(ensureManualCashAccount).toHaveBeenCalledWith(
client,
'company-1',
'1680',
'EUR',
'WooCommerce-saldo',
)
})
it('surfaces a cash-account failure on the connection instead of failing silently', async () => {
const { client, updates } = makeSupabaseMock()
listOrdersPage.mockResolvedValueOnce([makeOrder()])
vi.mocked(ensureManualCashAccount).mockRejectedValueOnce(
new Error('cash account 1680 exists with currency EUR'),
)
await expect(syncWooCommerceOrders(client, makeConnection())).rejects.toThrow(
/currency EUR/,
)
const errorUpdate = updates.find(
(u) => u.table === 'woocommerce_connections' && 'error_message' in u.values,
)
expect(errorUpdate?.values.error_message).toMatch(/1680/)
})
it('counts an unparseable order total as an error without stalling the cursor', async () => {
const { client, updates } = makeSupabaseMock()
listOrdersPage.mockResolvedValueOnce([makeOrder({ total: 'not-a-number' })])
const summary = await syncWooCommerceOrders(client, makeConnection())
expect(summary.errors).toBe(1)
expect(ingestTransactions).not.toHaveBeenCalled()
// Deliberate: a permanently corrupt total must not stall the feed.
expect(cursorUpdates(updates)).toHaveLength(1)
})
it('does nothing for a connection without credentials or not active', async () => {
const { client } = makeSupabaseMock()
const summary = await syncWooCommerceOrders(
client,
makeConnection({ consumer_key_encrypted: null }),
)
expect(summary.fetched).toBe(0)
expect(listOrdersPage).not.toHaveBeenCalled()
const revokedSummary = await syncWooCommerceOrders(
client,
makeConnection({ status: 'revoked' }),
)
expect(revokedSummary.fetched).toBe(0)
})
it('flips the connection to revoked when the store rejects the credentials', async () => {
const { client, updates } = makeSupabaseMock()
listOrdersPage.mockRejectedValueOnce(new Error('REVOKED'))
const summary = await syncWooCommerceOrders(client, makeConnection())
expect(summary.revoked).toBe(true)
const revokeUpdate = updates.find((u) => u.table === 'woocommerce_connections')
expect(revokeUpdate?.values.status).toBe('revoked')
})
it('stops before fetching when the deadline is already reached', async () => {
const { client } = makeSupabaseMock()
const summary = await syncWooCommerceOrders(
client,
makeConnection(),
undefined,
Date.now() - 1,
)
expect(summary.deadlineReached).toBe(true)
expect(listOrdersPage).not.toHaveBeenCalled()
})
it('skips remaining refund fetches on deadline and holds the cursor for them', async () => {
const { client, updates } = makeSupabaseMock()
const refunded = makeOrder({ refunds: [{ id: 77, reason: '', total: '-1.00' }] })
// The list call itself consumes the whole budget, so the deadline is
// comfortably alive at the loop check and expired by the refund loop.
const deadlineMs = Date.now() + 200
listOrdersPage.mockImplementationOnce(async () => {
await new Promise((resolve) => setTimeout(resolve, 250))
return [refunded]
})
const summary = await syncWooCommerceOrders(client, makeConnection(), undefined, deadlineMs)
expect(summary.deadlineReached).toBe(true)
expect(listOrderRefunds).not.toHaveBeenCalled()
const cursors = cursorUpdates(updates)
expect(cursors).toHaveLength(1)
expect(cursors[0].values.last_order_synced_at).toBe('2026-08-01T09:04:59.000Z')
})
})
@@ -0,0 +1,46 @@
import { describe, it, expect } from 'vitest'
import { syncSummary } from '../lib/settings-actions'
describe('syncSummary', () => {
it('maps an unreadable body to unknown', () => {
expect(syncSummary(null)).toEqual({ reason: 'unknown' })
expect(syncSummary({})).toEqual({ reason: 'unknown' })
expect(syncSummary({ transactions: {} })).toEqual({ reason: 'unknown' })
})
it('reports revoked before anything else', () => {
expect(syncSummary({ transactions: { revoked: true, fetched: 5 } })).toEqual({
reason: 'revoked',
})
})
it('reports a deadline-truncated run as partial, never as complete', () => {
expect(
syncSummary({ transactions: { deadlineReached: true, fetched: 120, imported: 80 } }),
).toEqual({ reason: 'partial', values: { fetched: 120, imported: 80, errors: 0 } })
// Even a zero-fetch truncated run is partial, not "empty": the window was
// not exhausted, so claiming the store had nothing would be false.
expect(
syncSummary({ transactions: { deadlineReached: true, fetched: 0, imported: 0 } }),
).toEqual({ reason: 'partial', values: { fetched: 0, imported: 0, errors: 0 } })
})
it('a truncated run with row errors keeps both facts', () => {
expect(
syncSummary({
transactions: { deadlineReached: true, fetched: 50, imported: 40, errors: 3 },
}),
).toEqual({ reason: 'partial', values: { fetched: 50, imported: 40, errors: 3 } })
})
it('distinguishes empty, errors and feed outcomes', () => {
expect(syncSummary({ transactions: { fetched: 0 } })).toEqual({ reason: 'empty' })
expect(
syncSummary({ transactions: { fetched: 3, imported: 2, errors: 1 } }),
).toEqual({ reason: 'errors', values: { fetched: 3, imported: 2, errors: 1 } })
expect(syncSummary({ transactions: { fetched: 3, imported: 3 } })).toEqual({
reason: 'feed',
values: { fetched: 3, imported: 3 },
})
})
})
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
import type { Extension } from '@/lib/extensions/types'
import { woocommerceApiRoutes } from './api-routes'
/**
* WooCommerce extension
*
* Connects a company's WooCommerce store via the wc-auth key handshake (or
* manual key entry) and imports the store's paid orders and refunds into the
* transactions inbox as a bank-style feed on the 1680 cash account. Feed-only
* (same doctrine as the Stripe feed, decision 2026-08-06): nothing is
* auto-booked, and payment-gateway fees/payouts are out of scope: core wc/v3
* does not expose them.
*
* Required environment variables:
* - WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY (at-rest key for consumer key/secret)
*/
export const woocommerceExtension: Extension = {
id: 'woocommerce',
name: 'WooCommerce',
version: '1.0.0',
sector: 'general',
settingsPanel: {
label: 'WooCommerce',
path: '/import?mode=woocommerce',
},
apiRoutes: woocommerceApiRoutes,
}
export default woocommerceExtension
@@ -0,0 +1,319 @@
import type { WooOrder, WooRefund, WooStoreInfo } from '../types'
/**
* Minimal WooCommerce REST API (wc/v3) client for the order feed.
*
* Auth is HTTP Basic (consumer key as username, secret as password) over
* HTTPS only. Some hosts (Apache CGI, security plugins) strip the
* Authorization header, so a 401 is retried once with the documented
* query-string credential fallback; that fallback is why plain-http stores
* are refused outright (keys in a cleartext URL are a credentials leak).
*
* Typical WooCommerce hosts are slow shared PHP boxes: requests run
* sequentially, pages are capped at 100 rows, and 429/5xx responses get a
* short exponential backoff before the error is surfaced.
*/
const REQUEST_TIMEOUT_MS = 30_000
const RETRYABLE_STATUS = new Set([429, 502, 503, 504])
const RETRY_DELAYS_MS = [1_000, 3_000]
/** wc/v3 hard maximum for per_page. */
export const WC_PAGE_SIZE = 100
export interface WooCredentials {
storeUrl: string
consumerKey: string
consumerSecret: string
}
export class WooCommerceApiError extends Error {
constructor(
message: string,
/** HTTP status, or 0 for network-level failures. */
readonly status: number,
/** WooCommerce error code (e.g. woocommerce_rest_cannot_view), if any. */
readonly wooCode: string | null = null,
) {
super(message)
this.name = 'WooCommerceApiError'
}
}
/**
* Whether an API error means the credentials themselves are dead (key deleted
* or demoted in wp-admin), as opposed to a transient failure. Used to flip a
* connection to status 'revoked' so the UI offers a reconnect instead of the
* cron retrying forever.
*/
export function isRevokedCredentialsError(error: unknown): boolean {
if (!(error instanceof WooCommerceApiError)) return false
return error.status === 401 || error.status === 403
}
/**
* Hostnames the server must never fetch: the store URL is user input that we
* probe server-side, so loopback/link-local/private ranges and internal
* naming conventions are refused outright (SSRF guard). Hostname-level only:
* a public DNS name resolving to a private address is not caught here, which
* matches the app's other outbound-URL surfaces.
*/
function isDisallowedHost(hostname: string): boolean {
const h = hostname.toLowerCase()
if (h === 'localhost' || h.endsWith('.localhost')) return true
if (h.endsWith('.local') || h.endsWith('.internal')) return true
// IPv6 literals (URL.hostname strips the brackets): never a real store.
if (h.includes(':')) return true
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h)
if (v4) {
const a = Number(v4[1])
const b = Number(v4[2])
if (a === 0 || a === 10 || a === 127) return true
if (a === 169 && b === 254) return true
if (a === 172 && b >= 16 && b <= 31) return true
if (a === 192 && b === 168) return true
}
return false
}
/**
* Normalize and validate a user-entered store URL to an https origin plus
* optional subdirectory path (WordPress installs under a path are common),
* lowercased host, no trailing slash, no query/fragment/credentials, and no
* private/internal hosts. Returns null for anything invalid, including
* plain http.
*/
export function normalizeStoreUrl(input: string): string | null {
const trimmed = input.trim()
if (!trimmed) return null
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`
let url: URL
try {
url = new URL(withScheme)
} catch {
return null
}
if (url.protocol !== 'https:') return null
if (url.username || url.password || url.search || url.hash) return null
if (isDisallowedHost(url.hostname)) return null
const path = url.pathname.replace(/\/+$/, '')
return `https://${url.host.toLowerCase()}${path}`
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
function buildUrl(
creds: WooCredentials,
path: string,
params: Record<string, string>,
credentialsInQuery: boolean,
): string {
const url = new URL(`${creds.storeUrl}/wp-json/wc/v3${path}`)
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value)
if (credentialsInQuery) {
url.searchParams.set('consumer_key', creds.consumerKey)
url.searchParams.set('consumer_secret', creds.consumerSecret)
}
return url.toString()
}
async function requestOnce(
creds: WooCredentials,
path: string,
params: Record<string, string>,
credentialsInQuery: boolean,
): Promise<Response> {
const headers: Record<string, string> = { Accept: 'application/json' }
if (!credentialsInQuery) {
const basic = Buffer.from(`${creds.consumerKey}:${creds.consumerSecret}`).toString('base64')
headers.Authorization = `Basic ${basic}`
}
return fetch(buildUrl(creds, path, params, credentialsInQuery), {
headers,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
}
async function parseError(response: Response): Promise<WooCommerceApiError> {
let wooCode: string | null = null
let detail = ''
try {
const body = (await response.json()) as { code?: string; message?: string }
wooCode = body.code ?? null
detail = body.message ?? ''
} catch {
// Non-JSON error body (host error page); the status is enough.
}
return new WooCommerceApiError(
`WooCommerce API ${response.status}${detail ? `: ${detail}` : ''}`,
response.status,
wooCode,
)
}
/**
* GET a wc/v3 path. Retries the header-stripped-auth case (401 → query-string
* credentials) once, and 429/5xx with a short backoff.
*/
export async function wcGet<T>(
creds: WooCredentials,
path: string,
params: Record<string, string> = {},
): Promise<T> {
let credentialsInQuery = false
let lastError: unknown
for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
let response: Response
try {
response = await requestOnce(creds, path, params, credentialsInQuery)
} catch (err) {
// Network/timeout errors: retry on the same backoff schedule.
lastError = new WooCommerceApiError(
`WooCommerce request failed: ${err instanceof Error ? err.message : String(err)}`,
0,
)
if (attempt < RETRY_DELAYS_MS.length) {
await sleep(RETRY_DELAYS_MS[attempt])
continue
}
throw lastError
}
if (response.ok) return (await response.json()) as T
if (response.status === 401 && !credentialsInQuery) {
// Host may be stripping the Authorization header; the documented
// fallback is credentials in the query string (HTTPS enforced upstream).
credentialsInQuery = true
lastError = await parseError(response)
continue
}
if (RETRYABLE_STATUS.has(response.status) && attempt < RETRY_DELAYS_MS.length) {
lastError = await parseError(response)
await sleep(RETRY_DELAYS_MS[attempt])
continue
}
throw await parseError(response)
}
throw lastError instanceof Error
? lastError
: new WooCommerceApiError('WooCommerce request failed', 0)
}
export interface ListOrdersOptions {
/** ISO timestamp; interpreted as UTC (dates_are_gmt is always sent). */
modifiedAfter: string
page: number
}
/**
* One page of orders modified after the cursor, oldest-modified first so the
* caller's cursor advances chronologically. Requires WooCommerce 5.8+
* (modified_after); older stores fail with a woocommerce_rest_invalid_param
* style error surfaced to the connection's error state.
*/
export async function listOrdersPage(
creds: WooCredentials,
options: ListOrdersOptions,
): Promise<WooOrder[]> {
return wcGet<WooOrder[]>(creds, '/orders', {
modified_after: options.modifiedAfter,
dates_are_gmt: 'true',
status: 'any',
orderby: 'modified',
order: 'asc',
per_page: String(WC_PAGE_SIZE),
page: String(options.page),
})
}
/** Hard cap on refund pages per order; a real order never approaches this. */
const MAX_REFUND_PAGES = 10
/**
* All refunds of one order. Terminates on an EMPTY batch, not a short one
* (hosts may cap per_page below our request, same as the order pagination),
* dedupes by id so a host that ignores `page` cannot loop forever, and caps
* total pages as a final backstop.
*/
export async function listOrderRefunds(
creds: WooCredentials,
orderId: number,
): Promise<WooRefund[]> {
const refunds: WooRefund[] = []
const seen = new Set<number>()
for (let page = 1; page <= MAX_REFUND_PAGES; page++) {
const batch = await wcGet<WooRefund[]>(creds, `/orders/${orderId}/refunds`, {
per_page: String(WC_PAGE_SIZE),
page: String(page),
})
if (batch.length === 0) return refunds
const fresh = batch.filter((r) => !seen.has(r.id))
if (fresh.length === 0) return refunds
for (const refund of fresh) seen.add(refund.id)
refunds.push(...fresh)
}
// Cap exhausted with data still flowing: returning the partial list would
// let the sync advance its cursor past refunds it never saw. Throwing
// routes into the caller's refund-failure path instead (order held, cursor
// capped, retried next run).
throw new WooCommerceApiError(
`Refund pagination cap exceeded for order ${orderId}`,
0,
)
}
/**
* Verify credentials and read store metadata. The one-order probe is the
* authoritative credential check (it exercises the read scope the feed
* needs); title and settings lookups are best-effort extras.
*/
export async function testConnectionAndFetchStoreInfo(
creds: WooCredentials,
): Promise<WooStoreInfo> {
await wcGet<unknown[]>(creds, '/orders', { per_page: '1' })
const info: WooStoreInfo = {
name: null,
currency: null,
prices_include_tax: null,
wc_version: null,
}
try {
const settings = await wcGet<Array<{ id: string; value: unknown }>>(
creds,
'/settings/general',
)
const currency = settings.find((s) => s.id === 'woocommerce_currency')?.value
if (typeof currency === 'string' && currency) info.currency = currency.toUpperCase()
const pricesIncludeTax = settings.find((s) => s.id === 'woocommerce_prices_include_tax')?.value
if (typeof pricesIncludeTax === 'string') info.prices_include_tax = pricesIncludeTax === 'yes'
} catch {
// Settings need broader permissions on some setups; the feed works without.
}
try {
const status = await wcGet<{ environment?: { version?: string } }>(creds, '/system_status')
if (status.environment?.version) info.wc_version = status.environment.version
} catch {
// system_status is admin-capability data and often blocked; optional.
}
try {
// The WP REST index is public and carries the site title.
const response = await fetch(`${creds.storeUrl}/wp-json/`, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
if (response.ok) {
const body = (await response.json()) as { name?: string }
if (body.name) info.name = body.name
}
} catch {
// Cosmetic only.
}
return info
}
@@ -0,0 +1,52 @@
import type { WooCredentials } from './api-client'
import { decryptCredential } from './credentials'
import type { WooCommerceConnection } from '../types'
/**
* WooCommerce "Auth Endpoint" handshake helpers.
*
* The merchant's browser is sent to {store}/wc-auth/v1/authorize; after they
* approve, WooCommerce POSTs the generated consumer key/secret server-to-
* server to our callback_url and redirects the browser to return_url. Our
* oauth_state UUID rides in the handshake's user_id parameter and comes back
* in both places, tying callback and return to the pending connection row.
*
* There is no signature on the callback POST, so possession of the
* single-use state is the CSRF defense, and authenticity is proven by
* probing the STORED store_url with the received keys before activation: a
* forged POST would need working read credentials for the exact store the
* user asked to connect.
*/
const APP_NAME = 'Accounted'
export function buildAuthorizeUrl(storeUrl: string, state: string): string {
const baseUrl = process.env.NEXT_PUBLIC_APP_URL
if (!baseUrl) throw new Error('NEXT_PUBLIC_APP_URL is not configured')
const params = new URLSearchParams({
app_name: APP_NAME,
// Read-only: the feed never writes to the store.
scope: 'read',
user_id: state,
return_url: `${baseUrl}/api/extensions/woocommerce/return`,
callback_url: `${baseUrl}/api/extensions/woocommerce/callback`,
})
return `${storeUrl}/wc-auth/v1/authorize?${params.toString()}`
}
/** Decrypted API credentials for an active connection. */
export function credentialsOf(
connection: Pick<
WooCommerceConnection,
'store_url' | 'consumer_key_encrypted' | 'consumer_secret_encrypted'
>,
): WooCredentials {
if (!connection.consumer_key_encrypted || !connection.consumer_secret_encrypted) {
throw new Error('Connection has no stored credentials')
}
return {
storeUrl: connection.store_url,
consumerKey: decryptCredential(connection.consumer_key_encrypted),
consumerSecret: decryptCredential(connection.consumer_secret_encrypted),
}
}
@@ -0,0 +1,44 @@
import crypto from 'crypto'
/**
* At-rest encryption for WooCommerce consumer key/secret.
*
* AES-256-GCM with a dedicated env key, mirroring the Skatteverket token
* store (extensions/general/skatteverket/lib/token-store.ts): 12-byte IV,
* 16-byte auth tag, layout iv|tag|ciphertext, base64url encoded. The key is
* deployment-wide (not per-tenant); what makes rows useless off-server is
* that WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY never leaves the environment.
*/
const ALGORITHM = 'aes-256-gcm'
/** Whether the integration is configured on this deployment. */
export function isWooCommerceConfigured(): boolean {
return Boolean(process.env.WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY)
}
function getEncryptionKey(): Buffer {
const key = process.env.WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY
if (!key) throw new Error('WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY is required')
return crypto.createHash('sha256').update(key).digest()
}
export function encryptCredential(plaintext: string): string {
const key = getEncryptionKey()
const iv = crypto.randomBytes(12)
const cipher = crypto.createCipheriv(ALGORITHM, key, iv)
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
const tag = cipher.getAuthTag()
return Buffer.concat([iv, tag, encrypted]).toString('base64url')
}
export function decryptCredential(ciphertext: string): string {
const key = getEncryptionKey()
const combined = Buffer.from(ciphertext, 'base64url')
const iv = combined.subarray(0, 12)
const tag = combined.subarray(12, 28)
const encrypted = combined.subarray(28)
const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)
decipher.setAuthTag(tag)
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString('utf8')
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,160 @@
/**
* The WooCommerce settings panel's server calls, each classified into exactly
* one outcome. Same doctrine as the Stripe panel's settings-actions (see the
* doc block there): never throw, one toast sentence per click, and the
* classification lives outside the component because component logic has no
* tests in this repo.
*/
import { fetchWithTimeout, isTimeoutError } from '@/lib/http/fetch-with-timeout'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import type { ActionFailure } from '@/lib/browser/action-failure'
/**
* Deadline for the quick calls (status, toggle, disconnect). Connect and
* manual-connect probe the merchant's WooCommerce host (often a slow shared
* PHP box, with retries), so they get a longer one.
*/
export const WOO_ACTION_TIMEOUT_MS = 15_000
export const WOO_CONNECT_TIMEOUT_MS = 120_000
/**
* Deadline for "Synka nu": the route's own ceiling (maxDuration 300 on the
* extension dispatcher) plus margin, same reasoning as the Stripe panel. A
* first sync backfills 90 days from a slow host and legitimately takes
* minutes; the server keeps working and advances the cursor even if we
* aborted, so aborting early would misreport a sync that landed.
*/
export const WOO_SYNC_TIMEOUT_MS = 310_000
export type WooRequestResult<T> =
/** 2xx. `data` is null when the body was not readable JSON. */
| { ok: true; data: T | null }
| ActionFailure
export interface WooRequestOptions {
url: string
method?: 'GET' | 'POST' | 'DELETE'
body?: unknown
locale?: ErrorLocale
timeoutMs?: number
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
/** The one sentence for a non-2xx; route copy wins over the generic map. */
export function serverErrorMessage(
body: unknown,
status: number,
locale: ErrorLocale,
): string {
if (isRecord(body)) {
if (locale === 'en' && typeof body.error_en === 'string' && body.error_en.trim()) {
return body.error_en.trim()
}
if (typeof body.error === 'string' && body.error.trim()) {
return body.error.trim()
}
}
return getErrorMessage(body, { statusCode: status, locale })
}
/** Call one of the panel's endpoints and report exactly why it failed. */
export async function wooRequest<T>({
url,
method = 'POST',
body,
locale = 'sv',
timeoutMs = WOO_ACTION_TIMEOUT_MS,
}: WooRequestOptions): Promise<WooRequestResult<T>> {
try {
const res = await fetchWithTimeout(
url,
body === undefined
? { method }
: {
method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
},
{ timeoutMs, description: `${method} ${url}` },
)
const payload = await res.json().catch(() => null)
if (!res.ok) {
return {
ok: false,
reason: 'server',
status: res.status,
message: serverErrorMessage(payload, res.status, locale),
}
}
return { ok: true, data: payload as T | null }
} catch (err) {
if (isTimeoutError(err)) return { ok: false, reason: 'timeout' }
return { ok: false, reason: 'network', message: getErrorMessage(err, { locale }) }
}
}
/** Success body of POST /api/extensions/ext/woocommerce/sync. */
export interface WooSyncPayload {
success?: boolean
/** `WooCommerceSyncSummary` from lib/order-sync.ts, over the wire. */
transactions?: {
fetched?: number
refundsFetched?: number
imported?: number
duplicates?: number
errors?: number
revoked?: boolean
deadlineReached?: boolean
}
}
type SyncCounts = {
fetched: number
imported: number
}
export type WooSyncSummary =
/** The store rejected the credentials; the connection was flipped to revoked. */
| { reason: 'revoked' }
/** The window genuinely held nothing. A real answer, not a silent success. */
| { reason: 'empty' }
/**
* The time budget ran out with orders still unfetched. Reported before the
* count-based outcomes so a truncated run never reads as a complete one;
* the cursor persisted, so pressing sync again continues where it stopped.
* Carries the error count too: a truncated run can also have failed rows,
* and dropping that number would repeat the silent-partial mistake.
*/
| { reason: 'partial'; values: SyncCounts & { errors: number } }
/** Rows landed, and some rows did not. Both halves get said. */
| { reason: 'errors'; values: SyncCounts & { errors: number } }
/** Rows landed. */
| { reason: 'feed'; values: SyncCounts }
/** 2xx whose body could not be read: the sync ran, the counts are unknown. */
| { reason: 'unknown' }
/** Turn the sync route's success body into the single sentence the user gets. */
export function syncSummary(payload: WooSyncPayload | null): WooSyncSummary {
const summary = payload?.transactions
if (!summary) return { reason: 'unknown' }
if (summary.revoked === true) return { reason: 'revoked' }
if (typeof summary.fetched !== 'number') return { reason: 'unknown' }
const fetched = summary.fetched
const imported = typeof summary.imported === 'number' ? summary.imported : 0
const errors = typeof summary.errors === 'number' ? summary.errors : 0
if (summary.deadlineReached === true) {
return { reason: 'partial', values: { fetched, imported, errors } }
}
if (fetched === 0) return { reason: 'empty' }
if (errors > 0) return { reason: 'errors', values: { fetched, imported, errors } }
return { reason: 'feed', values: { fetched, imported } }
}
@@ -0,0 +1,19 @@
{
"id": "woocommerce",
"sector": "general",
"exportName": "woocommerceExtension",
"entryPoint": "@/extensions/general/woocommerce",
"workspace": null,
"requiredEnvVars": ["WOOCOMMERCE_CREDENTIALS_ENCRYPTION_KEY"],
"optionalEnvVars": [],
"npmDependencies": [],
"definition": {
"name": "WooCommerce",
"category": "import",
"icon": "ShoppingCart",
"dataPattern": "manual",
"hasOwnData": true,
"description": "Hämta betalda ordrar och återbetalningar från din WooCommerce-butik till transaktionsinkorgen",
"longDescription": "Anslut din WooCommerce-butik så hämtas betalda ordrar och återbetalningar automatiskt varje natt till transaktionsinkorgen, som ett bankflöde för butiken. Inget bokförs automatiskt: du bokför raderna själv precis som vanliga banktransaktioner."
}
}
+89
View File
@@ -0,0 +1,89 @@
/** Row shape of public.woocommerce_connections. */
export interface WooCommerceConnection {
id: string
company_id: string
user_id: string
/** Normalized https origin (+ optional subdirectory path), no trailing slash. */
store_url: string
store_name: string | null
consumer_key_encrypted: string | null
consumer_secret_encrypted: string | null
key_permissions: string | null
status: 'pending' | 'active' | 'revoked' | 'error'
oauth_state: string | null
currency: string | null
prices_include_tax: boolean | null
wc_version: string | null
/** Opt-in: nightly order-feed cron (the manual sync button ignores it). */
transaction_sync_enabled: boolean
/** Order-polling cursor (max date_modified_gmt processed). */
last_order_synced_at: string | null
error_message: string | null
connected_at: string | null
disconnected_at: string | null
created_at: string
updated_at: string
}
/** Status payload returned by GET /api/extensions/ext/woocommerce/status. */
export interface WooCommerceStatusResponse {
configured: boolean
connection: Pick<
WooCommerceConnection,
| 'id'
| 'status'
| 'store_url'
| 'store_name'
| 'currency'
| 'error_message'
| 'connected_at'
| 'transaction_sync_enabled'
| 'last_order_synced_at'
> | null
}
/**
* Minimal wc/v3 order shape consumed by the feed. All money fields are strings
* in the order's `currency`; every date has a `_gmt` twin and the feed only
* ever reads the `_gmt` variants (store-local dates shift with DST).
*/
export interface WooOrder {
id: number
/** Display order number; usually the id, but plugins can renumber. */
number: string
status: string
currency: string
/** Grand total actually charged (gross, incl. tax and shipping). */
total: string
total_tax: string
prices_include_tax: boolean
date_created_gmt: string
date_modified_gmt: string
/** Set when payment completed; the feed's inclusion criterion and row date. */
date_paid_gmt: string | null
payment_method: string
payment_method_title: string
/** Gateway charge reference; join key for later gateway-side reconciliation. */
transaction_id: string
/** Summary of refunds against this order; totals are negative strings. */
refunds: Array<{ id: number; reason: string; total: string }>
}
/** Minimal wc/v3 order-refund shape (GET /orders/{id}/refunds). */
export interface WooRefund {
id: number
/** Refund amount as a positive string. */
amount: string
reason: string
date_created_gmt: string
}
/** Store metadata read at connect time. */
export interface WooStoreInfo {
/** WordPress site title from GET {store}/wp-json/ (public, unauthenticated). */
name: string | null
/** ISO 4217 store currency, when readable. */
currency: string | null
prices_include_tax: boolean | null
wc_version: string | null
}