feat(shopify): Shopify order/refund feed into the transactions inbox (#1474)

* feat(shopify): Shopify order/refund feed into the transactions inbox

New extensions/general/shopify feed extension, modeled on the WooCommerce
feed: connect a Shopify store with Dev Dashboard custom-app client
credentials (client credentials grant, ~24h tokens, never stored), then a
nightly cron + manual sync imports paid orders and refunds via the GraphQL
Admin API (pinned 2026-07) into the transactions inbox on clearing account
1584. Feed-only: nothing auto-books. Zero PII fields are queried, keeping
the app outside Shopify's protected customer data program.

- shopify_connections migration (RLS, revoke-never-delete, encrypted
  client id/secret) + shopify_sync capability and bank_sync-mirrored
  backfill
- frozen external_id scheme shopify_{shop_domain}_order|refund_{id},
  scoped on the shop domain so reconnects never re-import
- cursor sync on updated_at windows with 24h overlap, lock-date drop at
  map time, ingest-failure cursor floor, deadline stop-and-resume,
  revoked-credential flip
- /import card + settings panel, sv/en i18n, cron 03:15 in vercel.json +
  regenerated Docker crontabs, logo, events, panel registry
- 65 unit tests + pg-real RLS test; extensions.schema.json enum also
  gains the missing stripe entry (pre-existing drift)

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

* fix(shopify): review findings from PR 1474

- token exchange: a 429 that survives every retry is throttling, not a
  credential failure; stop remapping retryable 4xx to 401 so sustained
  throttling can no longer flip the connection to revoked and delete the
  stored credentials (CodeRabbit critical)
- order sync: advance a scanned-through watermark (run start, capped by
  the failure floor) after a fully-listed window, so empty first runs and
  quiet stores rotate to the back of the cron's oldest-first selection
  instead of permanently occupying the 50-connection batch (CodeRabbit
  major, starvation)
- add handler-level tests for the orders cron route (auth 401, disabled
  503, unconfigured no-op, query failure, capability skip, happy path,
  per-connection failure isolation, revoked marking)
- add 401 tests for /sync, /transaction-sync and /disconnect; pin the
  cursor floor rule with a two-order page; stub the encryption key via
  vi.stubEnv
- note in the panel description (sv/en) that orders can mix VAT rates and
  must be split at booking (Swedish review advisory)
- DECISIONS.md: wrap underscore identifiers in backticks (MD037)

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

---------

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Mattsson
2026-08-09 12:44:08 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 02a5d10538
commit c187fabf92
38 changed files with 4034 additions and 9 deletions
+4
View File
File diff suppressed because one or more lines are too long
+32 -3
View File
@@ -20,7 +20,7 @@ import {
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeft, CreditCard, Landmark, Loader2, ChevronRight, Download, AlertTriangle, ShoppingCart } from 'lucide-react'
import { ArrowLeft, CreditCard, Landmark, Loader2, ChevronRight, Download, AlertTriangle, ShoppingBag, ShoppingCart } from 'lucide-react'
import { cn, formatDate } from '@/lib/utils'
import { createClient } from '@/lib/supabase/client'
import { useCompany, useCapability } from '@/contexts/CompanyContext'
@@ -1959,11 +1959,14 @@ const StripePanel = getSettingsPanel('stripe')
// an import source in the same category as the Stripe feed above.
const WooCommercePanel = getSettingsPanel('woocommerce')
// And for the Shopify order feed: same category as the WooCommerce feed above.
const ShopifyPanel = getSettingsPanel('shopify')
// ============================================================
// Import Page with Selection Cards
// ============================================================
type ImportMode = null | 'psd2' | 'stripe' | 'woocommerce' | 'bank' | 'sie' | 'csv_data' | 'migration'
type ImportMode = null | 'psd2' | 'stripe' | 'woocommerce' | 'shopify' | 'bank' | 'sie' | 'csv_data' | 'migration'
export default function ImportPage() {
const { isSandbox } = useCompany()
@@ -1996,7 +1999,7 @@ export default function ImportPage() {
// Manual file-import modes (bank file, CSV/Excel, SIE) stay reachable.
const allowedModes = isSandbox
? ['bank', 'sie', 'csv_data']
: ['psd2', 'stripe', 'woocommerce', 'bank', 'sie', 'csv_data', 'migration']
: ['psd2', 'stripe', 'woocommerce', 'shopify', 'bank', 'sie', 'csv_data', 'migration']
if (!isSandbox && searchParams.get('migration')) {
setMode('migration')
} else {
@@ -2051,6 +2054,8 @@ export default function ImportPage() {
const hasWooCommerceExtension = ENABLED_EXTENSION_IDS.has('woocommerce')
// Same doctrine as Stripe: external credentials never leave the sandbox.
const woocommerceDisabled = isSandbox
const hasShopifyExtension = ENABLED_EXTENSION_IDS.has('shopify')
const shopifyDisabled = isSandbox
return (
<div className="space-y-8">
@@ -2131,6 +2136,15 @@ export default function ImportPage() {
onClick={() => setMode('woocommerce')}
/>
)}
{hasShopifyExtension && (
<ImportRow
title={t('shopify_title')}
sub={t('shopify_description')}
chips={<LogoChip src="/logos/shopify.svg" name="Shopify" />}
disabled={shopifyDisabled}
onClick={() => setMode('shopify')}
/>
)}
{hasMigrationExtension && (
<ImportRow
title={t('migration_title')}
@@ -2308,6 +2322,21 @@ export default function ImportPage() {
</Card>
)
)}
{mode === 'shopify' && (
hasShopifyExtension && ShopifyPanel ? (
<ShopifyPanel />
) : (
<Card>
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
<ShoppingBag className="mb-4 h-10 w-10 text-muted-foreground/40" />
<p className="mb-1 font-medium">{t('shopify_not_enabled_title')}</p>
<p className="max-w-md text-sm text-muted-foreground">
{t('shopify_not_enabled_description')}
</p>
</CardContent>
</Card>
)
)}
{mode === 'bank' && <BankFileImportWizard />}
{mode === 'sie' && <SIEImportWizard />}
{mode === 'csv_data' && <CSVDataImportWizard />}
@@ -0,0 +1,162 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const verifyCronSecret = vi.fn(() => null as unknown)
vi.mock('@/lib/auth/cron', () => ({
verifyCronSecret: (...args: unknown[]) => verifyCronSecret(...args),
}))
const registryGet = vi.fn()
vi.mock('@/lib/extensions/loader', () => ({ loadExtensions: vi.fn() }))
vi.mock('@/lib/extensions/registry', () => ({
extensionRegistry: { get: (...args: unknown[]) => registryGet(...args) },
}))
// The connection query chain ends in .limit(); resolve it there.
const limitResult = vi.fn()
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(() => ({
from: () => ({
select: () => ({
eq: () => ({
eq: () => ({
order: () => ({
limit: (...args: unknown[]) => limitResult(...args),
}),
}),
}),
}),
}),
})),
}))
const isShopifyConfigured = vi.fn(() => true)
vi.mock('@/extensions/general/shopify/lib/credentials', () => ({
isShopifyConfigured: (...args: unknown[]) => isShopifyConfigured(...args),
}))
const syncShopifyOrders = vi.fn()
vi.mock('@/extensions/general/shopify/lib/order-sync', () => ({
syncShopifyOrders: (...args: unknown[]) => syncShopifyOrders(...args),
}))
const hasCapability = vi.fn()
vi.mock('@/lib/entitlements/has-capability', () => ({
hasCapability: (...args: unknown[]) => hasCapability(...args),
}))
const CONNECTION = { id: 'conn-1', company_id: 'company-1' }
async function callRoute() {
const { GET } = await import('../route')
return GET(new Request('https://example.test/api/extensions/shopify/orders/cron'))
}
beforeEach(() => {
vi.clearAllMocks()
verifyCronSecret.mockReturnValue(null)
registryGet.mockReturnValue({ id: 'shopify' })
isShopifyConfigured.mockReturnValue(true)
hasCapability.mockResolvedValue(true)
limitResult.mockResolvedValue({ data: [CONNECTION], error: null })
syncShopifyOrders.mockResolvedValue({
fetched: 2,
refundsFetched: 0,
imported: 2,
duplicates: 0,
skippedLocked: 0,
errors: 0,
})
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-key'
})
describe('GET /api/extensions/shopify/orders/cron', () => {
it('returns 401 when the cron secret is wrong', async () => {
verifyCronSecret.mockReturnValue({ error: 'unauthorized' })
const res = await callRoute()
expect(res.status).toBe(401)
expect(syncShopifyOrders).not.toHaveBeenCalled()
})
it('refuses with 503 when the extension is not enabled', async () => {
registryGet.mockReturnValue(undefined)
const res = await callRoute()
expect(res.status).toBe(503)
const body = await res.json()
expect(body.code).toBe('EXTENSION_DISABLED')
})
it('no-ops when the encryption key is not configured', async () => {
isShopifyConfigured.mockReturnValue(false)
const res = await callRoute()
expect(res.status).toBe(200)
expect((await res.json()).processed).toBe(0)
expect(syncShopifyOrders).not.toHaveBeenCalled()
})
it('fails loudly when the connection query errors', async () => {
limitResult.mockResolvedValue({ data: null, error: { message: 'boom', code: '500' } })
const res = await callRoute()
expect(res.status).toBeGreaterThanOrEqual(500)
})
it('syncs each eligible connection and reports the totals', async () => {
limitResult.mockResolvedValue({
data: [CONNECTION, { id: 'conn-2', company_id: 'company-2' }],
error: null,
})
const res = await callRoute()
expect(res.status).toBe(200)
const body = await res.json()
expect(body.processed).toBe(2)
expect(body.imported).toBe(4)
expect(syncShopifyOrders).toHaveBeenCalledTimes(2)
// Runs on the service client with a shared deadline.
expect(syncShopifyOrders.mock.calls[0][0]).toBeTruthy()
expect(typeof syncShopifyOrders.mock.calls[0][3]).toBe('number')
})
it('skips connections whose company is not entitled', async () => {
hasCapability.mockResolvedValue(false)
const res = await callRoute()
expect(res.status).toBe(200)
expect((await res.json()).processed).toBe(0)
expect(syncShopifyOrders).not.toHaveBeenCalled()
})
it('records a failed connection without aborting the run', async () => {
limitResult.mockResolvedValue({
data: [CONNECTION, { id: 'conn-2', company_id: 'company-2' }],
error: null,
})
syncShopifyOrders
.mockRejectedValueOnce(new Error('store on fire'))
.mockResolvedValueOnce({
fetched: 1,
refundsFetched: 0,
imported: 1,
duplicates: 0,
skippedLocked: 0,
errors: 0,
})
const res = await callRoute()
expect(res.status).toBe(200)
const body = await res.json()
expect(body.processed).toBe(2)
expect(body.results.map((r: { status: string }) => r.status)).toEqual(['error', 'synced'])
})
it('marks a revoked connection in the results', async () => {
syncShopifyOrders.mockResolvedValue({
fetched: 0,
refundsFetched: 0,
imported: 0,
duplicates: 0,
skippedLocked: 0,
errors: 0,
revoked: true,
})
const body = await (await callRoute()).json()
expect(body.results[0].status).toBe('revoked')
})
})
@@ -0,0 +1,138 @@
import { createClient } from '@supabase/supabase-js'
import { NextResponse } from 'next/server'
import { withCronContext } from '@/lib/api/with-cron-context'
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
import { hasCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { loadExtensions } from '@/lib/extensions/loader'
import { extensionRegistry } from '@/lib/extensions/registry'
import { isShopifyConfigured } from '@/extensions/general/shopify/lib/credentials'
import { syncShopifyOrders } from '@/extensions/general/shopify/lib/order-sync'
import type { ShopifyConnection } from '@/extensions/general/shopify/types'
export const maxDuration = 300
/**
* GET /api/extensions/shopify/orders/cron
* Nightly order sync for connections that opted in (transaction_sync_enabled):
* imports each connected store's paid orders and refunds into the
* transactions inbox as a bank-style feed on the 1584 cash account.
*
* Read-only against the stores, and it never posts to the journal: rows land
* unbooked; booking stays a human decision. Idempotent via the
* (company_id, external_id) unique index, so overlapping windows and re-runs
* are no-ops. Emits no events, so no ensureInitialized() is needed.
*/
export const GET = withCronContext('cron.shopify_order_sync', async (_request, ctx) => {
// Physical routes under app/api/extensions/<id>/ compile into EVERY build,
// including the core-with-zero-extensions one: the registry (generated from
// extensions.config.json) is what actually switches an extension on. A
// scheduled-but-disabled cron must fail visibly (503) instead of quietly
// doing the work anyway.
loadExtensions()
if (!extensionRegistry.get('shopify')) {
ctx.log.warn('shopify extension is not enabled; cron refused')
return NextResponse.json(
{ error: 'Shopify extension is not enabled', code: 'EXTENSION_DISABLED' },
{ status: 503 },
)
}
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
if (!supabaseUrl || !supabaseServiceKey) {
return errorResponseFromCode('INTERNAL_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'Missing Supabase configuration' },
})
}
if (!isShopifyConfigured()) {
return NextResponse.json({ message: 'Shopify not configured', processed: 0 })
}
const supabase = createClient(supabaseUrl, supabaseServiceKey)
const { data: connections, error: connError } = await supabase
.from('shopify_connections')
.select('*')
.eq('status', 'active')
.eq('transaction_sync_enabled', true)
.order('last_order_synced_at', { ascending: true, nullsFirst: true })
.limit(50)
if (connError) {
ctx.log.error('failed to fetch shopify connections', connError, {
message: connError.message,
code: connError.code,
})
return errorResponse(connError, ctx.log, { requestId: ctx.requestId })
}
if (!connections || connections.length === 0) {
return NextResponse.json({
message: 'No connections with transaction sync enabled',
processed: 0,
})
}
const startTime = Date.now()
const TIME_BUDGET_MS = 240_000 // leave a minute of margin inside maxDuration
// Shared with syncShopifyOrders: it stops between pages and persists its
// cursor, so a truncated connection resumes next night.
const deadlineMs = startTime + TIME_BUDGET_MS
const results: Array<{
connectionId: string
imported: number
duplicates: number
status: 'synced' | 'revoked' | 'error'
}> = []
for (const connection of connections as ShopifyConnection[]) {
if (Date.now() >= deadlineMs) {
ctx.log.info('time budget reached', { processedSoFar: results.length })
break
}
if (!(await hasCapability(supabase, connection.company_id, CAPABILITY.shopify_sync))) {
ctx.log.info('skip: capability not entitled', { companyId: connection.company_id })
continue
}
try {
const summary = await syncShopifyOrders(supabase, connection, ctx.log, deadlineMs)
if (summary.deadlineReached) {
ctx.log.info('connection stopped early on time budget; remaining rows resume next run', {
connectionId: connection.id,
})
}
results.push({
connectionId: connection.id,
imported: summary.imported,
duplicates: summary.duplicates,
status: summary.revoked ? 'revoked' : 'synced',
})
} catch (error) {
ctx.log.error('shopify order sync failed for connection', error as Error, {
connectionId: connection.id,
companyId: connection.company_id,
})
results.push({
connectionId: connection.id,
imported: 0,
duplicates: 0,
status: 'error',
})
}
}
const totalImported = results.reduce((acc, r) => acc + r.imported, 0)
ctx.log.info('shopify order sync summary', {
processed: results.length,
totalImported,
failed: results.filter((r) => r.status === 'error').length,
})
return NextResponse.json({ processed: results.length, imported: totalImported, results })
})
+1
View File
@@ -30,6 +30,7 @@
0 5 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/enable-banking/sync/cron
30 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/stripe/transactions/cron
45 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/woocommerce/orders/cron
15 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/shopify/orders/cron
0 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/documents/verify/cron
0 4 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/sandbox/cleanup/cron
0 2 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/events/cleanup/cron
+1
View File
@@ -30,6 +30,7 @@
0 5 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/enable-banking/sync/cron
30 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/stripe/transactions/cron
45 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/woocommerce/orders/cron
15 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/extensions/shopify/orders/cron
0 3 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/documents/verify/cron
0 4 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/sandbox/cleanup/cron
0 2 * * * curl -sf -H "Authorization: Bearer ${CRON_SECRET}" ${APP_URL}/api/events/cleanup/cron
+1 -1
View File
@@ -1 +1 @@
{"$schema":"./extensions.schema.json","extensions":["enable-banking","email","arcim-migration","tic","mcp-server","cloud-backup","skatteverket","invoice-inbox","document-extraction","stripe","whatsapp-inbox","woocommerce"]}
{"$schema":"./extensions.schema.json","extensions":["enable-banking","email","arcim-migration","tic","mcp-server","cloud-backup","skatteverket","invoice-inbox","document-extraction","stripe","whatsapp-inbox","woocommerce","shopify"]}
+3 -1
View File
@@ -32,7 +32,9 @@
"cloud-backup",
"document-extraction",
"whatsapp-inbox",
"woocommerce"
"woocommerce",
"stripe",
"shopify"
]
},
"description": "Extension IDs to enable. Each ID must match a manifest.json in the extensions/ directory."
@@ -0,0 +1,186 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
normalizeShopDomain,
exchangeAccessToken,
shopifyGraphQL,
listOrdersPage,
isRevokedCredentialsError,
ShopifyApiError,
SHOPIFY_API_VERSION,
SHOPIFY_PAGE_SIZE,
type ShopifyCredentials,
type ShopifySession,
} from '../lib/api-client'
const CREDS: ShopifyCredentials = {
shopDomain: 'minbutik.myshopify.com',
clientId: 'client-id',
clientSecret: 'client-secret',
}
const SESSION: ShopifySession = {
shopDomain: 'minbutik.myshopify.com',
accessToken: 'token-1',
}
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
})
}
const fetchMock = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('fetch', fetchMock)
})
afterEach(() => {
vi.unstubAllGlobals()
})
describe('normalizeShopDomain', () => {
it('accepts the full myshopify.com domain in any casing, with or without scheme', () => {
expect(normalizeShopDomain('minbutik.myshopify.com')).toBe('minbutik.myshopify.com')
expect(normalizeShopDomain(' MinButik.MyShopify.com ')).toBe('minbutik.myshopify.com')
expect(normalizeShopDomain('https://minbutik.myshopify.com')).toBe('minbutik.myshopify.com')
expect(normalizeShopDomain('https://minbutik.myshopify.com/admin')).toBe(
'minbutik.myshopify.com',
)
})
it('expands a bare store handle', () => {
expect(normalizeShopDomain('minbutik')).toBe('minbutik.myshopify.com')
})
it('accepts a pasted admin URL', () => {
expect(normalizeShopDomain('https://admin.shopify.com/store/minbutik')).toBe(
'minbutik.myshopify.com',
)
expect(normalizeShopDomain('admin.shopify.com/store/minbutik/settings/apps')).toBe(
'minbutik.myshopify.com',
)
})
it('rejects anything that is not a myshopify.com host (SSRF guard)', () => {
expect(normalizeShopDomain('minbutik.se')).toBeNull()
expect(normalizeShopDomain('192.168.1.1')).toBeNull()
expect(normalizeShopDomain('https://evil.example.com/x.myshopify.com')).toBeNull()
expect(normalizeShopDomain('sub.domain.myshopify.com')).toBeNull()
expect(normalizeShopDomain('')).toBeNull()
// A bare word expands to <word>.myshopify.com, which is Shopify-owned:
// safe by construction, never a private host.
expect(normalizeShopDomain('localhost')).toBe('localhost.myshopify.com')
})
})
describe('exchangeAccessToken', () => {
it('POSTs the client credentials grant and returns the token', async () => {
fetchMock.mockResolvedValueOnce(
jsonResponse({ access_token: 'token-1', expires_in: 86399 }),
)
await expect(exchangeAccessToken(CREDS)).resolves.toBe('token-1')
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('https://minbutik.myshopify.com/admin/oauth/access_token')
expect(JSON.parse((init as RequestInit).body as string)).toEqual({
client_id: 'client-id',
client_secret: 'client-secret',
grant_type: 'client_credentials',
})
})
it('classifies a non-retryable 4xx as revoked credentials', async () => {
fetchMock.mockResolvedValueOnce(
jsonResponse({ error: 'invalid_client' }, 400),
)
const error = await exchangeAccessToken(CREDS).catch((e) => e)
expect(error).toBeInstanceOf(ShopifyApiError)
expect(isRevokedCredentialsError(error)).toBe(true)
expect((error as ShopifyApiError).code).toBe('invalid_client')
})
it('does NOT classify sustained throttling (429) as revoked credentials', async () => {
// A persistent 429 that survives every retry is still throttling.
// Classifying it as revoked would delete the stored credentials and force
// the merchant to reconnect over a rate limit.
fetchMock.mockResolvedValue(jsonResponse({}, 429))
const error = await exchangeAccessToken(CREDS).catch((e) => e)
expect(error).toBeInstanceOf(ShopifyApiError)
expect((error as ShopifyApiError).status).toBe(429)
expect(isRevokedCredentialsError(error)).toBe(false)
}, 15_000)
})
describe('shopifyGraphQL', () => {
it('sends the token header against the pinned API version and returns data', async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ data: { shop: { name: 'Butiken' } } }))
const data = await shopifyGraphQL<{ shop: { name: string } }>(SESSION, 'query { shop { name } }')
expect(data.shop.name).toBe('Butiken')
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe(
`https://minbutik.myshopify.com/admin/api/${SHOPIFY_API_VERSION}/graphql.json`,
)
expect((init as RequestInit).headers).toMatchObject({
'X-Shopify-Access-Token': 'token-1',
})
})
it('retries a THROTTLED response before surfacing data', async () => {
fetchMock
.mockResolvedValueOnce(
jsonResponse({ errors: [{ message: 'Throttled', extensions: { code: 'THROTTLED' } }] }),
)
.mockResolvedValueOnce(jsonResponse({ data: { ok: true } }))
await expect(shopifyGraphQL(SESSION, 'query { ok }')).resolves.toEqual({ ok: true })
expect(fetchMock).toHaveBeenCalledTimes(2)
}, 15_000)
it('classifies ACCESS_DENIED as revoked (missing scope)', async () => {
fetchMock.mockResolvedValueOnce(
jsonResponse({
errors: [{ message: 'Access denied', extensions: { code: 'ACCESS_DENIED' } }],
}),
)
const error = await shopifyGraphQL(SESSION, 'query { orders }').catch((e) => e)
expect(isRevokedCredentialsError(error)).toBe(true)
})
it('classifies HTTP 401 as revoked without retrying', async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({}, 401))
const error = await shopifyGraphQL(SESSION, 'query { ok }').catch((e) => e)
expect(isRevokedCredentialsError(error)).toBe(true)
expect(fetchMock).toHaveBeenCalledTimes(1)
})
})
describe('listOrdersPage', () => {
it('passes the window filter and cursor and unwraps the connection', async () => {
fetchMock.mockResolvedValueOnce(
jsonResponse({
data: {
orders: {
pageInfo: { hasNextPage: true, endCursor: 'cursor-2' },
nodes: [{ legacyResourceId: '1042', name: '#1042' }],
},
},
}),
)
const page = await listOrdersPage(SESSION, {
updatedAtMin: '2026-05-01T00:00:00.000Z',
after: 'cursor-1',
})
expect(page.hasNextPage).toBe(true)
expect(page.endCursor).toBe('cursor-2')
expect(page.orders).toHaveLength(1)
const body = JSON.parse((fetchMock.mock.calls[0][1] as RequestInit).body as string)
expect(body.variables).toEqual({
first: SHOPIFY_PAGE_SIZE,
after: 'cursor-1',
query: "updated_at:>='2026-05-01T00:00:00.000Z'",
})
})
})
@@ -0,0 +1,371 @@
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/woocommerce 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 Shopify host: the credential probe is
// mocked, the pure helpers (normalizeShopDomain) stay real.
vi.mock('../lib/api-client', async (importOriginal) => {
const actual = await importOriginal<typeof import('../lib/api-client')>()
return { ...actual, testConnectionAndFetchShopInfo: 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, syncShopifyOrders: vi.fn() }
})
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => ({ service: true })),
}))
import { shopifyExtension } from '../index'
import { requireCapability, capabilityBlockedResponse } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { testConnectionAndFetchShopInfo } from '../lib/api-client'
import { syncShopifyOrders } 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 = shopifyExtension.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/shopify/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: 'shopify',
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 }
const VALID_CONNECT_BODY = {
shop_domain: 'minbutik.myshopify.com',
client_id: 'client-id',
client_secret: 'client-secret',
}
describe('shopify extension routes', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(requireCapability).mockResolvedValue(null)
vi.stubEnv('SHOPIFY_CREDENTIALS_ENCRYPTION_KEY', 'test-key')
})
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', shop_domain: 'minbutik.myshopify.com' },
],
})
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)
expect(testConnectionAndFetchShopInfo).not.toHaveBeenCalled()
})
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.shopify_sync),
)
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', VALID_CONNECT_BODY),
makeContext(supabase),
)
expect(res.status).toBe(403)
})
it('rejects a non-myshopify.com domain 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', { ...VALID_CONNECT_BODY, shop_domain: 'https://minbutik.se' }),
makeContext(supabase),
)
expect(res.status).toBe(400)
})
it('rejects missing client credentials 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', { shop_domain: 'minbutik.myshopify.com', client_id: 'x' }),
makeContext(supabase),
)
expect(res.status).toBe(400)
})
it('returns 409 when an active connection already exists', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
enqueue({ data: { is_sandbox: false } })
enqueue({ data: [{ id: 'conn-0', status: 'active' }] })
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', VALID_CONNECT_BODY),
makeContext(supabase),
)
expect(res.status).toBe(409)
expect(testConnectionAndFetchShopInfo).not.toHaveBeenCalled()
})
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(testConnectionAndFetchShopInfo).mockRejectedValue(new Error('401'))
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', VALID_CONNECT_BODY),
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', shop_domain: 'minbutik.myshopify.com' } }) // insert
vi.mocked(testConnectionAndFetchShopInfo).mockResolvedValue({
name: 'Testbutiken',
currency: 'SEK',
})
const ctx = makeContext(supabase)
const res = await findRoute('POST', '/connect').handler(
makeRequest('POST', { ...VALID_CONNECT_BODY, shop_domain: 'MinButik' }),
ctx,
)
expect(res.status).toBe(200)
const inserted = findCall('shopify_connections', 'insert')?.[0] as Record<
string,
string
>
expect(inserted.status).toBe('active')
expect(inserted.shop_name).toBe('Testbutiken')
// The bare handle was normalized before probing and storing.
expect(inserted.shop_domain).toBe('minbutik.myshopify.com')
// Secrets never stored in plaintext, and they decrypt back.
expect(inserted.client_id_encrypted).not.toContain('client-id')
expect(decryptCredential(inserted.client_id_encrypted)).toBe('client-id')
expect(decryptCredential(inserted.client_secret_encrypted)).toBe('client-secret')
expect(ctx.emit).toHaveBeenCalledWith(
expect.objectContaining({ type: 'shopify.connected' }),
)
})
})
describe('POST /sync', () => {
it('returns 401 without a user', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: null }, error: null })
const res = await findRoute('POST', '/sync').handler(
makeRequest('POST'),
makeContext(supabase),
)
expect(res.status).toBe(401)
})
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(syncShopifyOrders).mockResolvedValue({
fetched: 3,
refundsFetched: 1,
imported: 4,
duplicates: 0,
skippedLocked: 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(syncShopifyOrders).mock.calls[0][0]).toEqual({ service: true })
})
})
describe('POST /transaction-sync', () => {
it('returns 401 without a user', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: null }, error: null })
const res = await findRoute('POST', '/transaction-sync').handler(
makeRequest('POST', { enabled: true }),
makeContext(supabase),
)
expect(res.status).toBe(401)
})
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('shopify_connections', 'update')?.[0]).toEqual({
transaction_sync_enabled: false,
})
})
})
describe('DELETE /disconnect', () => {
it('returns 401 without a user', async () => {
const { supabase } = createQueuedMockSupabase()
supabase.auth.getUser.mockResolvedValue({ data: { user: null }, error: null })
const res = await findRoute('DELETE', '/disconnect').handler(
makeRequest('DELETE', {}),
makeContext(supabase),
)
expect(res.status).toBe(401)
})
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), drops credentials 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', shop_domain: 'minbutik.myshopify.com' }],
})
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('shopify_connections', 'update')?.[0] as Record<
string,
unknown
>
expect(updated.status).toBe('revoked')
expect(updated.client_id_encrypted).toBeNull()
expect(updated.client_secret_encrypted).toBeNull()
expect(ctx.emit).toHaveBeenCalledWith(
expect.objectContaining({ type: 'shopify.disconnected' }),
)
})
})
})
@@ -0,0 +1,64 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import {
encryptCredential,
decryptCredential,
credentialsOf,
isShopifyConfigured,
} from '../lib/credentials'
describe('shopify credentials encryption', () => {
beforeEach(() => {
vi.stubEnv('SHOPIFY_CREDENTIALS_ENCRYPTION_KEY', 'test-key')
})
afterEach(() => {
vi.unstubAllEnvs()
})
it('round-trips a credential', () => {
const ciphertext = encryptCredential('shpca_client_secret_123')
expect(ciphertext).not.toContain('shpca')
expect(decryptCredential(ciphertext)).toBe('shpca_client_secret_123')
})
it('uses a fresh IV per encryption', () => {
const a = encryptCredential('same-input')
const b = encryptCredential('same-input')
expect(a).not.toBe(b)
expect(decryptCredential(a)).toBe('same-input')
expect(decryptCredential(b)).toBe('same-input')
})
it('rejects tampered ciphertext', () => {
const ciphertext = encryptCredential('secret')
const buf = Buffer.from(ciphertext, 'base64url')
buf[buf.length - 1] ^= 0xff
expect(() => decryptCredential(buf.toString('base64url'))).toThrow()
})
it('throws without the env key', () => {
vi.stubEnv('SHOPIFY_CREDENTIALS_ENCRYPTION_KEY', '')
expect(isShopifyConfigured()).toBe(false)
expect(() => encryptCredential('x')).toThrow(/SHOPIFY_CREDENTIALS_ENCRYPTION_KEY/)
})
it('credentialsOf decrypts a connection and refuses missing credentials', () => {
const creds = credentialsOf({
shop_domain: 'minbutik.myshopify.com',
client_id_encrypted: encryptCredential('client-id'),
client_secret_encrypted: encryptCredential('client-secret'),
})
expect(creds).toEqual({
shopDomain: 'minbutik.myshopify.com',
clientId: 'client-id',
clientSecret: 'client-secret',
})
expect(() =>
credentialsOf({
shop_domain: 'minbutik.myshopify.com',
client_id_encrypted: null,
client_secret_encrypted: null,
}),
).toThrow(/no stored credentials/)
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,58 @@
import { describe, it, expect } from 'vitest'
import { serverErrorMessage, syncSummary, type ShopifySyncPayload } from '../lib/settings-actions'
describe('syncSummary', () => {
const base = { fetched: 5, refundsFetched: 1, imported: 4, duplicates: 1, errors: 0 }
it('classifies a revoked run before anything else', () => {
expect(syncSummary({ transactions: { ...base, revoked: true } })).toEqual({
reason: 'revoked',
})
})
it('classifies a truncated run as partial, keeping the error count', () => {
expect(
syncSummary({ transactions: { ...base, errors: 2, deadlineReached: true } }),
).toEqual({ reason: 'partial', values: { fetched: 5, imported: 4, errors: 2 } })
})
it('classifies an empty window as its own outcome', () => {
expect(
syncSummary({ transactions: { ...base, fetched: 0, imported: 0 } }),
).toEqual({ reason: 'empty' })
})
it('reports both halves when rows landed and rows failed', () => {
expect(syncSummary({ transactions: { ...base, errors: 2 } })).toEqual({
reason: 'errors',
values: { fetched: 5, imported: 4, errors: 2 },
})
})
it('classifies a clean run as feed', () => {
expect(syncSummary({ transactions: base })).toEqual({
reason: 'feed',
values: { fetched: 5, imported: 4 },
})
})
it('classifies an unreadable body as unknown', () => {
expect(syncSummary(null)).toEqual({ reason: 'unknown' })
expect(syncSummary({} as ShopifySyncPayload)).toEqual({ reason: 'unknown' })
expect(syncSummary({ transactions: {} })).toEqual({ reason: 'unknown' })
})
})
describe('serverErrorMessage', () => {
it('prefers route copy over the generic map', () => {
expect(serverErrorMessage({ error: 'Ingen ansluten Shopify-butik.' }, 404, 'sv')).toBe(
'Ingen ansluten Shopify-butik.',
)
})
it('prefers the English variant when present and the locale is en', () => {
expect(
serverErrorMessage({ error: 'Fel.', error_en: 'An error.' }, 500, 'en'),
).toBe('An error.')
})
})
+414
View File
@@ -0,0 +1,414 @@
import { NextResponse } from 'next/server'
import type { ApiRouteDefinition, ExtensionContext } from '@/lib/extensions/types'
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
import { requireCapability } from '@/lib/entitlements/has-capability'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { guardSandbox, sandboxBlockedResponse } from '@/lib/sandbox/guard'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { isShopifyConfigured, encryptCredential } from './lib/credentials'
import { normalizeShopDomain, testConnectionAndFetchShopInfo } from './lib/api-client'
import { syncShopifyOrders } from './lib/order-sync'
import type { ShopifyConnection, ShopifyStatusResponse } from './types'
// Per-user limits: connect probes the merchant's store, sync pages its
// order history.
const RATE_LIMIT_CONNECT = { maxRequests: 10, windowMs: 60_000 }
const RATE_LIMIT_DISCONNECT = { maxRequests: 10, windowMs: 60_000 }
const RATE_LIMIT_SYNC = { maxRequests: 10, windowMs: 60_000 }
const NOT_CONFIGURED_MESSAGE =
'Shopify-integrationen är inte konfigurerad på den här installationen.'
/** Columns safe to hand to the browser: never the encrypted credentials. */
const STATUS_COLUMNS =
'id, status, shop_domain, shop_name, currency, error_message, connected_at, transaction_sync_enabled, last_order_synced_at'
type AuthedContext = {
supabase: ExtensionContext['supabase']
userId: string
isAnonymous: boolean
companyId: string
}
/** Shared auth preamble: cookie user + company context, or an error response. */
async function requireUserAndCompany(
ctx: ExtensionContext | undefined,
): Promise<AuthedContext | NextResponse> {
const supabase = ctx?.supabase ?? await (await import('@/lib/supabase/server')).createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
if (!ctx?.companyId) {
return NextResponse.json({ error: 'Company context required' }, { status: 400 })
}
return {
supabase,
userId: user.id,
isAnonymous: Boolean(user.is_anonymous),
companyId: ctx.companyId,
}
}
/**
* Connect guards: sandbox users never reach external stores (same doctrine as
* the Stripe/WooCommerce connects), and the feed is a paid capability
* (shopify_sync).
*/
async function guardConnectPreconditions(auth: AuthedContext): Promise<NextResponse | null> {
if (auth.isAnonymous) return sandboxBlockedResponse()
const sandboxBlocked = await guardSandbox(auth.supabase, auth.companyId)
if (sandboxBlocked) return sandboxBlocked
return requireCapability(auth.supabase, auth.companyId, CAPABILITY.shopify_sync)
}
export const shopifyApiRoutes: ApiRouteDefinition[] = [
{
method: 'GET',
path: '/status',
handler: async (_request: Request, ctx?: ExtensionContext) => {
const auth = await requireUserAndCompany(ctx)
if (auth instanceof NextResponse) return auth
// Prefer the active connection; otherwise surface the most recent row
// so the panel can show error/revoked states.
const { data: rows } = await auth.supabase
.from('shopify_connections')
.select(STATUS_COLUMNS)
.eq('company_id', auth.companyId)
.order('created_at', { ascending: false })
.limit(10)
const connection = rows?.find((r) => r.status === 'active') ?? rows?.[0] ?? null
const payload: ShopifyStatusResponse = {
configured: isShopifyConfigured(),
connection,
}
return NextResponse.json(payload)
},
},
{
method: 'POST',
path: '/connect',
handler: async (request: Request, ctx?: ExtensionContext) => {
const log = ctx?.log ?? console
const auth = await requireUserAndCompany(ctx)
if (auth instanceof NextResponse) return auth
const blocked = await guardConnectPreconditions(auth)
if (blocked) return blocked
const rl = await checkRateLimit({
prefix: 'shopify:connect',
identifier: auth.userId,
...RATE_LIMIT_CONNECT,
})
if (!rl.ok) return rl.response!
if (!isShopifyConfigured()) {
return NextResponse.json({ error: NOT_CONFIGURED_MESSAGE }, { status: 503 })
}
const body = (await request.json().catch(() => ({}))) as {
shop_domain?: unknown
client_id?: unknown
client_secret?: unknown
}
const shopDomain =
typeof body.shop_domain === 'string' ? normalizeShopDomain(body.shop_domain) : null
const clientId = typeof body.client_id === 'string' ? body.client_id.trim() : ''
const clientSecret =
typeof body.client_secret === 'string' ? body.client_secret.trim() : ''
if (!shopDomain) {
return NextResponse.json(
{ error: 'Ange butikens myshopify.com-adress, t.ex. minbutik.myshopify.com.' },
{ status: 400 },
)
}
if (!clientId || !clientSecret) {
return NextResponse.json(
{ error: 'Ange både appens klient-ID och klienthemlighet.' },
{ status: 400 },
)
}
const { data: existing } = await auth.supabase
.from('shopify_connections')
.select('id, status')
.eq('company_id', auth.companyId)
.eq('status', 'active')
if (existing && existing.length > 0) {
return NextResponse.json(
{ error: 'Företaget har redan en ansluten Shopify-butik. Koppla från den först.' },
{ status: 409 },
)
}
// Verify before storing: a typo'd secret or missing read_orders scope
// must fail here, not at 03:15.
let shopInfo
try {
shopInfo = await testConnectionAndFetchShopInfo({
shopDomain,
clientId,
clientSecret,
})
} catch (probeError) {
log.warn('[shopify] Credential probe failed', {
companyId: auth.companyId,
message: probeError instanceof Error ? probeError.message : String(probeError),
})
return NextResponse.json(
{
error:
'Kunde inte ansluta till butiken med de angivna uppgifterna. Kontrollera adressen och att appen har behörigheten read_orders.',
},
{ status: 400 },
)
}
const { data: created, error: insertError } = await auth.supabase
.from('shopify_connections')
.insert({
company_id: auth.companyId,
user_id: auth.userId,
shop_domain: shopDomain,
shop_name: shopInfo.name,
currency: shopInfo.currency,
client_id_encrypted: encryptCredential(clientId),
client_secret_encrypted: encryptCredential(clientSecret),
status: 'active',
connected_at: new Date().toISOString(),
transaction_sync_enabled: true,
})
.select('id, shop_domain')
.single()
if (insertError || !created) {
const isConflict = insertError?.code === '23505'
log.error('[shopify] Failed to create connection', {
message: insertError?.message,
code: insertError?.code,
companyId: auth.companyId,
})
return NextResponse.json(
{
error: isConflict
? 'Butiken är redan ansluten till ett företag.'
: 'Kunde inte spara anslutningen. Försök igen.',
},
{ status: isConflict ? 409 : 500 },
)
}
if (ctx?.emit) {
try {
await ctx.emit({
type: 'shopify.connected',
payload: {
connectionId: created.id,
shopDomain: created.shop_domain,
userId: auth.userId,
companyId: auth.companyId,
},
})
} catch {
// Audit event failure must not block the connect itself.
}
}
return NextResponse.json({ success: true, connection_id: created.id })
},
},
{
method: 'POST',
path: '/sync',
handler: async (_request: Request, ctx?: ExtensionContext) => {
const log = ctx?.log ?? console
const auth = await requireUserAndCompany(ctx)
if (auth instanceof NextResponse) return auth
const capabilityBlocked = await requireCapability(
auth.supabase,
auth.companyId,
CAPABILITY.shopify_sync,
)
if (capabilityBlocked) return capabilityBlocked
const rl = await checkRateLimit({
prefix: 'shopify:sync',
identifier: auth.userId,
...RATE_LIMIT_SYNC,
})
if (!rl.ok) return rl.response!
// Membership-scoped lookup via the user client; the sync itself runs on
// the service client (cursor updates and ingest are service paths). The
// manual button ignores transaction_sync_enabled (that flag gates the
// nightly cron): pressing it IS the opt-in.
const { data: connection } = await auth.supabase
.from('shopify_connections')
.select('*')
.eq('company_id', auth.companyId)
.eq('status', 'active')
.maybeSingle()
if (!connection) {
return NextResponse.json(
{ error: 'Ingen ansluten Shopify-butik.' },
{ status: 404 },
)
}
try {
const serviceClient = createServiceClientNoCookies()
// Bounded like the cron: without a deadline a huge first sync would be
// killed at the dispatcher's maxDuration with no cursor persisted;
// with one it stops cleanly, reports a partial sync and resumes where
// it stopped on the next press.
const summary = await syncShopifyOrders(
serviceClient,
connection as ShopifyConnection,
undefined,
Date.now() + 240_000,
)
return NextResponse.json({ success: true, transactions: summary })
} catch (error) {
log.error('[shopify] Manual sync failed', {
message: error instanceof Error ? error.message : String(error),
connection_id: connection.id,
})
return NextResponse.json(
{ error: 'Synkroniseringen misslyckades. Försök igen.' },
{ status: 502 },
)
}
},
},
{
method: 'POST',
path: '/transaction-sync',
handler: async (request: Request, ctx?: ExtensionContext) => {
const auth = await requireUserAndCompany(ctx)
if (auth instanceof NextResponse) return auth
const capabilityBlocked = await requireCapability(
auth.supabase,
auth.companyId,
CAPABILITY.shopify_sync,
)
if (capabilityBlocked) return capabilityBlocked
const rl = await checkRateLimit({
prefix: 'shopify:transaction-sync-toggle',
identifier: auth.userId,
...RATE_LIMIT_SYNC,
})
if (!rl.ok) return rl.response!
const body = (await request.json().catch(() => ({}))) as { enabled?: unknown }
if (typeof body.enabled !== 'boolean') {
return NextResponse.json({ error: 'enabled (boolean) krävs.' }, { status: 400 })
}
const { data: updated, error: updateError } = await auth.supabase
.from('shopify_connections')
.update({ transaction_sync_enabled: body.enabled })
.eq('company_id', auth.companyId)
.eq('status', 'active')
.select('id')
if (updateError) {
return NextResponse.json(
{ error: 'Kunde inte spara inställningen. Försök igen.' },
{ status: 500 },
)
}
if (!updated || updated.length === 0) {
return NextResponse.json(
{ error: 'Ingen ansluten Shopify-butik.' },
{ status: 404 },
)
}
return NextResponse.json({ success: true, enabled: body.enabled })
},
},
{
method: 'DELETE',
path: '/disconnect',
handler: async (request: Request, ctx?: ExtensionContext) => {
const log = ctx?.log ?? console
const auth = await requireUserAndCompany(ctx)
if (auth instanceof NextResponse) return auth
const rl = await checkRateLimit({
prefix: 'shopify:disconnect',
identifier: auth.userId,
...RATE_LIMIT_DISCONNECT,
})
if (!rl.ok) return rl.response!
const body = (await request.json().catch(() => ({}))) as { connection_id?: string }
const base = auth.supabase
.from('shopify_connections')
.select('id, status, shop_domain')
.eq('company_id', auth.companyId)
const query = body.connection_id
? base.eq('id', body.connection_id).limit(1)
: base.neq('status', 'revoked').order('created_at', { ascending: false }).limit(1)
const { data: rows, error: findError } = await query
const connection = rows?.[0]
if (findError || !connection) {
return NextResponse.json({ error: 'Connection not found' }, { status: 404 })
}
// There is no remote revoke API for a merchant-owned custom app: the
// app lives in the merchant's Dev Dashboard and only they can delete it
// or rotate its secret. We drop our copy of the credentials outright
// (nothing reads them after revoke, and a reconnect inserts a fresh
// row); the audit row keeps shop_domain and the connect/disconnect
// timestamps. The panel tells the user to remove the app in Shopify too.
const { error: updateError } = await auth.supabase
.from('shopify_connections')
.update({
status: 'revoked',
client_id_encrypted: null,
client_secret_encrypted: null,
disconnected_at: new Date().toISOString(),
})
.eq('id', connection.id)
.eq('company_id', auth.companyId)
if (updateError) {
log.error('[shopify] Failed to mark connection revoked', {
message: updateError.message,
connection_id: connection.id,
})
return NextResponse.json(
{ error: 'Kunde inte koppla från. Försök igen.' },
{ status: 500 },
)
}
if (ctx?.emit) {
try {
await ctx.emit({
type: 'shopify.disconnected',
payload: {
connectionId: connection.id,
shopDomain: connection.shop_domain ?? null,
reason: 'user',
userId: auth.userId,
companyId: auth.companyId,
},
})
} catch {
// Audit event failure must not block the disconnect itself.
}
}
return NextResponse.json({ success: true })
},
},
]
@@ -0,0 +1,413 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Switch } from '@/components/ui/switch'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import { useToast } from '@/components/ui/use-toast'
import { useFormat } from '@/lib/hooks/use-format'
import { failureDescription } from '@/lib/browser/action-failure'
import type { ErrorLocale } from '@/lib/errors/get-error-message'
import { KeyRound, Loader2, RefreshCw, ShoppingBag, Unlink } from 'lucide-react'
import {
shopifyRequest,
syncSummary,
SHOPIFY_CONNECT_TIMEOUT_MS,
SHOPIFY_SYNC_TIMEOUT_MS,
type ShopifySyncPayload,
} from '../lib/settings-actions'
import type { ShopifyStatusResponse } from '../types'
type ConnectionInfo = NonNullable<ShopifyStatusResponse['connection']>
const STATUS_VARIANT: Record<ConnectionInfo['status'], 'success' | 'secondary' | 'destructive' | 'warning'> = {
active: 'success',
pending: 'secondary',
revoked: 'warning',
error: 'destructive',
}
export default function ShopifySettingsPanel() {
const t = useTranslations('shopify')
const tCommon = useTranslations('common')
const locale = useLocale() as ErrorLocale
const { toast } = useToast()
const { formatDateLong } = useFormat()
const [loading, setLoading] = useState(true)
const [loadFailed, setLoadFailed] = useState(false)
const [configured, setConfigured] = useState(false)
const [connection, setConnection] = useState<ConnectionInfo | null>(null)
const [shopDomain, setShopDomain] = useState('')
const [clientId, setClientId] = useState('')
const [clientSecret, setClientSecret] = useState('')
const [connecting, setConnecting] = useState(false)
const [disconnecting, setDisconnecting] = useState(false)
const [confirmDisconnect, setConfirmDisconnect] = useState(false)
const [syncing, setSyncing] = useState(false)
const [togglingTransactionSync, setTogglingTransactionSync] = useState(false)
const failureCopy = { timeout: t('action_timeout'), network: t('action_network') }
const loadStatus = useCallback(async () => {
// A failed status read must never render as "not configured" (see the
// Stripe panel: that copy sends the user to an administrator for nothing).
const result = await shopifyRequest<ShopifyStatusResponse>({
url: '/api/extensions/ext/shopify/status',
method: 'GET',
locale,
})
setLoading(false)
if (!result.ok || !result.data) {
setLoadFailed(true)
return
}
setLoadFailed(false)
setConfigured(result.data.configured)
setConnection(result.data.connection)
}, [locale])
useEffect(() => {
void loadStatus()
}, [loadStatus])
function retryLoadStatus() {
setLoading(true)
void loadStatus()
}
async function handleConnect() {
if (connecting) return
setConnecting(true)
try {
const result = await shopifyRequest({
url: '/api/extensions/ext/shopify/connect',
body: {
shop_domain: shopDomain,
client_id: clientId,
client_secret: clientSecret,
},
locale,
timeoutMs: SHOPIFY_CONNECT_TIMEOUT_MS,
})
if (!result.ok) {
toast({
title: t('connect_failed_title'),
description: failureDescription(result, failureCopy),
variant: 'destructive',
})
return
}
toast({ title: t('connected_toast_title'), description: t('connected_toast_description') })
setClientId('')
setClientSecret('')
await loadStatus()
} finally {
setConnecting(false)
}
}
async function handleSyncNow() {
if (syncing) return
setSyncing(true)
try {
const result = await shopifyRequest<ShopifySyncPayload>({
url: '/api/extensions/ext/shopify/sync',
locale,
timeoutMs: SHOPIFY_SYNC_TIMEOUT_MS,
})
if (!result.ok) {
toast({
title: t('sync_failed_title'),
description: failureDescription(result, failureCopy),
variant: 'destructive',
})
return
}
const summary = syncSummary(result.data)
if (summary.reason === 'revoked') {
toast({
title: t('sync_failed_title'),
description: t('sync_revoked'),
variant: 'destructive',
})
} else if (summary.reason === 'partial') {
toast({ title: t('sync_partial_title'), description: t('sync_partial', summary.values) })
} else if (summary.reason === 'empty') {
toast({ title: t('sync_done_title'), description: t('sync_done_empty') })
} else if (summary.reason === 'errors') {
toast({ title: t('sync_done_title'), description: t('sync_done_feed_errors', summary.values) })
} else if (summary.reason === 'feed') {
toast({ title: t('sync_done_title'), description: t('sync_done_feed', summary.values) })
} else {
toast({ title: t('sync_done_title') })
}
await loadStatus()
} finally {
setSyncing(false)
}
}
async function handleToggleTransactionSync(enabled: boolean) {
if (togglingTransactionSync) return
setTogglingTransactionSync(true)
try {
const result = await shopifyRequest({
url: '/api/extensions/ext/shopify/transaction-sync',
body: { enabled },
locale,
})
if (!result.ok) {
toast({
title: t('transaction_sync_toggle_failed'),
description: failureDescription(result, failureCopy),
variant: 'destructive',
})
return
}
toast({
title: enabled
? t('transaction_sync_enabled_toast')
: t('transaction_sync_disabled_toast'),
})
await loadStatus()
} finally {
setTogglingTransactionSync(false)
}
}
async function handleDisconnect() {
if (!connection || disconnecting) return
setDisconnecting(true)
try {
const result = await shopifyRequest({
url: '/api/extensions/ext/shopify/disconnect',
method: 'DELETE',
body: { connection_id: connection.id },
locale,
})
if (!result.ok) {
toast({
title: t('disconnect_failed_title'),
description: failureDescription(result, failureCopy),
variant: 'destructive',
})
return
}
// The app still exists in the merchant's Shopify Dev Dashboard; only
// they can delete it there, so the toast says so.
toast({ title: t('disconnected_toast_title'), description: t('disconnected_toast_description') })
setConfirmDisconnect(false)
await loadStatus()
} finally {
setDisconnecting(false)
}
}
if (loading) {
return (
<Card>
<CardContent className="space-y-3 p-6">
<Skeleton className="h-5 w-48" />
<Skeleton className="h-4 w-72" />
<Skeleton className="h-10 w-40" />
</CardContent>
</Card>
)
}
if (loadFailed) {
return (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('title')}</CardTitle>
</CardHeader>
<CardContent className="space-y-4 pt-0">
<p className="text-sm text-destructive">{t('load_failed')}</p>
<Button variant="outline" size="sm" onClick={retryLoadStatus}>
<RefreshCw className="mr-2 h-4 w-4" />
{tCommon('retry')}
</Button>
</CardContent>
</Card>
)
}
if (!configured) {
return (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('title')}</CardTitle>
</CardHeader>
<CardContent className="pt-0">
<p className="text-sm text-muted-foreground">{t('not_configured')}</p>
</CardContent>
</Card>
)
}
const isActive = connection?.status === 'active'
const showConnectForm = !connection || !isActive
return (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('title')}</CardTitle>
</CardHeader>
<CardContent className="space-y-6 pt-0">
<p className="text-sm text-muted-foreground">{t('description')}</p>
{connection && (
<div className="flex flex-wrap items-center justify-between gap-4 rounded-lg border border-border p-4">
<div className="flex items-center gap-3">
<ShoppingBag className="h-5 w-5 text-muted-foreground" />
<div>
<div className="flex items-center gap-2">
<span className="text-sm font-medium">
{connection.shop_name || connection.shop_domain || t('unnamed_store')}
</span>
<Badge variant={STATUS_VARIANT[connection.status]}>
{t(`status_${connection.status}`)}
</Badge>
</div>
{connection.shop_name && (
<p className="mt-1 text-sm text-muted-foreground">{connection.shop_domain}</p>
)}
{isActive && connection.connected_at && (
<p className="mt-1 text-sm text-muted-foreground">
{t('connected_since', { date: formatDateLong(connection.connected_at) })}
</p>
)}
{connection.error_message && (
// Shown for active connections too: a sync that cannot run
// (e.g. cash-account currency conflict) must not hide
// behind a healthy-looking "Ansluten" badge.
<p className="mt-1 text-sm text-destructive">{connection.error_message}</p>
)}
</div>
</div>
{isActive && (
confirmDisconnect ? (
<div className="flex items-center gap-2">
<Button
variant="destructive"
size="sm"
onClick={handleDisconnect}
disabled={disconnecting}
>
{t('disconnect_confirm')}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setConfirmDisconnect(false)}
disabled={disconnecting}
>
{t('cancel')}
</Button>
</div>
) : (
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={handleSyncNow} disabled={syncing}>
{syncing ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<RefreshCw className="mr-2 h-4 w-4" />
)}
{syncing ? t('syncing') : t('sync_now')}
</Button>
<Button variant="outline" size="sm" onClick={() => setConfirmDisconnect(true)}>
<Unlink className="mr-2 h-4 w-4" />
{t('disconnect')}
</Button>
</div>
)
)}
</div>
)}
{showConnectForm && (
<div className="space-y-4">
<p className="text-sm text-muted-foreground">{t('connect_hint')}</p>
<div className="space-y-2">
<Label htmlFor="shopify-shop-domain">{t('shop_domain_label')}</Label>
<Input
id="shopify-shop-domain"
inputMode="url"
placeholder="minbutik.myshopify.com"
value={shopDomain}
onChange={(e) => setShopDomain(e.target.value)}
disabled={connecting}
/>
</div>
<div className="space-y-2">
<Label htmlFor="shopify-client-id">{t('client_id_label')}</Label>
<Input
id="shopify-client-id"
autoComplete="off"
value={clientId}
onChange={(e) => setClientId(e.target.value)}
disabled={connecting}
/>
</div>
<div className="space-y-2">
<Label htmlFor="shopify-client-secret">{t('client_secret_label')}</Label>
<Input
id="shopify-client-secret"
type="password"
autoComplete="off"
value={clientSecret}
onChange={(e) => setClientSecret(e.target.value)}
disabled={connecting}
/>
</div>
<Button
onClick={handleConnect}
disabled={connecting || !shopDomain || !clientId || !clientSecret}
>
{connecting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<KeyRound className="mr-2 h-4 w-4" />
)}
{connecting ? t('connecting') : t('connect')}
</Button>
</div>
)}
{isActive && connection && (
<div className="flex flex-wrap items-start justify-between gap-4 rounded-lg border border-border p-4">
<div className="min-w-0 max-w-prose space-y-1">
<p className="text-sm font-medium">{t('transaction_sync_title')}</p>
<p className="text-sm text-muted-foreground">{t('transaction_sync_description')}</p>
{connection.transaction_sync_enabled ? (
<p className="text-xs text-muted-foreground">
{connection.last_order_synced_at
? t('transaction_sync_last_synced', {
date: formatDateLong(connection.last_order_synced_at),
})
: t('transaction_sync_never_synced')}
</p>
) : (
<p className="text-xs text-muted-foreground">
{t('transaction_sync_backfill_note')}
</p>
)}
</div>
<Switch
checked={connection.transaction_sync_enabled}
onCheckedChange={handleToggleTransactionSync}
disabled={togglingTransactionSync}
aria-label={t('transaction_sync_title')}
/>
</div>
)}
</CardContent>
</Card>
)
}
+32
View File
@@ -0,0 +1,32 @@
import type { Extension } from '@/lib/extensions/types'
import { shopifyApiRoutes } from './api-routes'
/**
* Shopify extension
*
* Connects a company's Shopify store via a merchant-created Dev Dashboard
* custom app (client credentials grant; the revealable shpat_ token flow was
* discontinued 2026-01-01) and imports the store's paid orders and refunds
* into the transactions inbox as a bank-style feed on the 1584 cash account.
* Feed-only (same doctrine as the Stripe and WooCommerce feeds): nothing is
* auto-booked, and Shopify Payments payout/fee reconciliation is out of
* scope for now (phase 2).
*
* Required environment variables:
* - SHOPIFY_CREDENTIALS_ENCRYPTION_KEY (at-rest key for client id/secret)
*/
export const shopifyExtension: Extension = {
id: 'shopify',
name: 'Shopify',
version: '1.0.0',
sector: 'general',
settingsPanel: {
label: 'Shopify',
path: '/import?mode=shopify',
},
apiRoutes: shopifyApiRoutes,
}
export default shopifyExtension
@@ -0,0 +1,349 @@
import type { ShopifyOrder, ShopifyShopInfo } from '../types'
/**
* Minimal Shopify GraphQL Admin API client for the order feed.
*
* Auth is the client credentials grant: the merchant creates a custom app in
* their own Shopify Dev Dashboard (the admin-created custom apps with
* revealable shpat_ tokens were discontinued 2026-01-01) and pastes the app's
* client id/secret; the server exchanges those for a ~24h access token at the
* start of every run. REST is legacy since 2024, so everything here is
* GraphQL against a pinned API version.
*
* Rate limiting is cost-based (points/second leaky bucket); a throttled query
* comes back as HTTP 200 with a THROTTLED GraphQL error, so both that and
* plain 429/5xx get a short backoff before the error is surfaced.
*/
/** Pinned Admin API version; bump quarterly (supported >= 12 months). */
export const SHOPIFY_API_VERSION = '2026-07'
/** Orders per page; the API caps `first` at 250, 100 keeps query cost low. */
export const SHOPIFY_PAGE_SIZE = 100
const REQUEST_TIMEOUT_MS = 30_000
const RETRYABLE_STATUS = new Set([429, 502, 503, 504])
const RETRY_DELAYS_MS = [1_000, 3_000]
export interface ShopifyCredentials {
/** Normalized myshopify.com domain. */
shopDomain: string
clientId: string
clientSecret: string
}
/** A run-scoped session: the exchanged token lives ~24h and is never stored. */
export interface ShopifySession {
shopDomain: string
accessToken: string
}
export class ShopifyApiError extends Error {
constructor(
message: string,
/** HTTP status, or 0 for network-level / GraphQL-level failures. */
readonly status: number,
/** GraphQL error code (e.g. ACCESS_DENIED) or OAuth error, if any. */
readonly code: string | null = null,
) {
super(message)
this.name = 'ShopifyApiError'
}
}
/**
* Whether an API error means the credentials themselves are dead (app deleted
* or secret rotated in the Dev Dashboard), 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 ShopifyApiError)) return false
return error.status === 401 || error.status === 403
}
/**
* Normalize user input to a bare myshopify.com domain. Accepts the domain
* with or without scheme/path, the bare store handle, and a pasted admin URL
* (admin.shopify.com/store/<handle>). Anything that does not resolve to
* <handle>.myshopify.com returns null: the Admin API only lives there, and
* refusing arbitrary hosts doubles as the SSRF guard (the server never
* fetches a user-controlled hostname).
*/
export function normalizeShopDomain(input: string): string | null {
let value = input.trim().toLowerCase()
if (!value) return null
const adminMatch =
/^(?:https?:\/\/)?admin\.shopify\.com\/store\/([a-z0-9][a-z0-9-]*)(?:[/?#]|$)/.exec(value)
if (adminMatch) return `${adminMatch[1]}.myshopify.com`
value = value.replace(/^https?:\/\//, '')
value = value.split(/[/?#]/)[0]
if (!value) return null
if (!value.includes('.')) value = `${value}.myshopify.com`
return /^[a-z0-9][a-z0-9-]*\.myshopify\.com$/.test(value) ? value : null
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function postJson(url: string, body: unknown, headers: Record<string, string>) {
return fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json', ...headers },
body: JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
}
/**
* Exchange the custom app's client id/secret for an access token
* (client credentials grant; expires_in ~86400s). Any 4xx here means the
* credentials are unusable (invalid_client, app uninstalled, plan gate), so
* it is reported as status 401 and classified as revoked; 429/5xx retry on
* the normal backoff schedule.
*/
export async function exchangeAccessToken(creds: ShopifyCredentials): Promise<string> {
let lastError: unknown
for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
let response: Response
try {
response = await postJson(
`https://${creds.shopDomain}/admin/oauth/access_token`,
{
client_id: creds.clientId,
client_secret: creds.clientSecret,
grant_type: 'client_credentials',
},
{},
)
} catch (err) {
lastError = new ShopifyApiError(
`Shopify token exchange 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) {
const body = (await response.json().catch(() => null)) as {
access_token?: unknown
} | null
if (typeof body?.access_token === 'string' && body.access_token) {
return body.access_token
}
throw new ShopifyApiError('Shopify token exchange returned no access token', 0)
}
if (RETRYABLE_STATUS.has(response.status) && attempt < RETRY_DELAYS_MS.length) {
lastError = new ShopifyApiError(
`Shopify token exchange ${response.status}`,
response.status,
)
await sleep(RETRY_DELAYS_MS[attempt])
continue
}
const errorBody = (await response.json().catch(() => null)) as {
error?: string
error_description?: string
} | null
// Only non-retryable 4xx means the credentials are unusable. A 429 that
// survived every retry is still throttling, not revocation: mapping it to
// 401 would classify as revoked and delete the stored credentials.
const credentialFailure =
response.status >= 400 &&
response.status < 500 &&
!RETRYABLE_STATUS.has(response.status)
throw new ShopifyApiError(
`Shopify token exchange ${response.status}${
errorBody?.error_description ? `: ${errorBody.error_description}` : ''
}`,
credentialFailure ? 401 : response.status,
errorBody?.error ?? null,
)
}
throw lastError instanceof Error
? lastError
: new ShopifyApiError('Shopify token exchange failed', 0)
}
/** Exchange the credentials for a run-scoped session. */
export async function createShopifySession(
creds: ShopifyCredentials,
): Promise<ShopifySession> {
return { shopDomain: creds.shopDomain, accessToken: await exchangeAccessToken(creds) }
}
interface GraphQLErrorShape {
message?: string
extensions?: { code?: string }
}
/**
* POST one GraphQL query. Retries THROTTLED (HTTP 200 + GraphQL error code),
* 429/5xx and network errors with a short backoff; 401/403 (token expired
* mid-run, app revoked) and ACCESS_DENIED (scope missing) throw a
* ShopifyApiError that classifies as revoked.
*/
export async function shopifyGraphQL<T>(
session: ShopifySession,
query: string,
variables: Record<string, unknown> = {},
): Promise<T> {
const url = `https://${session.shopDomain}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`
let lastError: unknown
for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
let response: Response
try {
response = await postJson(url, { query, variables }, {
'X-Shopify-Access-Token': session.accessToken,
})
} catch (err) {
lastError = new ShopifyApiError(
`Shopify 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) {
if (RETRYABLE_STATUS.has(response.status) && attempt < RETRY_DELAYS_MS.length) {
lastError = new ShopifyApiError(`Shopify API ${response.status}`, response.status)
await sleep(RETRY_DELAYS_MS[attempt])
continue
}
throw new ShopifyApiError(`Shopify API ${response.status}`, response.status)
}
const body = (await response.json().catch(() => null)) as {
data?: T
errors?: GraphQLErrorShape[]
} | null
if (body?.errors && body.errors.length > 0) {
const throttled = body.errors.some((e) => e.extensions?.code === 'THROTTLED')
if (throttled && attempt < RETRY_DELAYS_MS.length) {
lastError = new ShopifyApiError('Shopify API throttled', 0, 'THROTTLED')
await sleep(RETRY_DELAYS_MS[attempt])
continue
}
const accessDenied = body.errors.some((e) => e.extensions?.code === 'ACCESS_DENIED')
const message = body.errors[0]?.message ?? 'unknown GraphQL error'
throw new ShopifyApiError(
`Shopify GraphQL error: ${message}`,
accessDenied ? 403 : 0,
body.errors[0]?.extensions?.code ?? null,
)
}
if (!body?.data) {
throw new ShopifyApiError('Shopify API returned no data', 0)
}
return body.data
}
throw lastError instanceof Error
? lastError
: new ShopifyApiError('Shopify request failed', 0)
}
/**
* Order fields for the feed. Deliberately NO customer/PII fields (customer,
* email, addresses): they are gated behind Shopify's protected customer data
* program, and a bookkeeping feed does not need them; the verifikat reference
* is the order name/id. Refunds come inline (plain list, not a connection),
* so no per-order follow-up requests are needed.
*/
const ORDERS_QUERY = `
query OrdersFeed($first: Int!, $after: String, $query: String) {
orders(first: $first, after: $after, query: $query, sortKey: UPDATED_AT) {
pageInfo { hasNextPage endCursor }
nodes {
legacyResourceId
name
test
processedAt
updatedAt
displayFinancialStatus
paymentGatewayNames
totalPriceSet { shopMoney { amount currencyCode } }
refunds {
legacyResourceId
createdAt
totalRefundedSet { shopMoney { amount currencyCode } }
}
}
}
}`
export interface OrdersPage {
orders: ShopifyOrder[]
hasNextPage: boolean
endCursor: string | null
}
export interface ListOrdersOptions {
/** ISO timestamp; orders with updated_at >= this are listed. */
updatedAtMin: string
/** Relay cursor from the previous page's endCursor, or null for page one. */
after: string | null
}
/**
* One page of orders updated on/after the window start, oldest-updated first
* so the caller's cursor advances chronologically. Relay cursor pagination is
* stable across same-second ties, so no offset fallback is needed (unlike the
* WooCommerce client).
*/
export async function listOrdersPage(
session: ShopifySession,
options: ListOrdersOptions,
): Promise<OrdersPage> {
const data = await shopifyGraphQL<{
orders: {
pageInfo: { hasNextPage: boolean; endCursor: string | null }
nodes: ShopifyOrder[]
}
}>(session, ORDERS_QUERY, {
first: SHOPIFY_PAGE_SIZE,
after: options.after,
query: `updated_at:>='${options.updatedAtMin}'`,
})
return {
orders: data.orders.nodes,
hasNextPage: data.orders.pageInfo.hasNextPage,
endCursor: data.orders.pageInfo.endCursor,
}
}
const PROBE_QUERY = `
query ConnectProbe {
shop { name currencyCode }
orders(first: 1) { nodes { legacyResourceId } }
}`
/**
* Verify credentials and read shop metadata. The one-order probe inside the
* query is the authoritative check: it exercises the read_orders scope the
* feed needs, so an app created without that scope fails here (ACCESS_DENIED)
* instead of at 03:15.
*/
export async function testConnectionAndFetchShopInfo(
creds: ShopifyCredentials,
): Promise<ShopifyShopInfo> {
const session = await createShopifySession(creds)
const data = await shopifyGraphQL<{
shop: { name: string | null; currencyCode: string | null }
}>(session, PROBE_QUERY)
return {
name: data.shop?.name ?? null,
currency: data.shop?.currencyCode ? data.shop.currencyCode.toUpperCase() : null,
}
}
@@ -0,0 +1,61 @@
import crypto from 'crypto'
/**
* At-rest encryption for Shopify custom-app client id/secret.
*
* AES-256-GCM with a dedicated env key, mirroring the WooCommerce credential
* store (extensions/general/woocommerce/lib/credentials.ts) and the
* Skatteverket token store: 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
* SHOPIFY_CREDENTIALS_ENCRYPTION_KEY never leaves the environment.
*/
const ALGORITHM = 'aes-256-gcm'
/** Whether the integration is configured on this deployment. */
export function isShopifyConfigured(): boolean {
return Boolean(process.env.SHOPIFY_CREDENTIALS_ENCRYPTION_KEY)
}
function getEncryptionKey(): Buffer {
const key = process.env.SHOPIFY_CREDENTIALS_ENCRYPTION_KEY
if (!key) throw new Error('SHOPIFY_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')
}
/** Decrypted API credentials for an active connection. */
export function credentialsOf(connection: {
shop_domain: string
client_id_encrypted: string | null
client_secret_encrypted: string | null
}): { shopDomain: string; clientId: string; clientSecret: string } {
if (!connection.client_id_encrypted || !connection.client_secret_encrypted) {
throw new Error('Connection has no stored credentials')
}
return {
shopDomain: connection.shop_domain,
clientId: decryptCredential(connection.client_id_encrypted),
clientSecret: decryptCredential(connection.client_secret_encrypted),
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,160 @@
/**
* The Shopify settings panel's server calls, each classified into exactly one
* outcome. Same doctrine as the Stripe and WooCommerce panels'
* settings-actions (see the doc blocks 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 probes
* the merchant's store (token exchange + orders probe, with retries), so it
* gets a longer one.
*/
export const SHOPIFY_ACTION_TIMEOUT_MS = 15_000
export const SHOPIFY_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/WooCommerce
* panels. A first sync backfills 90 days 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 SHOPIFY_SYNC_TIMEOUT_MS = 310_000
export type ShopifyRequestResult<T> =
/** 2xx. `data` is null when the body was not readable JSON. */
| { ok: true; data: T | null }
| ActionFailure
export interface ShopifyRequestOptions {
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 shopifyRequest<T>({
url,
method = 'POST',
body,
locale = 'sv',
timeoutMs = SHOPIFY_ACTION_TIMEOUT_MS,
}: ShopifyRequestOptions): Promise<ShopifyRequestResult<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/shopify/sync. */
export interface ShopifySyncPayload {
success?: boolean
/** `ShopifySyncSummary` 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 ShopifySyncOutcome =
/** 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: ShopifySyncPayload | null): ShopifySyncOutcome {
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 } }
}
+19
View File
@@ -0,0 +1,19 @@
{
"id": "shopify",
"sector": "general",
"exportName": "shopifyExtension",
"entryPoint": "@/extensions/general/shopify",
"workspace": null,
"requiredEnvVars": ["SHOPIFY_CREDENTIALS_ENCRYPTION_KEY"],
"optionalEnvVars": [],
"npmDependencies": [],
"definition": {
"name": "Shopify",
"category": "import",
"icon": "ShoppingBag",
"dataPattern": "manual",
"hasOwnData": true,
"description": "Hämta betalda ordrar och återbetalningar från din Shopify-butik till transaktionsinkorgen",
"longDescription": "Anslut din Shopify-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."
}
}
+91
View File
@@ -0,0 +1,91 @@
/** Row shape of public.shopify_connections. */
export interface ShopifyConnection {
id: string
company_id: string
user_id: string
/** Normalized myshopify.com domain, lowercased, no scheme/path. */
shop_domain: string
shop_name: string | null
/**
* Dev Dashboard custom-app credentials (client credentials grant). Shopify
* discontinued revealable admin API tokens for new custom apps on
* 2026-01-01; the merchant pastes the app's client id/secret instead and
* the server exchanges them for a short-lived (24h) access token per run.
*/
client_id_encrypted: string | null
client_secret_encrypted: string | null
status: 'pending' | 'active' | 'revoked' | 'error'
/** ISO 4217 shop currency read at connect time. */
currency: string | null
/** Opt-in: nightly order-feed cron (the manual sync button ignores it). */
transaction_sync_enabled: boolean
/** Order-polling cursor (max updatedAt 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/shopify/status. */
export interface ShopifyStatusResponse {
configured: boolean
connection: Pick<
ShopifyConnection,
| 'id'
| 'status'
| 'shop_domain'
| 'shop_name'
| 'currency'
| 'error_message'
| 'connected_at'
| 'transaction_sync_enabled'
| 'last_order_synced_at'
> | null
}
/**
* GraphQL MoneyBag, shop-currency side only. Amounts are decimal strings in
* major units for every currency (also zero-decimal ones like JPY), so
* parseFloat is correct universally: never divide by 100.
*/
export interface ShopifyMoneyBag {
shopMoney: { amount: string; currencyCode: string }
}
/** Minimal refund shape; Shopify returns refunds inline on the order. */
export interface ShopifyRefund {
legacyResourceId: string
createdAt: string
totalRefundedSet: ShopifyMoneyBag
}
/**
* Minimal GraphQL Admin API order shape consumed by the feed. All timestamps
* are ISO 8601 UTC with a Z suffix.
*/
export interface ShopifyOrder {
/** Numeric order id as a string; stable join key for external_id. */
legacyResourceId: string
/** Display name incl. the # prefix (e.g. "#1042"); plugins can renumber. */
name: string
/** Test-gateway order (dev stores, Bogus Gateway); never real revenue. */
test: boolean
/** When payment was captured; the feed's row date. */
processedAt: string
updatedAt: string
displayFinancialStatus: string | null
/** Gateway display names; join key for gateway-side reconciliation. */
paymentGatewayNames: string[]
/** Grand total actually charged (gross, incl. tax and shipping). */
totalPriceSet: ShopifyMoneyBag
refunds: ShopifyRefund[]
}
/** Shop metadata read at connect time. */
export interface ShopifyShopInfo {
name: string | null
/** ISO 4217 shop currency. */
currency: string | null
}
+3
View File
@@ -32,6 +32,8 @@ export const CAPABILITY = {
stripe_payments: 'stripe_payments',
/** WooCommerce store sync: orders/refunds imported as a transaction feed. */
woocommerce_sync: 'woocommerce_sync',
/** Shopify store sync: orders/refunds imported as a transaction feed. */
shopify_sync: 'shopify_sync',
} as const
export type CapabilityKey = (typeof CAPABILITY)[keyof typeof CAPABILITY]
@@ -58,6 +60,7 @@ export const PAID_CAPABILITIES: readonly CapabilityKey[] = [
CAPABILITY.email_send,
CAPABILITY.stripe_payments,
CAPABILITY.woocommerce_sync,
CAPABILITY.shopify_sync,
] as const
/**
+3
View File
@@ -82,6 +82,9 @@ export type CoreEvent =
// party's API credentials are granted/dropped).
| { type: 'woocommerce.connected'; payload: { connectionId: string; storeUrl: string; userId: string; companyId: string } }
| { type: 'woocommerce.disconnected'; payload: { connectionId: string; storeUrl: string | null; reason: 'user' | 'revoked_upstream'; userId: string; companyId: string } }
// Shopify store lifecycle: same audit doctrine as stripe.*/woocommerce.*.
| { type: 'shopify.connected'; payload: { connectionId: string; shopDomain: string; userId: string; companyId: string } }
| { type: 'shopify.disconnected'; payload: { connectionId: string; shopDomain: string | null; reason: 'user' | 'revoked_upstream'; userId: string; companyId: string } }
// Periods
| { type: 'period.locked'; payload: { period: FiscalPeriod; userId: string; companyId: string } }
| { type: 'period.unlocked'; payload: { period: FiscalPeriod; userId: string; companyId: string } }
+3 -3
View File
@@ -48,8 +48,8 @@ describe('sectors registry', () => {
expect(SECTORS.length).toBe(1)
})
it('should have 16 total extensions', () => {
expect(getAllExtensions().length).toBe(16)
it('should have 17 total extensions', () => {
expect(getAllExtensions().length).toBe(17)
})
it('should have unique slugs within each sector', () => {
@@ -94,7 +94,7 @@ describe('sectors registry', () => {
it('getExtensionsBySector returns extensions for a sector', () => {
const extensions = getExtensionsBySector('general')
expect(extensions.length).toBe(16)
expect(extensions.length).toBe(17)
})
it('all extensions have required fields', () => {
+1
View File
@@ -13,4 +13,5 @@ export const ENABLED_EXTENSION_IDS: ReadonlySet<string> = new Set([
'stripe',
'whatsapp-inbox',
'woocommerce',
'shopify',
])
+2
View File
@@ -12,6 +12,7 @@ import { documentExtractionExtension } from '@/extensions/general/document-extra
import { stripeExtension } from '@/extensions/general/stripe'
import { whatsappInboxExtension } from '@/extensions/general/whatsapp-inbox'
import { woocommerceExtension } from '@/extensions/general/woocommerce'
import { shopifyExtension } from '@/extensions/general/shopify'
export const FIRST_PARTY_EXTENSIONS: Extension[] = [
enableBankingExtension,
@@ -26,4 +27,5 @@ export const FIRST_PARTY_EXTENSIONS: Extension[] = [
stripeExtension,
whatsappInboxExtension,
woocommerceExtension,
shopifyExtension,
]
+11
View File
@@ -158,5 +158,16 @@ export const EXTENSION_DEFINITIONS: Record<string, ExtensionDefinition[]> = {
"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.",
"hasOwnData": true
},
{
"slug": "shopify",
"name": "Shopify",
"sector": "general",
"category": "import",
"icon": "ShoppingBag",
"dataPattern": "manual",
"description": "Hämta betalda ordrar och återbetalningar från din Shopify-butik till transaktionsinkorgen",
"longDescription": "Anslut din Shopify-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.",
"hasOwnData": true
},
],
}
@@ -22,6 +22,9 @@ const SETTINGS_PANELS: Record<string, ComponentType> = {
woocommerce: dynamic(
() => import('@/extensions/general/woocommerce/components/WooCommerceSettingsPanel')
),
shopify: dynamic(
() => import('@/extensions/general/shopify/components/ShopifySettingsPanel')
),
}
/**
+1
View File
@@ -1019,6 +1019,7 @@ export const ARCHIVE_EXCLUDED_TABLES: Record<string, string> = {
'WhatsApp bot conversation state (company_id is only a which-company pin); receipts live in document_attachments',
webhooks: 'automation config with signing secrets',
woocommerce_connections: 'WooCommerce connection state (encrypted API secrets)',
shopify_connections: 'Shopify connection state (encrypted API secrets)',
}
/** Max parent ids per `IN (...)` chunk: keeps the PostgREST URL well under limits. */

Some files were not shown because too many files have changed in this diff Show More