feat(webshop-orders): Orders page with per-store, per-payment-method booking (#1525)
* feat(webshop-orders): schema, types and error codes for the orders surface webshop_orders (order/refund rows, financial-freeze trigger, member select/update RLS, no DELETE) + webshop_store_settings (per-store payment method -> account map), source_type 'webshop_order', multi-store index drop, customer_country, and a one-time woo cursor reset so the switch-over backfills and cross-marks existing feed rows. Tables classified in the full-archive export; pg-real coverage for RLS, freeze and CHECK. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(webshop-orders): core service (ingest, booking lines) upsertWebshopOrders: two-phase order/refund upsert with FX enrichment, legacy-feed cross-marking, frozen-row protection and field-wise jsonb comparisons (Postgres does not preserve object key order). Booking-line builder: per-rate VAT split with SIGNED buckets (discounts book as revenue reductions), refund mirroring, 3740 residual, per-store account prefill, and advisory export/EU + OSS warnings. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(webshop-orders): API routes for list, booking, invoicing and mapping Booking is draft -> atomic claim -> commit (conditional link-back closes the concurrent double-book race; a lost claim cancels the voucher-free draft). Legacy-feed guard honors transactions.is_ignored on both the book and create-invoice paths. Invoice conversion reuses buildInvoiceWriteData for an unnumbered draft with dominant-rate fallback and drift-safe unit prices. Co-Authored-By: Claude Fable 5 <[email protected]> * feat(webshop-orders): Orders page, booking/invoice dialogs and gated nav /orders lists per-store orders with status tabs (server-side filters), exception chips and one action per row. Booking dialog prefills from the per-store payment-method mapping with an opt-in remember; invoice dialog converts to a draft kundfaktura. The Order nav item renders only for companies with an active WooCommerce connection or existing order rows (Shopify deliberately excluded until its sync writes webshop_orders). Co-Authored-By: Claude Fable 5 <[email protected]> * feat(woocommerce): switch the order sync to webshop_orders, multi-store The sync maps rich wc/v3 payloads (billing, line/shipping/fee taxes, refund allocations with parent-prorated VAT fallback) and upserts order rows instead of transactions-inbox rows; already-imported feed rows stay bookable and get cross-marked. Multi-store: several active connections per company, per-store panel cards with the account-mapping editor. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(webshop-orders): decision log entries and ratchet baseline Baseline moves DOWN only: naive-ore-round 638 -> 637 via roundOre adoption; hand-rolled invariants stay at 115 (ACCOUNT_NUMBER_RE imported, not inlined). Co-Authored-By: Claude Fable 5 <[email protected]> * fix(webshop-orders): resolve PR #1525 review findings and CI failures Review batch (Superagent, CodeRabbit, Swedish compliance review): - Mutual-exclusion claims: booking guards invoice_id, invoice link-back guards journal_entry_id AND treats zero matched rows as the conflict it is (409 + rollback), closing both TOCTOU races. - Freeze v2 migration (20260812124858): the link columns themselves are protected: invoice links immutable, journal links clearable only while the entry is still a draft (the booking rollback path). - Scraped orgnr no longer auto-written to customers.org_number; rate fallback applies only on single-VAT-bucket orders; refunds get their own WEBSHOP_ORDER_REFUND_NOT_CONVERTIBLE code; VAT advisories outrank the invoice-mode hint in the booking dialog. - Ingest compares every synced field (billing corrections no longer drop as unchanged); sync guards absent refunds arrays; /sync aggregates per-store results; panel disables all cards while a request runs; orders page separates load failure from empty; account field explains itself. CI: regenerated skills/accounted-api; pg tests restructured for transaction-abort/rollback semantics + freeze-link coverage; unresolvable- expression ceiling 375 -> 378 with documented reason (partial-update payloads in ingest, shapes covered by unit tests). Declined: CodeRabbit docstring-coverage advisory (house style: comments only where the code cannot say it). Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5
parent
89cfa82f2f
commit
c35b2547fb
File diff suppressed because one or more lines are too long
@@ -151,6 +151,7 @@ export default async function DashboardLayout({
|
||||
entitlements,
|
||||
{ data: allSettingsNames },
|
||||
{ data: userPrefs },
|
||||
hasWebshop,
|
||||
] = await Promise.all([
|
||||
supabase.from('companies').select('*').eq('id', companyId).single(),
|
||||
supabase.from('company_members').select('role').eq('company_id', companyId).eq('user_id', user.id).single(),
|
||||
@@ -178,6 +179,22 @@ export default async function DashboardLayout({
|
||||
// preference (Inställningar → Assistenten). Batched here so it costs no
|
||||
// extra round-trip on the dashboard critical path.
|
||||
supabase.from('user_preferences').select('ui_state, hide_assistant_fab').eq('user_id', user.id).maybeSingle(),
|
||||
// Whether the company has a webshop hooked up: an ACTIVE WooCommerce
|
||||
// connection, or already-imported webshop_orders rows (a disconnected
|
||||
// store's orders are accounting underlag and must stay reachable).
|
||||
// Shopify connections deliberately do NOT count until the Shopify sync
|
||||
// is switched from the transactions feed to webshop_orders: gating on
|
||||
// them today would surface a permanently empty Orders page. Two
|
||||
// indexed limit-1 selects, parallel with the batch; accepted cost on
|
||||
// the first-paint path (gates a nav destination, unlike the badge
|
||||
// counts that moved client-side above).
|
||||
Promise.all([
|
||||
supabase.from('woocommerce_connections').select('id').eq('company_id', companyId).eq('status', 'active').limit(1),
|
||||
supabase.from('webshop_orders').select('id').eq('company_id', companyId).limit(1),
|
||||
]).then(
|
||||
([woo, orders]) =>
|
||||
(woo.data?.length ?? 0) > 0 || (orders.data?.length ?? 0) > 0,
|
||||
),
|
||||
])
|
||||
|
||||
// company_id -> current display name for every company the user belongs to.
|
||||
@@ -318,6 +335,7 @@ export default async function DashboardLayout({
|
||||
entityType={entityType}
|
||||
paysSalaries={paysSalaries}
|
||||
dimensionsEnabled={dimensionsEnabled}
|
||||
hasWebshop={hasWebshop}
|
||||
isSandbox={isSandbox}
|
||||
extensionNavItems={getExtensionNavItems()}
|
||||
userName={userProfile?.full_name ?? null}
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ShoppingCart } from 'lucide-react'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { ContextPicker } from '@/components/common/ContextPicker'
|
||||
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { WebshopOrder, WebshopStoreSettings } from '@/types'
|
||||
|
||||
const OrderBookingDialog = dynamic(() => import('@/components/orders/OrderBookingDialog'), {
|
||||
ssr: false,
|
||||
})
|
||||
const CreateInvoiceFromOrderDialog = dynamic(
|
||||
() => import('@/components/orders/CreateInvoiceFromOrderDialog'),
|
||||
{ ssr: false },
|
||||
)
|
||||
|
||||
interface StoreFacet {
|
||||
platform: string
|
||||
store_scope: string
|
||||
store_label: string | null
|
||||
}
|
||||
|
||||
type StatusTab = 'all' | 'unpaid' | 'paid' | 'refunds' | 'booked'
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
/** Server-side query params per status tab (pagination stays correct). */
|
||||
function tabQuery(tab: StatusTab): string {
|
||||
switch (tab) {
|
||||
case 'unpaid':
|
||||
return '&paid=unpaid'
|
||||
case 'paid':
|
||||
return '&paid=paid&booked=unbooked'
|
||||
case 'refunds':
|
||||
return '&row_type=refund'
|
||||
case 'booked':
|
||||
return '&booked=booked'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export default function OrdersPage() {
|
||||
const t = useTranslations('webshop_orders')
|
||||
const { canWrite } = useCanWrite()
|
||||
const [rows, setRows] = useState<WebshopOrder[]>([])
|
||||
const [stores, setStores] = useState<StoreFacet[]>([])
|
||||
const [settings, setSettings] = useState<WebshopStoreSettings[]>([])
|
||||
const [count, setCount] = useState(0)
|
||||
const [loading, setLoading] = useState(true)
|
||||
// A transient fetch failure must not render as "no orders" with a connect
|
||||
// CTA (review finding): failure gets its own retry state.
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [tab, setTab] = useState<StatusTab>('all')
|
||||
const [storeScope, setStoreScope] = useState<string | null>(null)
|
||||
const [page, setPage] = useState(0)
|
||||
const [bookingOrder, setBookingOrder] = useState<WebshopOrder | null>(null)
|
||||
const [invoicingOrder, setInvoicingOrder] = useState<WebshopOrder | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const storeParam = storeScope ? `&store_scope=${encodeURIComponent(storeScope)}` : ''
|
||||
const res = await fetch(
|
||||
`/api/webshop-orders?limit=${PAGE_SIZE}&offset=${page * PAGE_SIZE}${tabQuery(tab)}${storeParam}`,
|
||||
)
|
||||
if (!res.ok) throw new Error(`list failed: ${res.status}`)
|
||||
const json = (await res.json()) as {
|
||||
data: WebshopOrder[]
|
||||
count: number | null
|
||||
stores: StoreFacet[]
|
||||
}
|
||||
setRows(json.data)
|
||||
setCount(json.count ?? json.data.length)
|
||||
setStores(json.stores)
|
||||
setLoadFailed(false)
|
||||
} catch {
|
||||
setRows([])
|
||||
setCount(0)
|
||||
setLoadFailed(true)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [tab, storeScope, page])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
useEffect(() => {
|
||||
fetch('/api/webshop-orders/settings')
|
||||
.then((r) => (r.ok ? r.json() : { data: [] }))
|
||||
.then((json: { data: WebshopStoreSettings[] }) => setSettings(json.data ?? []))
|
||||
.catch(() => setSettings([]))
|
||||
}, [])
|
||||
|
||||
const visibleRows = rows
|
||||
|
||||
const multiStore = stores.length > 1
|
||||
const activeStore = stores.find((s) => s.store_scope === storeScope) ?? null
|
||||
const storeItems = [
|
||||
{ id: 'all', label: t('all_stores') },
|
||||
...stores.map((s) => ({ id: s.store_scope, label: s.store_label || s.store_scope })),
|
||||
]
|
||||
|
||||
const settingsFor = useCallback(
|
||||
(order: WebshopOrder) =>
|
||||
settings.find(
|
||||
(s) => s.platform === order.platform && s.store_scope === order.store_scope,
|
||||
) ?? null,
|
||||
[settings],
|
||||
)
|
||||
|
||||
const tabs: Array<{ key: StatusTab; label: string }> = [
|
||||
{ key: 'all', label: t('tab_all') },
|
||||
{ key: 'unpaid', label: t('tab_unpaid') },
|
||||
{ key: 'paid', label: t('tab_to_book') },
|
||||
{ key: 'refunds', label: t('tab_refunds') },
|
||||
{ key: 'booked', label: t('tab_booked') },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader title={t('title')} />
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
{tabs.map(({ key, label }) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setTab(key)
|
||||
setPage(0)
|
||||
}}
|
||||
className={cn(
|
||||
'rounded-full px-3 py-[5px] text-[13px] transition-colors duration-150',
|
||||
tab === key
|
||||
? 'bg-secondary text-foreground'
|
||||
: 'text-muted-foreground hover:bg-secondary/60 hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="ml-auto">
|
||||
<ContextPicker
|
||||
items={storeItems}
|
||||
value={storeScope ?? 'all'}
|
||||
onChange={(id) => {
|
||||
setStoreScope(id === 'all' ? null : id)
|
||||
setPage(0)
|
||||
}}
|
||||
triggerLabel={
|
||||
activeStore ? activeStore.store_label || activeStore.store_scope : t('all_stores')
|
||||
}
|
||||
ariaLabel={t('store_picker_aria')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
</div>
|
||||
) : loadFailed ? (
|
||||
<div className="space-y-4 py-8 text-center">
|
||||
<p className="text-sm text-muted-foreground">{t('load_failed')}</p>
|
||||
<Button variant="outline" size="sm" onClick={() => void load()}>
|
||||
{t('retry')}
|
||||
</Button>
|
||||
</div>
|
||||
) : visibleRows.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={ShoppingCart}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
actionLabel={t('empty_action')}
|
||||
actionHref="/import?mode=woocommerce"
|
||||
/>
|
||||
) : (
|
||||
<div className="stagger-enter overflow-x-auto">
|
||||
<table className="w-full border-collapse text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={TH_CLASS}>{t('col_date')}</th>
|
||||
<th className={TH_CLASS}>{t('col_order')}</th>
|
||||
{multiStore && <th className={TH_CLASS}>{t('col_store')}</th>}
|
||||
<th className={TH_CLASS}>{t('col_customer')}</th>
|
||||
<th className={TH_CLASS}>{t('col_payment_method')}</th>
|
||||
<th className={cn(TH_CLASS, 'text-right')}>{t('col_total')}</th>
|
||||
<th className={TH_CLASS}>{t('col_status')}</th>
|
||||
<th className={cn(TH_CLASS, 'w-0')} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{visibleRows.map((order) => (
|
||||
<OrderRow
|
||||
key={order.id}
|
||||
order={order}
|
||||
multiStore={multiStore}
|
||||
canWrite={canWrite}
|
||||
onBook={() => setBookingOrder(order)}
|
||||
onInvoice={() => setInvoicingOrder(order)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{count > PAGE_SIZE && (
|
||||
<div className="mt-4 flex items-center justify-between text-[12.5px] text-muted-foreground">
|
||||
<span>
|
||||
{t('pagination', {
|
||||
from: page * PAGE_SIZE + 1,
|
||||
to: Math.min((page + 1) * PAGE_SIZE, count),
|
||||
total: count,
|
||||
})}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={page === 0}
|
||||
onClick={() => setPage((p) => p - 1)}
|
||||
>
|
||||
{t('prev')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={(page + 1) * PAGE_SIZE >= count}
|
||||
onClick={() => setPage((p) => p + 1)}
|
||||
>
|
||||
{t('next')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{bookingOrder && (
|
||||
<OrderBookingDialog
|
||||
open={!!bookingOrder}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setBookingOrder(null)
|
||||
}}
|
||||
order={bookingOrder}
|
||||
storeSettings={settingsFor(bookingOrder)}
|
||||
onBooked={() => {
|
||||
setBookingOrder(null)
|
||||
void load()
|
||||
}}
|
||||
onSettingsSaved={(updated) => {
|
||||
setSettings((prev) => {
|
||||
const rest = prev.filter(
|
||||
(s) => !(s.platform === updated.platform && s.store_scope === updated.store_scope),
|
||||
)
|
||||
return [...rest, updated]
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{invoicingOrder && (
|
||||
<CreateInvoiceFromOrderDialog
|
||||
open={!!invoicingOrder}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setInvoicingOrder(null)
|
||||
}}
|
||||
order={invoicingOrder}
|
||||
onCreated={() => {
|
||||
setInvoicingOrder(null)
|
||||
void load()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function OrderRow({
|
||||
order,
|
||||
multiStore,
|
||||
canWrite,
|
||||
onBook,
|
||||
onInvoice,
|
||||
t,
|
||||
}: {
|
||||
order: WebshopOrder
|
||||
multiStore: boolean
|
||||
canWrite: boolean
|
||||
onBook: () => void
|
||||
onInvoice: () => void
|
||||
t: ReturnType<typeof useTranslations<'webshop_orders'>>
|
||||
}) {
|
||||
const isRefund = order.row_type === 'refund'
|
||||
const booked = order.journal_entry_id !== null
|
||||
const invoiced = order.invoice_id !== null
|
||||
// Cross-marked rows (legacy_transaction_id) keep their action buttons: the
|
||||
// server guard decides (it allows booking once the feed row is booked-
|
||||
// elsewhere-no, ignored-yes) and its 409 message explains what to do.
|
||||
// Hiding the button would be a dead-end soft guard.
|
||||
const bookable = canWrite && !booked && !invoiced && (isRefund || order.is_paid)
|
||||
const invoiceable = canWrite && !isRefund && !booked && !invoiced
|
||||
|
||||
return (
|
||||
<tr className="group transition-colors duration-150 hover:bg-secondary/35">
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums text-muted-foreground')}>
|
||||
{formatDate(order.order_date)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap')}>
|
||||
{isRefund ? (
|
||||
<span className="text-muted-foreground">
|
||||
{t('refund_prefix')} {order.order_number}
|
||||
</span>
|
||||
) : (
|
||||
<span>{order.order_number}</span>
|
||||
)}
|
||||
</td>
|
||||
{multiStore && (
|
||||
<td className={cn(TD_CLASS, 'max-w-[160px] truncate text-muted-foreground')}>
|
||||
{order.store_label || order.store_scope}
|
||||
</td>
|
||||
)}
|
||||
{/* One-line rows (design convention 4): the full beställningsuppgifter
|
||||
(kontaktperson, orgnr, e-post) live in the native tooltip. */}
|
||||
<td
|
||||
className={cn(TD_CLASS, 'max-w-[220px] truncate')}
|
||||
title={
|
||||
[
|
||||
order.customer_company ? order.customer_name : null,
|
||||
order.customer_orgnr,
|
||||
order.customer_email,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ') || undefined
|
||||
}
|
||||
>
|
||||
{order.customer_company || order.customer_name || (
|
||||
<span className="text-muted-foreground">{'–'}</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap text-muted-foreground')}>
|
||||
{order.payment_method_title || order.payment_method || ''}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')}>
|
||||
{formatCurrency(order.total, order.currency)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap')}>
|
||||
<OrderStatus order={order} t={t} />
|
||||
</td>
|
||||
{/* One action per row: Bokför when the money event is bookable, else
|
||||
Skapa faktura for unpaid invoice-flow orders. Two buttons side by
|
||||
side pushed the table past the panel width and the overflow clip
|
||||
swallowed single-button cells. */}
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right')}>
|
||||
{bookable ? (
|
||||
<Button variant="outline" size="sm" onClick={onBook}>
|
||||
{t('action_book')}
|
||||
</Button>
|
||||
) : invoiceable ? (
|
||||
<Button variant="outline" size="sm" onClick={onInvoice}>
|
||||
{t('action_create_invoice')}
|
||||
</Button>
|
||||
) : null}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Chips mark exceptions only (design convention 5): booked rows render as
|
||||
* muted text; deviations (unbooked-but-paid, unpaid, legacy overlap, remote
|
||||
* drift) get a Badge.
|
||||
*/
|
||||
function OrderStatus({
|
||||
order,
|
||||
t,
|
||||
}: {
|
||||
order: WebshopOrder
|
||||
t: ReturnType<typeof useTranslations<'webshop_orders'>>
|
||||
}) {
|
||||
if (order.remote_changed_after_freeze) {
|
||||
return <Badge variant="warning">{t('status_remote_changed')}</Badge>
|
||||
}
|
||||
if (order.journal_entry_id) {
|
||||
return <span className="text-xs text-muted-foreground">{t('status_booked')}</span>
|
||||
}
|
||||
if (order.invoice_id) {
|
||||
return (
|
||||
<Link
|
||||
href={`/invoices/${order.invoice_id}`}
|
||||
className="text-xs text-muted-foreground underline decoration-border underline-offset-4 hover:text-foreground"
|
||||
>
|
||||
{t('status_invoiced')}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
if (order.legacy_transaction_id) {
|
||||
return (
|
||||
<Link href="/transactions">
|
||||
<Badge variant="outline">{t('status_in_transactions')}</Badge>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
if (!order.is_paid && order.row_type === 'order') {
|
||||
return <Badge variant="secondary">{t('status_unpaid')}</Badge>
|
||||
}
|
||||
return <Badge variant="warning">{t('status_to_book')}</Badge>
|
||||
}
|
||||
@@ -15,13 +15,13 @@ export const maxDuration = 300
|
||||
/**
|
||||
* GET /api/extensions/woocommerce/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 1680 cash account.
|
||||
* upserts each connected store's orders and refunds into webshop_orders
|
||||
* (the Orders page), replacing the earlier transactions-inbox feed.
|
||||
*
|
||||
* 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.
|
||||
* unbooked; booking stays a human decision on the Orders page. Idempotent via
|
||||
* the (company_id, external_id) unique index; overlap re-polls become status
|
||||
* updates. Emits no events, so no ensureInitialized() is needed.
|
||||
*/
|
||||
export const GET = withCronContext('cron.woocommerce_order_sync', async (_request, ctx) => {
|
||||
// Physical routes under app/api/extensions/<id>/ compile into EVERY build,
|
||||
@@ -84,8 +84,8 @@ export const GET = withCronContext('cron.woocommerce_order_sync', async (_reques
|
||||
|
||||
const results: Array<{
|
||||
connectionId: string
|
||||
imported: number
|
||||
duplicates: number
|
||||
inserted: number
|
||||
updated: number
|
||||
status: 'synced' | 'revoked' | 'error'
|
||||
}> = []
|
||||
|
||||
@@ -109,8 +109,8 @@ export const GET = withCronContext('cron.woocommerce_order_sync', async (_reques
|
||||
}
|
||||
results.push({
|
||||
connectionId: connection.id,
|
||||
imported: summary.imported,
|
||||
duplicates: summary.duplicates,
|
||||
inserted: summary.inserted,
|
||||
updated: summary.updated,
|
||||
status: summary.revoked ? 'revoked' : 'synced',
|
||||
})
|
||||
} catch (error) {
|
||||
@@ -120,19 +120,19 @@ export const GET = withCronContext('cron.woocommerce_order_sync', async (_reques
|
||||
})
|
||||
results.push({
|
||||
connectionId: connection.id,
|
||||
imported: 0,
|
||||
duplicates: 0,
|
||||
inserted: 0,
|
||||
updated: 0,
|
||||
status: 'error',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const totalImported = results.reduce((acc, r) => acc + r.imported, 0)
|
||||
const totalInserted = results.reduce((acc, r) => acc + r.inserted, 0)
|
||||
ctx.log.info('woocommerce order sync summary', {
|
||||
processed: results.length,
|
||||
totalImported,
|
||||
totalInserted,
|
||||
failed: results.filter((r) => r.status === 'error').length,
|
||||
})
|
||||
|
||||
return NextResponse.json({ processed: results.length, imported: totalImported, results })
|
||||
return NextResponse.json({ processed: results.length, inserted: totalInserted, results })
|
||||
})
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { createDraftEntry, commitEntry } from '@/lib/bookkeeping/engine'
|
||||
import { bookkeepingErrorResponse } from '@/lib/bookkeeping/errors'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { BookWebshopOrderSchema } from '@/lib/api/schemas'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import type { Currency, WebshopOrder } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
/**
|
||||
* Book one webshop order/refund row as a verifikat. The dialog sends the
|
||||
* (user-reviewed) lines built by lib/webshop-orders/booking-lines; the server
|
||||
* re-guards state and routes everything through the engine
|
||||
* (source_type 'webshop_order'). Period/company locks and balance are
|
||||
* enforced by the engine + DB triggers as usual.
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'webshop_order.book',
|
||||
async (request, { supabase, user, companyId, log, requestId }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const validation = await validateBody(request, BookWebshopOrderSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { fiscal_period_id, entry_date, description, lines, voucher_series, notes } =
|
||||
validation.data
|
||||
|
||||
const { data: order, error: fetchError } = await supabase
|
||||
.from('webshop_orders')
|
||||
.select('*')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single<WebshopOrder>()
|
||||
|
||||
if (fetchError || !order) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_NOT_FOUND', log, { requestId })
|
||||
}
|
||||
|
||||
if (order.journal_entry_id) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_ALREADY_BOOKED', log, {
|
||||
requestId,
|
||||
details: { journal_entry_id: order.journal_entry_id },
|
||||
})
|
||||
}
|
||||
if (order.invoice_id) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_ALREADY_INVOICED', log, {
|
||||
requestId,
|
||||
details: { invoice_id: order.invoice_id },
|
||||
})
|
||||
}
|
||||
// Refunds of an invoiced order belong in the credit-note flow.
|
||||
if (order.row_type === 'refund' && order.parent_order_id) {
|
||||
const { data: parent } = await supabase
|
||||
.from('webshop_orders')
|
||||
.select('invoice_id')
|
||||
.eq('id', order.parent_order_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (parent?.invoice_id) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_REFUND_PARENT_INVOICED', log, {
|
||||
requestId,
|
||||
details: { invoice_id: parent.invoice_id },
|
||||
})
|
||||
}
|
||||
}
|
||||
if (!order.is_paid && order.row_type === 'order') {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_NOT_PAID', log, { requestId })
|
||||
}
|
||||
|
||||
// Double-booking lock against the legacy transactions feed: the same
|
||||
// money event may already sit in the inbox (imported before the Orders
|
||||
// switch-over). A booked feed row means this order IS booked via the
|
||||
// feed; an open one must be booked or IGNORED there first — and an
|
||||
// ignored row (is_ignored) unlocks order-side booking, exactly as the
|
||||
// error message instructs.
|
||||
if (order.legacy_transaction_id) {
|
||||
const { data: legacyTxn } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, journal_entry_id, is_ignored')
|
||||
.eq('id', order.legacy_transaction_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (legacyTxn) {
|
||||
if (legacyTxn.journal_entry_id) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_LEGACY_TRANSACTION_BOOKED', log, {
|
||||
requestId,
|
||||
details: {
|
||||
transaction_id: legacyTxn.id,
|
||||
journal_entry_id: legacyTxn.journal_entry_id,
|
||||
},
|
||||
})
|
||||
}
|
||||
if (!legacyTxn.is_ignored) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_LEGACY_TRANSACTION_OPEN', log, {
|
||||
requestId,
|
||||
details: { transaction_id: legacyTxn.id },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Non-SEK rows book in SEK; retry the rate once at booking time before
|
||||
// refusing (a sync-time Riksbanken hiccup should not strand the order).
|
||||
if (order.currency.toUpperCase() !== 'SEK' && order.total_sek === null) {
|
||||
let resolved = false
|
||||
try {
|
||||
const rate = await fetchExchangeRate(
|
||||
order.currency.toUpperCase() as Currency,
|
||||
new Date(`${order.paid_date ?? order.order_date}T00:00:00Z`),
|
||||
supabase,
|
||||
)
|
||||
if (rate?.rate) {
|
||||
const totalSek = roundOre(order.total * rate.rate)
|
||||
const { error: fxError } = await supabase
|
||||
.from('webshop_orders')
|
||||
.update({ total_sek: totalSek, exchange_rate: rate.rate })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
resolved = !fxError
|
||||
}
|
||||
} catch (err) {
|
||||
log.warn('booking-time FX retry failed', err as Error)
|
||||
}
|
||||
if (!resolved) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_FX_UNRESOLVED', log, {
|
||||
requestId,
|
||||
details: { currency: order.currency },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Race-free booking: draft -> atomic claim -> commit. The read-then-book
|
||||
// pattern let two concurrent requests each post an immutable verifikat
|
||||
// for the same order (skeptic finding). Instead the order row is claimed
|
||||
// with a conditional update BEFORE anything gets a voucher number: the
|
||||
// loser's claim matches zero rows and its draft (no voucher yet, so no
|
||||
// series gap) is cancelled.
|
||||
let draft
|
||||
try {
|
||||
draft = await createDraftEntry(supabase, companyId, user.id, {
|
||||
fiscal_period_id,
|
||||
entry_date,
|
||||
description,
|
||||
source_type: 'webshop_order',
|
||||
source_id: id,
|
||||
voucher_series,
|
||||
notes,
|
||||
lines,
|
||||
})
|
||||
} catch (err) {
|
||||
const typed = bookkeepingErrorResponse(err)
|
||||
if (typed) return typed
|
||||
log.error('failed to draft journal entry for webshop order', err as Error)
|
||||
return NextResponse.json(
|
||||
{ error: getErrorMessage(err, { context: 'transaction' }) },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const cancelDraft = async () => {
|
||||
const { error: cancelError } = await supabase
|
||||
.from('journal_entries')
|
||||
.update({ status: 'cancelled' })
|
||||
.eq('id', draft.id)
|
||||
.eq('status', 'draft')
|
||||
if (cancelError) {
|
||||
log.error('draft cleanup failed after claim/commit failure', cancelError, {
|
||||
entryId: draft.id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The claim guards BOTH links: a concurrent create-invoice between our
|
||||
// read and this update must lose too (mutual exclusivity, not just
|
||||
// no-double-booking).
|
||||
const { data: claimed, error: claimError } = await supabase
|
||||
.from('webshop_orders')
|
||||
.update({ journal_entry_id: draft.id })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.is('journal_entry_id', null)
|
||||
.is('invoice_id', null)
|
||||
.select('id')
|
||||
if (claimError || !claimed || claimed.length === 0) {
|
||||
await cancelDraft()
|
||||
if (claimError) {
|
||||
log.error('webshop order claim failed', claimError, { orderId: id })
|
||||
return NextResponse.json(
|
||||
{ error: getErrorMessage(claimError, { context: 'transaction' }) },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
// Zero rows matched: someone else booked it between our read and claim.
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_ALREADY_BOOKED', log, { requestId })
|
||||
}
|
||||
|
||||
let journalEntry
|
||||
try {
|
||||
journalEntry = await commitEntry(supabase, companyId, user.id, draft.id)
|
||||
} catch (err) {
|
||||
// Unlink so the row does not point at a cancelled draft, then cancel.
|
||||
// Order matters: the financial-freeze trigger keys on journal_entry_id
|
||||
// being set, but journal_entry_id itself is not in its protected list,
|
||||
// so the unlink passes.
|
||||
await supabase
|
||||
.from('webshop_orders')
|
||||
.update({ journal_entry_id: null })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.eq('journal_entry_id', draft.id)
|
||||
await cancelDraft()
|
||||
const typed = bookkeepingErrorResponse(err)
|
||||
if (typed) return typed
|
||||
log.error('failed to commit journal entry for webshop order', err as Error)
|
||||
return NextResponse.json(
|
||||
{ error: getErrorMessage(err, { context: 'transaction' }) },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// No extra event here: commitEntry() already emits
|
||||
// journal_entry.committed from inside the engine.
|
||||
|
||||
return NextResponse.json({
|
||||
data: journalEntry,
|
||||
// commitEntry's post-commit fetch can theoretically return no row;
|
||||
// the entry still exists under draft.id.
|
||||
journal_entry_id: journalEntry?.id ?? draft.id,
|
||||
success: true,
|
||||
})
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,307 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateInvoiceFromWebshopOrderSchema } from '@/lib/api/schemas'
|
||||
import { buildInvoiceWriteData, type InvoiceWriteInput } from '@/lib/invoices/build-invoice-write'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { Currency, Customer, Invoice, WebshopOrder } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
/**
|
||||
* Convert one webshop order into a pre-filled DRAFT kundfaktura. Manual,
|
||||
* per-order, never automatic (invoice-of-record stays the user's decision):
|
||||
* the user reviews the draft and sends it through the normal invoice flow,
|
||||
* which also books it. Follows the invoice-inbox convert pattern: guard
|
||||
* already-converted, map items, reuse the shared invoice write path, link
|
||||
* back, roll back the draft if the link-back fails.
|
||||
*
|
||||
* Numbering: none here (unnumbered draft, save_as_draft semantics). The
|
||||
* F-number is allocated at finalize/send, so an abandoned draft can be
|
||||
* hard-deleted without an F-series gap (ML 17 kap 24§).
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'webshop_order.create_invoice',
|
||||
async (request, { supabase, user, companyId, log, requestId }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const validation = await validateBody(request, CreateInvoiceFromWebshopOrderSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { customer_id } = validation.data
|
||||
|
||||
const { data: order, error: fetchError } = await supabase
|
||||
.from('webshop_orders')
|
||||
.select('*')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single<WebshopOrder>()
|
||||
|
||||
if (fetchError || !order) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_NOT_FOUND', log, { requestId })
|
||||
}
|
||||
if (order.invoice_id) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_ALREADY_INVOICED', log, {
|
||||
requestId,
|
||||
details: { invoice_id: order.invoice_id },
|
||||
})
|
||||
}
|
||||
if (order.journal_entry_id) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_ALREADY_BOOKED', log, {
|
||||
requestId,
|
||||
details: { journal_entry_id: order.journal_entry_id },
|
||||
})
|
||||
}
|
||||
// Refund rows never convert (kreditfaktura is created from the invoice).
|
||||
if (order.row_type === 'refund') {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_REFUND_NOT_CONVERTIBLE', log, { requestId })
|
||||
}
|
||||
// Same legacy double-booking lock as the book route: an invoice created
|
||||
// for a sale whose feed row is later booked in the transactions inbox
|
||||
// would double-count the revenue. An ignored feed row unlocks the path.
|
||||
if (order.legacy_transaction_id) {
|
||||
const { data: legacyTxn } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, journal_entry_id, is_ignored')
|
||||
.eq('id', order.legacy_transaction_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (legacyTxn) {
|
||||
if (legacyTxn.journal_entry_id) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_LEGACY_TRANSACTION_BOOKED', log, {
|
||||
requestId,
|
||||
details: { transaction_id: legacyTxn.id },
|
||||
})
|
||||
}
|
||||
if (!legacyTxn.is_ignored) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_LEGACY_TRANSACTION_OPEN', log, {
|
||||
requestId,
|
||||
details: { transaction_id: legacyTxn.id },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the customer: explicit id, else match by email within the
|
||||
// company, else create from the order's billing snapshot. The orgnr is
|
||||
// best-effort scraped data and is deliberately NOT written to a customer
|
||||
// the user did not review; the dialog shows it as a review hint.
|
||||
let customer: Customer | null = null
|
||||
if (customer_id) {
|
||||
const { data } = await supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('id', customer_id)
|
||||
.eq('company_id', companyId)
|
||||
.single<Customer>()
|
||||
if (!data) {
|
||||
return errorResponseFromCode('CUSTOMER_NOT_FOUND', log, {
|
||||
requestId,
|
||||
details: { customerId: customer_id },
|
||||
})
|
||||
}
|
||||
customer = data
|
||||
} else {
|
||||
if (order.customer_email) {
|
||||
const { data } = await supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.ilike('email', order.customer_email)
|
||||
.limit(1)
|
||||
.maybeSingle<Customer>()
|
||||
customer = data ?? null
|
||||
}
|
||||
if (!customer) {
|
||||
const name = order.customer_company || order.customer_name
|
||||
if (!name) {
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_CREATE_INVOICE_MISSING_CUSTOMER', log, {
|
||||
requestId,
|
||||
})
|
||||
}
|
||||
// The scraped orgnr is deliberately NOT written to the customer's
|
||||
// legal org_number field: it is best-effort store data and must be
|
||||
// user-confirmed on the customer card before it lands anywhere legal
|
||||
// (Swedish compliance review, PR #1525). The dialog shows it as a
|
||||
// review hint.
|
||||
const { data: created, error: createError } = await supabase
|
||||
.from('customers')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
user_id: user.id,
|
||||
name,
|
||||
customer_type: order.customer_company ? 'business' : 'individual',
|
||||
contact_person: order.customer_company ? order.customer_name : null,
|
||||
email: order.customer_email,
|
||||
})
|
||||
.select('*')
|
||||
.single<Customer>()
|
||||
if (createError || !created) {
|
||||
log.error('failed to create customer from webshop order', createError ?? undefined, {
|
||||
orderId: id,
|
||||
})
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_CREATE_INVOICE_CUSTOMER_FAILED', log, {
|
||||
requestId,
|
||||
})
|
||||
}
|
||||
customer = created
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'customer.created',
|
||||
payload: { customer, userId: user.id, companyId },
|
||||
})
|
||||
} catch {
|
||||
// Non-critical
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Items from the order's line snapshot (products + shipping + fees; the
|
||||
// sync stores everything inside order.total). Where the net does not
|
||||
// divide evenly by the quantity, the line collapses to quantity 1 at its
|
||||
// exact total: buildInvoiceWriteData recomputes
|
||||
// line_total = quantity * unit_price, and an öre of division drift would
|
||||
// make the invoice total diverge from what the customer actually paid.
|
||||
// Rate fallback only when the order is UNAMBIGUOUS (a single VAT bucket):
|
||||
// on mixed-rate orders a "dominant" guess could stamp the wrong
|
||||
// tillämpad skattesats on a line (ML 17 kap 24 §); those lines fall back
|
||||
// to the customer-type default and the draft review is the gate.
|
||||
const singleRate =
|
||||
order.vat_breakdown.length === 1 ? order.vat_breakdown[0].rate : undefined
|
||||
const items: InvoiceWriteInput['items'] =
|
||||
order.line_items.length > 0
|
||||
? order.line_items.map((item) => {
|
||||
const unitPrice =
|
||||
item.quantity > 0 ? roundOre(item.total / item.quantity) : item.total
|
||||
const dividesEvenly =
|
||||
item.quantity > 0 && roundOre(unitPrice * item.quantity) === item.total
|
||||
return dividesEvenly
|
||||
? {
|
||||
description: item.name,
|
||||
quantity: item.quantity,
|
||||
unit: 'st',
|
||||
unit_price: unitPrice,
|
||||
vat_rate: item.vat_rate ?? singleRate,
|
||||
}
|
||||
: {
|
||||
description:
|
||||
item.quantity > 1 ? `${item.name} (${item.quantity} st)` : item.name,
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: item.total,
|
||||
vat_rate: item.vat_rate ?? singleRate,
|
||||
}
|
||||
})
|
||||
: [
|
||||
{
|
||||
description: `Order ${order.order_number}`,
|
||||
quantity: 1,
|
||||
unit: 'st',
|
||||
unit_price: roundOre(order.total - order.total_tax),
|
||||
vat_rate: singleRate,
|
||||
},
|
||||
]
|
||||
|
||||
const invoiceDate = new Date().toISOString().split('T')[0]
|
||||
const paymentTermsDays = customer.default_payment_terms ?? 30
|
||||
const due = new Date()
|
||||
due.setDate(due.getDate() + paymentTermsDays)
|
||||
const dueDate = due.toISOString().split('T')[0]
|
||||
|
||||
const input: InvoiceWriteInput = {
|
||||
customer_id: customer.id,
|
||||
invoice_date: invoiceDate,
|
||||
due_date: dueDate,
|
||||
currency: order.currency.toUpperCase() as Currency,
|
||||
your_reference: order.customer_name ?? undefined,
|
||||
notes: `Webshoporder ${order.order_number} (${order.store_label || order.store_scope})`,
|
||||
items,
|
||||
}
|
||||
|
||||
const build = await buildInvoiceWriteData({
|
||||
supabase,
|
||||
companyId,
|
||||
customer,
|
||||
documentType: 'invoice',
|
||||
input,
|
||||
})
|
||||
if (!build.ok) {
|
||||
if ('dbError' in build) {
|
||||
log.error('invoice write build failed on a DB lookup', build.dbError as Error)
|
||||
return errorResponse(build.dbError, log, { requestId })
|
||||
}
|
||||
return errorResponseFromCode(build.code, log, { requestId, details: build.details })
|
||||
}
|
||||
|
||||
const { data: invoice, error: invoiceError } = await supabase
|
||||
.from('invoices')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
company_id: companyId,
|
||||
invoice_number: null,
|
||||
...build.invoiceFields,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (invoiceError || !invoice) {
|
||||
log.error('invoice insert from webshop order failed', invoiceError ?? undefined)
|
||||
return errorResponseFromCode('INVOICE_CREATE_INSERT_FAILED', log, {
|
||||
requestId,
|
||||
details: { pgCode: invoiceError?.code },
|
||||
})
|
||||
}
|
||||
|
||||
const itemRows = build.items.map((item) => ({ ...item, invoice_id: invoice.id }))
|
||||
const { error: itemsError } = await supabase.from('invoice_items').insert(itemRows)
|
||||
if (itemsError) {
|
||||
await supabase.from('invoices').delete().eq('id', invoice.id)
|
||||
log.error('invoice items insert failed; rolled back draft', itemsError, {
|
||||
invoiceId: invoice.id,
|
||||
})
|
||||
return errorResponseFromCode('INVOICE_CREATE_ITEMS_FAILED', log, {
|
||||
requestId,
|
||||
details: { pgCode: itemsError.code },
|
||||
})
|
||||
}
|
||||
|
||||
// Link back; roll back the draft on failure so no orphan invoice exists
|
||||
// without its order marked (unnumbered draft: hard delete leaves no gap).
|
||||
// Guards BOTH links (mutual exclusivity with a concurrent booking) and
|
||||
// treats zero matched rows as the conflict it is: another request linked
|
||||
// first, and answering success would leave a duplicate sendable draft.
|
||||
const { data: linked, error: linkError } = await supabase
|
||||
.from('webshop_orders')
|
||||
.update({ invoice_id: invoice.id })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.is('invoice_id', null)
|
||||
.is('journal_entry_id', null)
|
||||
.select('id')
|
||||
if (linkError || !linked || linked.length === 0) {
|
||||
await supabase.from('invoice_items').delete().eq('invoice_id', invoice.id)
|
||||
await supabase.from('invoices').delete().eq('id', invoice.id)
|
||||
log.error('order link-back failed; rolled back draft invoice', linkError ?? undefined, {
|
||||
orderId: id,
|
||||
invoiceId: invoice.id,
|
||||
})
|
||||
if (linkError) return errorResponse(linkError, log, { requestId })
|
||||
// Zero rows matched: the order was invoiced or booked concurrently.
|
||||
return errorResponseFromCode('WEBSHOP_ORDER_ALREADY_INVOICED', log, { requestId })
|
||||
}
|
||||
|
||||
try {
|
||||
await eventBus.emit({
|
||||
type: 'invoice.created',
|
||||
payload: { invoice: invoice as Invoice, userId: user.id, companyId },
|
||||
})
|
||||
} catch {
|
||||
// Non-critical
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: invoice, invoice_id: invoice.id, success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,301 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
createMockRouteParams,
|
||||
createQueuedMockSupabase,
|
||||
makeJournalEntry,
|
||||
} from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset, findCall, findCalls } =
|
||||
createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
const mockCreateDraftEntry = vi.fn()
|
||||
const mockCommitEntry = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
createDraftEntry: (...args: unknown[]) => mockCreateDraftEntry(...args),
|
||||
commitEntry: (...args: unknown[]) => mockCommitEntry(...args),
|
||||
}))
|
||||
|
||||
const mockFetchExchangeRate = vi.fn()
|
||||
vi.mock('@/lib/currency/riksbanken', () => ({
|
||||
fetchExchangeRate: (...args: unknown[]) => mockFetchExchangeRate(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../[id]/book/route'
|
||||
|
||||
const PERIOD_UUID = '550e8400-e29b-41d4-a716-446655440000'
|
||||
|
||||
function makeOrderRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'order-1',
|
||||
company_id: 'company-1',
|
||||
row_type: 'order',
|
||||
parent_order_id: null,
|
||||
external_id: 'woo_butik.example.se_order_1001',
|
||||
order_number: '1001',
|
||||
status: 'processing',
|
||||
is_paid: true,
|
||||
order_date: '2026-08-01',
|
||||
paid_date: '2026-08-01',
|
||||
currency: 'SEK',
|
||||
total: 500,
|
||||
total_tax: 100,
|
||||
total_sek: 500,
|
||||
exchange_rate: 1,
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
line_items: [],
|
||||
payment_method: 'swish',
|
||||
journal_entry_id: null,
|
||||
invoice_id: null,
|
||||
legacy_transaction_id: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const validBody = {
|
||||
fiscal_period_id: PERIOD_UUID,
|
||||
entry_date: '2026-08-01',
|
||||
description: 'Order 1001 (Swish)',
|
||||
lines: [
|
||||
{ account_number: '1930', debit_amount: 500, credit_amount: 0 },
|
||||
{ account_number: '3001', debit_amount: 0, credit_amount: 400 },
|
||||
{ account_number: '2611', debit_amount: 0, credit_amount: 100 },
|
||||
],
|
||||
}
|
||||
|
||||
function postBook(body: unknown = validBody, id = 'order-1') {
|
||||
const request = createMockRequest(`/api/webshop-orders/${id}/book`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
})
|
||||
return POST(request, createMockRouteParams({ id }))
|
||||
}
|
||||
|
||||
describe('POST /api/webshop-orders/[id]/book', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
mockCreateDraftEntry.mockResolvedValue(makeJournalEntry({ id: 'draft-1', status: 'draft' }))
|
||||
mockCommitEntry.mockResolvedValue(makeJournalEntry({ id: 'je-1' }))
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await postBook())
|
||||
expect(status).toBe(401)
|
||||
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 when the caller is a viewer (requireWrite)', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await postBook())
|
||||
expect(status).toBe(403)
|
||||
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 on invalid body', async () => {
|
||||
const { status } = await parseJsonResponse(
|
||||
await postBook({ fiscal_period_id: PERIOD_UUID }),
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the order does not exist for the company', async () => {
|
||||
enqueue({ data: null, error: { message: 'not found' } })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('returns 409 when already booked', async () => {
|
||||
enqueue({ data: makeOrderRow({ journal_entry_id: 'je-9' }) })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_ALREADY_BOOKED')
|
||||
})
|
||||
|
||||
it('returns 409 when linked to an invoice', async () => {
|
||||
enqueue({ data: makeOrderRow({ invoice_id: 'inv-1' }) })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_ALREADY_INVOICED')
|
||||
})
|
||||
|
||||
it('returns 409 for unpaid orders', async () => {
|
||||
enqueue({ data: makeOrderRow({ is_paid: false, paid_date: null }) })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_NOT_PAID')
|
||||
})
|
||||
|
||||
it('returns 409 when the legacy feed transaction is still open', async () => {
|
||||
enqueue({ data: makeOrderRow({ legacy_transaction_id: 'txn-1' }) })
|
||||
enqueue({ data: { id: 'txn-1', journal_entry_id: null, is_ignored: false } })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_LEGACY_TRANSACTION_OPEN')
|
||||
expect(mockCreateDraftEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 409 when the legacy feed transaction is already booked', async () => {
|
||||
enqueue({ data: makeOrderRow({ legacy_transaction_id: 'txn-1' }) })
|
||||
enqueue({ data: { id: 'txn-1', journal_entry_id: 'je-77', is_ignored: false } })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_LEGACY_TRANSACTION_BOOKED')
|
||||
})
|
||||
|
||||
it('books when the legacy feed transaction was IGNORED (the 409 message honored)', async () => {
|
||||
enqueue({ data: makeOrderRow({ legacy_transaction_id: 'txn-1' }) })
|
||||
enqueue({ data: { id: 'txn-1', journal_entry_id: null, is_ignored: true } }) // legacy check
|
||||
enqueue({ data: [{ id: 'order-1' }] }) // claim
|
||||
const { status } = await parseJsonResponse(await postBook())
|
||||
expect(status).toBe(200)
|
||||
expect(mockCommitEntry).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 422 when a non-SEK order has no rate and the retry fails', async () => {
|
||||
enqueue({ data: makeOrderRow({ currency: 'EUR', total_sek: null, exchange_rate: null }) })
|
||||
mockFetchExchangeRate.mockResolvedValue(null)
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(422)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_FX_UNRESOLVED')
|
||||
})
|
||||
|
||||
it('drafts, claims atomically, then commits with source_type webshop_order', async () => {
|
||||
enqueue({ data: makeOrderRow() }) // fetch
|
||||
enqueue({ data: [{ id: 'order-1' }] }) // claim matched one row
|
||||
const { status, body } = await parseJsonResponse<{ journal_entry_id: string }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.journal_entry_id).toBe('je-1')
|
||||
expect(mockCreateDraftEntry).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'company-1',
|
||||
'user-1',
|
||||
expect.objectContaining({
|
||||
source_type: 'webshop_order',
|
||||
source_id: 'order-1',
|
||||
fiscal_period_id: PERIOD_UUID,
|
||||
}),
|
||||
)
|
||||
expect(mockCommitEntry).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'company-1',
|
||||
'user-1',
|
||||
'draft-1',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 409 and cancels the draft when another request wins the claim', async () => {
|
||||
enqueue({ data: makeOrderRow() }) // fetch (sees unbooked)
|
||||
enqueue({ data: [] }) // claim matched ZERO rows: raced
|
||||
enqueue({ data: null }) // draft cancel update
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_ALREADY_BOOKED')
|
||||
expect(mockCommitEntry).not.toHaveBeenCalled()
|
||||
const cancel = findCall('journal_entries', 'update')
|
||||
expect(cancel).toBeDefined()
|
||||
expect((cancel![0] as Record<string, unknown>).status).toBe('cancelled')
|
||||
})
|
||||
|
||||
it('unlinks and cancels the draft when the commit fails', async () => {
|
||||
mockCommitEntry.mockRejectedValueOnce(new Error('period locked'))
|
||||
enqueue({ data: makeOrderRow() }) // fetch
|
||||
enqueue({ data: [{ id: 'order-1' }] }) // claim
|
||||
enqueue({ data: null }) // unlink
|
||||
enqueue({ data: null }) // cancel draft
|
||||
const { status } = await parseJsonResponse(await postBook())
|
||||
expect(status).toBeGreaterThanOrEqual(400)
|
||||
const orderUpdates = findCalls('webshop_orders', 'update')
|
||||
expect(
|
||||
orderUpdates.some(
|
||||
(args) => (args[0] as Record<string, unknown>).journal_entry_id === null,
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('books a refund row whose parent is not invoiced', async () => {
|
||||
enqueue({
|
||||
data: makeOrderRow({
|
||||
row_type: 'refund',
|
||||
parent_order_id: 'parent-1',
|
||||
total: -500,
|
||||
total_sek: -500,
|
||||
}),
|
||||
})
|
||||
enqueue({ data: { invoice_id: null } }) // parent check
|
||||
enqueue({ data: [{ id: 'order-1' }] }) // claim
|
||||
const { status } = await parseJsonResponse(await postBook())
|
||||
expect(status).toBe(200)
|
||||
})
|
||||
|
||||
it('refuses a refund row whose parent was invoiced', async () => {
|
||||
enqueue({
|
||||
data: makeOrderRow({
|
||||
row_type: 'refund',
|
||||
parent_order_id: 'parent-1',
|
||||
total: -500,
|
||||
total_sek: -500,
|
||||
}),
|
||||
})
|
||||
enqueue({ data: { invoice_id: 'inv-5' } })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postBook(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_REFUND_PARENT_INVOICED')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,312 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
createMockRouteParams,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset, findCall } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
const mockBuildInvoiceWriteData = vi.fn()
|
||||
vi.mock('@/lib/invoices/build-invoice-write', () => ({
|
||||
buildInvoiceWriteData: (...args: unknown[]) => mockBuildInvoiceWriteData(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../[id]/create-invoice/route'
|
||||
|
||||
function makeOrderRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'order-1',
|
||||
company_id: 'company-1',
|
||||
row_type: 'order',
|
||||
external_id: 'woo_butik.example.se_order_1001',
|
||||
order_number: '1001',
|
||||
status: 'processing',
|
||||
is_paid: false,
|
||||
order_date: '2026-08-01',
|
||||
paid_date: null,
|
||||
currency: 'SEK',
|
||||
total: 500,
|
||||
total_tax: 100,
|
||||
total_sek: 500,
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
line_items: [
|
||||
{ name: 'Produkt A', quantity: 2, total: 400, total_tax: 100, vat_rate: 25 },
|
||||
],
|
||||
customer_name: 'Test Person',
|
||||
customer_company: 'Testbolaget AB',
|
||||
customer_email: '[email protected]',
|
||||
customer_orgnr: '556677-8899',
|
||||
payment_method: 'bacs',
|
||||
payment_method_title: 'Faktura',
|
||||
journal_entry_id: null,
|
||||
invoice_id: null,
|
||||
legacy_transaction_id: null,
|
||||
store_label: 'Butiken',
|
||||
store_scope: 'butik.example.se',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const okBuild = {
|
||||
ok: true,
|
||||
invoiceFields: {
|
||||
customer_id: 'cust-1',
|
||||
invoice_date: '2026-08-10',
|
||||
due_date: '2026-09-09',
|
||||
currency: 'SEK',
|
||||
subtotal: 400,
|
||||
vat_amount: 100,
|
||||
total: 500,
|
||||
},
|
||||
items: [
|
||||
{
|
||||
sort_order: 0,
|
||||
description: 'Produkt A',
|
||||
quantity: 2,
|
||||
unit: 'st',
|
||||
unit_price: 200,
|
||||
line_total: 400,
|
||||
vat_rate: 25,
|
||||
vat_amount: 100,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
function postCreate(body: unknown = {}, id = 'order-1') {
|
||||
const request = createMockRequest(`/api/webshop-orders/${id}/create-invoice`, {
|
||||
method: 'POST',
|
||||
body,
|
||||
})
|
||||
return POST(request, createMockRouteParams({ id }))
|
||||
}
|
||||
|
||||
describe('POST /api/webshop-orders/[id]/create-invoice', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
mockBuildInvoiceWriteData.mockResolvedValue(okBuild)
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await postCreate())
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when the order is missing', async () => {
|
||||
enqueue({ data: null, error: { message: 'not found' } })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postCreate(),
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('returns 409 when already invoiced', async () => {
|
||||
enqueue({ data: makeOrderRow({ invoice_id: 'inv-1' }) })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postCreate(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_ALREADY_INVOICED')
|
||||
})
|
||||
|
||||
it('returns 409 when already booked', async () => {
|
||||
enqueue({ data: makeOrderRow({ journal_entry_id: 'je-1' }) })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postCreate(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_ALREADY_BOOKED')
|
||||
})
|
||||
|
||||
it('returns 422 when the order carries no customer data and none is chosen', async () => {
|
||||
enqueue({
|
||||
data: makeOrderRow({
|
||||
customer_name: null,
|
||||
customer_company: null,
|
||||
customer_email: null,
|
||||
}),
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postCreate(),
|
||||
)
|
||||
expect(status).toBe(422)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_CREATE_INVOICE_MISSING_CUSTOMER')
|
||||
})
|
||||
|
||||
it('creates an unnumbered draft from a matched customer and links back', async () => {
|
||||
enqueue({ data: makeOrderRow() }) // order fetch
|
||||
enqueue({ data: { id: 'cust-1', name: 'Testbolaget AB', customer_type: 'business' } }) // email match
|
||||
enqueue({ data: { id: 'inv-1', status: 'draft', invoice_number: null } }) // invoices insert
|
||||
enqueue({ data: null }) // invoice_items insert
|
||||
enqueue({ data: [{ id: 'order-1' }] }) // order link-back matched
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ invoice_id: string }>(
|
||||
await postCreate(),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.invoice_id).toBe('inv-1')
|
||||
|
||||
const invoiceInsert = findCall('invoices', 'insert')
|
||||
expect(invoiceInsert).toBeDefined()
|
||||
expect((invoiceInsert![0] as Record<string, unknown>).invoice_number).toBeNull()
|
||||
expect(mockBuildInvoiceWriteData).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ documentType: 'invoice' }),
|
||||
)
|
||||
const linkUpdate = findCall('webshop_orders', 'update')
|
||||
expect(linkUpdate).toBeDefined()
|
||||
expect((linkUpdate![0] as Record<string, unknown>).invoice_id).toBe('inv-1')
|
||||
})
|
||||
|
||||
it('creates a customer from the order billing data when none matches', async () => {
|
||||
enqueue({ data: makeOrderRow() }) // order fetch
|
||||
enqueue({ data: null }) // email match: none
|
||||
enqueue({ data: { id: 'cust-new', name: 'Testbolaget AB', customer_type: 'business' } }) // customer insert
|
||||
enqueue({ data: { id: 'inv-1', status: 'draft', invoice_number: null } })
|
||||
enqueue({ data: null }) // items
|
||||
enqueue({ data: [{ id: 'order-1' }] }) // link-back matched
|
||||
|
||||
const { status } = await parseJsonResponse(await postCreate())
|
||||
expect(status).toBe(200)
|
||||
const customerInsert = findCall('customers', 'insert')
|
||||
expect(customerInsert).toBeDefined()
|
||||
expect(customerInsert![0]).toMatchObject({
|
||||
name: 'Testbolaget AB',
|
||||
customer_type: 'business',
|
||||
contact_person: 'Test Person',
|
||||
})
|
||||
// Scraped orgnr must NOT auto-land on the customer's legal field
|
||||
// (Swedish compliance review): the dialog shows it for manual review.
|
||||
expect(customerInsert![0]).not.toHaveProperty('org_number')
|
||||
})
|
||||
|
||||
it('rolls back the draft when the order link-back fails', async () => {
|
||||
enqueue({ data: makeOrderRow() })
|
||||
enqueue({ data: { id: 'cust-1', name: 'Testbolaget AB' } })
|
||||
enqueue({ data: { id: 'inv-1', status: 'draft', invoice_number: null } })
|
||||
enqueue({ data: null }) // items insert ok
|
||||
enqueue({ data: null, error: { message: 'link failed' } }) // link-back DB error
|
||||
enqueue({ data: null }) // items delete
|
||||
enqueue({ data: null }) // invoice delete
|
||||
|
||||
const { status } = await parseJsonResponse(await postCreate())
|
||||
expect(status).toBeGreaterThanOrEqual(500)
|
||||
const deletes = findCall('invoices', 'delete')
|
||||
expect(deletes).toBeDefined()
|
||||
})
|
||||
|
||||
it('refuses refund rows', async () => {
|
||||
enqueue({ data: makeOrderRow({ row_type: 'refund' }) })
|
||||
const { status } = await parseJsonResponse(await postCreate())
|
||||
expect(status).toBe(409)
|
||||
})
|
||||
|
||||
it('returns 409 while the legacy feed transaction is open (double-booking lock)', async () => {
|
||||
enqueue({ data: makeOrderRow({ legacy_transaction_id: 'txn-1' }) })
|
||||
enqueue({ data: { id: 'txn-1', journal_entry_id: null, is_ignored: false } })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postCreate(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_LEGACY_TRANSACTION_OPEN')
|
||||
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('creates the draft when the legacy feed transaction was ignored', async () => {
|
||||
enqueue({ data: makeOrderRow({ legacy_transaction_id: 'txn-1' }) })
|
||||
enqueue({ data: { id: 'txn-1', journal_entry_id: null, is_ignored: true } })
|
||||
enqueue({ data: { id: 'cust-1', name: 'Testbolaget AB' } }) // email match
|
||||
enqueue({ data: { id: 'inv-1', status: 'draft', invoice_number: null } })
|
||||
enqueue({ data: null }) // items
|
||||
enqueue({ data: [{ id: 'order-1' }] }) // link-back matched
|
||||
const { status } = await parseJsonResponse(await postCreate())
|
||||
expect(status).toBe(200)
|
||||
})
|
||||
|
||||
it('returns 409 and rolls back when the link-back matches zero rows (raced)', async () => {
|
||||
enqueue({ data: makeOrderRow() })
|
||||
enqueue({ data: { id: 'cust-1', name: 'Testbolaget AB' } })
|
||||
enqueue({ data: { id: 'inv-1', status: 'draft', invoice_number: null } })
|
||||
enqueue({ data: null }) // items insert ok
|
||||
enqueue({ data: [] }) // link-back matched ZERO rows
|
||||
enqueue({ data: null }) // items delete
|
||||
enqueue({ data: null }) // invoice delete
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await postCreate(),
|
||||
)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error.code).toBe('WEBSHOP_ORDER_ALREADY_INVOICED')
|
||||
expect(findCall('invoices', 'delete')).toBeDefined()
|
||||
})
|
||||
|
||||
it('returns 403 when the caller is a viewer (requireWrite)', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await postCreate())
|
||||
expect(status).toBe(403)
|
||||
expect(mockBuildInvoiceWriteData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('collapses non-divisible lines to quantity 1 and applies the single-bucket rate', async () => {
|
||||
enqueue({
|
||||
data: makeOrderRow({
|
||||
line_items: [
|
||||
{ name: 'Produkt B', quantity: 3, total: 100, total_tax: 25, vat_rate: null },
|
||||
],
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
}),
|
||||
})
|
||||
enqueue({ data: { id: 'cust-1', name: 'Testbolaget AB' } })
|
||||
enqueue({ data: { id: 'inv-1', status: 'draft', invoice_number: null } })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: [{ id: 'order-1' }] })
|
||||
const { status } = await parseJsonResponse(await postCreate())
|
||||
expect(status).toBe(200)
|
||||
const input = mockBuildInvoiceWriteData.mock.calls[0][0] as {
|
||||
input: { items: Array<Record<string, unknown>> }
|
||||
}
|
||||
// 100/3 does not divide evenly in öre: exact total at quantity 1 instead
|
||||
// of 3 x 33.33 = 99.99 silently shrinking the invoice.
|
||||
expect(input.input.items[0]).toMatchObject({
|
||||
quantity: 1,
|
||||
unit_price: 100,
|
||||
description: 'Produkt B (3 st)',
|
||||
vat_rate: 25,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,195 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset, findCall } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
import { GET as listOrders } from '../route'
|
||||
import { GET as getSettings, PUT as putSettings } from '../settings/route'
|
||||
|
||||
describe('GET /api/webshop-orders', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const response = await listOrders(createMockRequest('/api/webshop-orders'))
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on an invalid filter value', async () => {
|
||||
const response = await listOrders(
|
||||
createMockRequest('/api/webshop-orders?paid=maybe'),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('lists rows with a deduped store facet', async () => {
|
||||
enqueue({
|
||||
data: [{ id: 'o1' }, { id: 'o2' }],
|
||||
count: 2,
|
||||
})
|
||||
enqueue({
|
||||
data: [
|
||||
{ platform: 'woocommerce', store_scope: 'a.se', store_label: 'A' },
|
||||
{ platform: 'woocommerce', store_scope: 'a.se', store_label: 'A' },
|
||||
{ platform: 'woocommerce', store_scope: 'b.se', store_label: 'B' },
|
||||
],
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: unknown[]
|
||||
count: number
|
||||
stores: Array<{ store_scope: string }>
|
||||
}>(await listOrders(createMockRequest('/api/webshop-orders?paid=paid&booked=unbooked')))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(2)
|
||||
expect(body.stores.map((s) => s.store_scope)).toEqual(['a.se', 'b.se'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET|PUT /api/webshop-orders/settings', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated (GET and PUT)', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const getRes = await getSettings(createMockRequest('/api/webshop-orders/settings'))
|
||||
expect(getRes.status).toBe(401)
|
||||
const putRes = await putSettings(
|
||||
createMockRequest('/api/webshop-orders/settings', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'a.se',
|
||||
payment_method_account_map: {},
|
||||
},
|
||||
}),
|
||||
)
|
||||
expect(putRes.status).toBe(401)
|
||||
})
|
||||
|
||||
it('PUT returns 403 for viewers (requireWrite)', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
const res = await putSettings(
|
||||
createMockRequest('/api/webshop-orders/settings', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'a.se',
|
||||
payment_method_account_map: {},
|
||||
},
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('GET returns the stored mappings', async () => {
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'a.se',
|
||||
payment_method_account_map: { swish: { mode: 'book', account: '1930' } },
|
||||
},
|
||||
],
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
||||
await getSettings(createMockRequest('/api/webshop-orders/settings?platform=woocommerce')),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('PUT rejects an invalid account number', async () => {
|
||||
const response = await putSettings(
|
||||
createMockRequest('/api/webshop-orders/settings', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'a.se',
|
||||
payment_method_account_map: { swish: { mode: 'book', account: 'not-an-account' } },
|
||||
},
|
||||
}),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('PUT upserts on (company, platform, store_scope)', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'a.se',
|
||||
payment_method_account_map: { swish: { mode: 'book', account: '1930' } },
|
||||
},
|
||||
})
|
||||
const { status } = await parseJsonResponse(
|
||||
await putSettings(
|
||||
createMockRequest('/api/webshop-orders/settings', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'a.se',
|
||||
payment_method_account_map: {
|
||||
swish: { mode: 'book', account: '1930' },
|
||||
bacs: { mode: 'invoice' },
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
const upsert = findCall('webshop_store_settings', 'upsert')
|
||||
expect(upsert).toBeDefined()
|
||||
expect((upsert![0] as Record<string, unknown>).company_id).toBe('company-1')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateQuery } from '@/lib/api/validate'
|
||||
import { WebshopOrdersListQuerySchema } from '@/lib/api/schemas'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
const DEFAULT_LIMIT = 50
|
||||
|
||||
/**
|
||||
* List webshop order rows for the Orders page, with a store facet for the
|
||||
* per-shop filter. Refund rows are returned inline (they are independent
|
||||
* bookable rows) and grouped client-side under their parent.
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'webshop_order.list',
|
||||
async (request, { supabase, companyId, log, requestId }) => {
|
||||
const validation = validateQuery(request, WebshopOrdersListQuerySchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { platform, store_scope, status, row_type, paid, booked } = validation.data
|
||||
const limit = validation.data.limit ?? DEFAULT_LIMIT
|
||||
const offset = validation.data.offset ?? 0
|
||||
|
||||
let query = supabase
|
||||
.from('webshop_orders')
|
||||
.select('*', { count: 'exact' })
|
||||
.eq('company_id', companyId)
|
||||
.order('order_date', { ascending: false })
|
||||
.order('created_at', { ascending: false })
|
||||
.range(offset, offset + limit - 1)
|
||||
|
||||
if (platform) query = query.eq('platform', platform)
|
||||
if (store_scope) query = query.eq('store_scope', store_scope)
|
||||
if (status) query = query.eq('status', status)
|
||||
if (row_type) query = query.eq('row_type', row_type)
|
||||
if (paid) query = query.eq('is_paid', paid === 'paid')
|
||||
if (booked === 'booked') query = query.not('journal_entry_id', 'is', null)
|
||||
if (booked === 'unbooked') query = query.is('journal_entry_id', null)
|
||||
|
||||
const { data, error, count } = await query
|
||||
if (error) {
|
||||
log.error('failed to list webshop orders', error)
|
||||
return errorResponse(error, log, { requestId })
|
||||
}
|
||||
|
||||
// Store facet for the filter dropdown: cheap distinct over the company's
|
||||
// stores (small cardinality; the select is capped defensively).
|
||||
const { data: facetRows, error: facetError } = await supabase
|
||||
.from('webshop_orders')
|
||||
.select('platform, store_scope, store_label')
|
||||
.eq('company_id', companyId)
|
||||
.eq('row_type', 'order')
|
||||
.order('store_scope')
|
||||
.limit(5000)
|
||||
if (facetError) {
|
||||
log.error('failed to build store facet', facetError)
|
||||
return errorResponse(facetError, log, { requestId })
|
||||
}
|
||||
const seen = new Set<string>()
|
||||
const stores: Array<{ platform: string; store_scope: string; store_label: string | null }> = []
|
||||
for (const row of facetRows ?? []) {
|
||||
const key = `${row.platform}:${row.store_scope}`
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
stores.push(row)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: data ?? [], count, stores })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,66 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { WebshopStoreSettingsUpdateSchema } from '@/lib/api/schemas'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
/**
|
||||
* Per-store payment-method -> account mapping (webshop_store_settings).
|
||||
* The mapping only PREFILLS the booking dialog; nothing here auto-books.
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'webshop_order.settings.read',
|
||||
async (request, { supabase, companyId, log, requestId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const platform = searchParams.get('platform')
|
||||
const storeScope = searchParams.get('store_scope')
|
||||
|
||||
let query = supabase
|
||||
.from('webshop_store_settings')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
if (platform) query = query.eq('platform', platform)
|
||||
if (storeScope) query = query.eq('store_scope', storeScope)
|
||||
|
||||
const { data, error } = await query
|
||||
if (error) {
|
||||
log.error('failed to read webshop store settings', error)
|
||||
return errorResponse(error, log, { requestId })
|
||||
}
|
||||
return NextResponse.json({ data: data ?? [] })
|
||||
},
|
||||
)
|
||||
|
||||
export const PUT = withRouteContext(
|
||||
'webshop_order.settings.update',
|
||||
async (request, { supabase, user, companyId, log, requestId }) => {
|
||||
const validation = await validateBody(request, WebshopStoreSettingsUpdateSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { platform, store_scope, payment_method_account_map } = validation.data
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('webshop_store_settings')
|
||||
.upsert(
|
||||
{
|
||||
company_id: companyId,
|
||||
user_id: user.id,
|
||||
platform,
|
||||
store_scope,
|
||||
payment_method_account_map,
|
||||
},
|
||||
{ onConflict: 'company_id,platform,store_scope' },
|
||||
)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
log.error('failed to upsert webshop store settings', error)
|
||||
return errorResponse(error, log, { requestId })
|
||||
}
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
PanelLeftClose,
|
||||
Library,
|
||||
BookCheck,
|
||||
ShoppingCart,
|
||||
} from 'lucide-react'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { ENABLED_EXTENSION_IDS as _ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
@@ -81,6 +82,10 @@ interface DashboardNavProps {
|
||||
// switched on. Drives visibility of the Kostnadsställen & projekt row:
|
||||
// same mechanism as paysSalaries: fetched by the dashboard layout.
|
||||
dimensionsEnabled?: boolean
|
||||
// Whether the company has a webshop hooked up (active WooCommerce/Shopify
|
||||
// connection, or existing webshop_orders rows). Drives visibility of the
|
||||
// Order row: same mechanism as paysSalaries, fetched by the layout.
|
||||
hasWebshop?: boolean
|
||||
isSandbox?: boolean
|
||||
extensionNavItems?: ExtensionNavItem[]
|
||||
// Signed-in user's full name + email: drives the bottom-left account
|
||||
@@ -101,6 +106,7 @@ type NavLabelKey =
|
||||
| 'kpi'
|
||||
| 'invoice_inbox'
|
||||
| 'invoices'
|
||||
| 'sales_orders'
|
||||
| 'customers'
|
||||
| 'articles'
|
||||
| 'supplier_invoices'
|
||||
@@ -162,6 +168,10 @@ interface NavItem {
|
||||
// company_settings.dimensions_enabled (UI-visibility gate only; the pages
|
||||
// and APIs work regardless, dimensions plan §2).
|
||||
requiresDimensions?: boolean
|
||||
// Webshop surfaces: visible only when the company has an active
|
||||
// WooCommerce/Shopify connection or already-imported order rows.
|
||||
// UI-visibility gate only; the page and APIs work regardless.
|
||||
requiresWebshop?: boolean
|
||||
// Paywall surfaces: hidden unless the active company holds this paid
|
||||
// capability. Cosmetic only, the page and API gates are the real
|
||||
// enforcement; this just keeps the sidebar honest for non-payers.
|
||||
@@ -191,6 +201,11 @@ const navItems: NavItem[] = [
|
||||
{ href: '/transactions', labelKey: 'transactions', icon: ArrowLeftRight, group: 'arbeta' },
|
||||
{ href: '/pending', labelKey: 'review', icon: ClipboardCheck, group: 'arbeta' },
|
||||
{ href: '/invoices', labelKey: 'invoices', icon: ReceiptText, group: 'arbeta' },
|
||||
// Webshop orders: visible only for companies that actually have a webshop
|
||||
// hooked up (active WooCommerce/Shopify connection or existing order rows).
|
||||
// Deliberately NOT capability-gated: a company whose entitlement lapsed
|
||||
// must still reach its already-imported orders (accounting underlag).
|
||||
{ href: '/orders', labelKey: 'sales_orders', icon: ShoppingCart, group: 'arbeta', requiresWebshop: true },
|
||||
{ href: '/supplier-invoices', labelKey: 'supplier_invoices', icon: Wallet, group: 'arbeta' },
|
||||
{ href: '/salary', labelKey: 'salary', icon: HandCoins, group: 'arbeta', employerOnly: true },
|
||||
// Körjournal is deliberately hidden from the nav; the /mileage route stays live.
|
||||
@@ -268,7 +283,7 @@ const groupLabelKey: Record<Exclude<GroupKey, 'top'>, string> = {
|
||||
skatt: 'group_tax',
|
||||
}
|
||||
|
||||
export default function DashboardNav({ companyName: _companyName, entityType, paysSalaries = false, dimensionsEnabled = false, isSandbox = false, extensionNavItems = [], userName = null, userEmail = null, initialUiState }: DashboardNavProps) {
|
||||
export default function DashboardNav({ companyName: _companyName, entityType, paysSalaries = false, dimensionsEnabled = false, hasWebshop = false, isSandbox = false, extensionNavItems = [], userName = null, userEmail = null, initialUiState }: DashboardNavProps) {
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const supabase = useRealtimeSupabase()
|
||||
@@ -485,6 +500,9 @@ export default function DashboardNav({ companyName: _companyName, entityType, pa
|
||||
// Dimension surfaces are hidden until the company opts in via the
|
||||
// bookkeeping settings toggle (company_settings.dimensions_enabled).
|
||||
if (item.requiresDimensions && !dimensionsEnabled) return false
|
||||
// Webshop surfaces are hidden until a store is connected (or order rows
|
||||
// already exist from a since-disconnected store).
|
||||
if (item.requiresWebshop && !hasWebshop) return false
|
||||
// Paywalled surfaces (e.g. the AI-only Dokumentinkorg) are hidden unless
|
||||
// the active company holds the capability. The page + API gates enforce
|
||||
// the paywall; this keeps the sidebar from advertising a dead workspace.
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { VTD_CLASS, VTH_CLASS } from '@/components/ui/dry-table'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import type { WebshopOrder } from '@/types'
|
||||
|
||||
interface CreateInvoiceFromOrderDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
order: WebshopOrder
|
||||
onCreated: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Order -> DRAFT kundfaktura (confirm up front, convention 10): the dialog
|
||||
* states exactly what will happen, the user confirms, and lands in the draft
|
||||
* to review before sending. The customer is matched by e-mail or created from
|
||||
* the order's billing snapshot server-side; the scraped orgnr is shown here
|
||||
* for the user to eyeball since it never auto-lands on legal invoice fields.
|
||||
*/
|
||||
export default function CreateInvoiceFromOrderDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
order,
|
||||
onCreated,
|
||||
}: CreateInvoiceFromOrderDialogProps) {
|
||||
const t = useTranslations('webshop_orders')
|
||||
const locale = useLocale() as ErrorLocale
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const customerLabel =
|
||||
order.customer_company || order.customer_name || t('invoice_no_customer')
|
||||
|
||||
async function handleCreate() {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const res = await fetch(`/api/webshop-orders/${order.id}/create-invoice`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
})
|
||||
const json = (await res.json()) as { invoice_id?: string }
|
||||
if (!res.ok || !json.invoice_id) {
|
||||
toast({
|
||||
title: t('invoice_create_failed'),
|
||||
description: getErrorMessage(json, { statusCode: res.status, locale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({ title: t('invoice_created') })
|
||||
onCreated()
|
||||
router.push(`/invoices/${json.invoice_id}`)
|
||||
} catch {
|
||||
toast({ title: t('invoice_create_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('invoice_title', { number: order.order_number })}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t('invoice_description', { customer: customerLabel })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 text-sm">
|
||||
<div className="space-y-1">
|
||||
<div>{customerLabel}</div>
|
||||
{order.customer_email && (
|
||||
<div className="text-muted-foreground">{order.customer_email}</div>
|
||||
)}
|
||||
{order.customer_orgnr && (
|
||||
<div className="text-muted-foreground">
|
||||
{t('invoice_orgnr_hint', { orgnr: order.customer_orgnr })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{order.line_items.length > 0 && (
|
||||
<table className="w-full border-collapse text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={VTH_CLASS}>{t('invoice_col_item')}</th>
|
||||
<th className={cn(VTH_CLASS, 'text-right')}>{t('invoice_col_amount')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{order.line_items.map((item, index) => (
|
||||
<tr key={index}>
|
||||
<td className={VTD_CLASS}>
|
||||
{item.quantity} × {item.name}
|
||||
</td>
|
||||
<td className={cn(VTD_CLASS, 'text-right tabular-nums')}>
|
||||
{formatCurrency(item.total + item.total_tax, order.currency)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between text-[13px]">
|
||||
<span className="text-muted-foreground">{t('invoice_total')}</span>
|
||||
<span className="tabular-nums">{formatCurrency(order.total, order.currency)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleCreate} disabled={submitting}>
|
||||
{submitting ? t('invoice_creating') : t('invoice_confirm')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import JournalEntryForm, { type FormLine } from '@/components/bookkeeping/JournalEntryForm'
|
||||
import {
|
||||
buildOrderBookingLines,
|
||||
resolveBookingWarnings,
|
||||
resolvePaymentAccount,
|
||||
} from '@/lib/webshop-orders/booking-lines'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { ACCOUNT_NUMBER_RE } from '@/lib/invariants/account-number'
|
||||
import type { WebshopOrder, WebshopStoreSettings } from '@/types'
|
||||
|
||||
interface OrderBookingDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
order: WebshopOrder
|
||||
storeSettings: WebshopStoreSettings | null
|
||||
onBooked: () => void
|
||||
onSettingsSaved: (settings: WebshopStoreSettings) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Books one order/refund row: prefilled lines from the per-store payment-
|
||||
* method mapping, fully editable in the shared JournalEntryForm (manual-base
|
||||
* doctrine: prefill never auto-books). The "remember" opt-in writes the
|
||||
* chosen counter-account back to the store mapping AFTER a successful
|
||||
* booking, mirroring the prefill-plus-explicit-override editor pattern.
|
||||
*/
|
||||
export default function OrderBookingDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
order,
|
||||
storeSettings,
|
||||
onBooked,
|
||||
onSettingsSaved,
|
||||
}: OrderBookingDialogProps) {
|
||||
const t = useTranslations('webshop_orders')
|
||||
const resolved = useMemo(
|
||||
() => resolvePaymentAccount(order, storeSettings),
|
||||
[order, storeSettings],
|
||||
)
|
||||
const [paymentAccount, setPaymentAccount] = useState(resolved.account)
|
||||
const [remember, setRemember] = useState(false)
|
||||
|
||||
const isRefund = order.row_type === 'refund'
|
||||
const fxUnresolved = order.currency.toUpperCase() !== 'SEK' && order.total_sek === null
|
||||
const accountValid = ACCOUNT_NUMBER_RE.test(paymentAccount)
|
||||
|
||||
const initialLines = useMemo<FormLine[] | null>(() => {
|
||||
if (fxUnresolved || !accountValid) return null
|
||||
try {
|
||||
return buildOrderBookingLines({
|
||||
order,
|
||||
settings: storeSettings,
|
||||
paymentAccount,
|
||||
}).map((line) => ({
|
||||
account_number: line.account_number,
|
||||
debit_amount: line.debit_amount ? line.debit_amount.toFixed(2) : '',
|
||||
credit_amount: line.credit_amount ? line.credit_amount.toFixed(2) : '',
|
||||
line_description: line.line_description ?? '',
|
||||
...(line.currency
|
||||
? {
|
||||
currency: line.currency,
|
||||
amount_in_currency: line.amount_in_currency,
|
||||
exchange_rate: line.exchange_rate,
|
||||
}
|
||||
: {}),
|
||||
}))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}, [order, storeSettings, paymentAccount, fxUnresolved, accountValid])
|
||||
|
||||
const methodLabel = order.payment_method_title || order.payment_method || ''
|
||||
|
||||
async function persistMapping() {
|
||||
if (!order.payment_method) return
|
||||
const map = {
|
||||
...(storeSettings?.payment_method_account_map ?? {}),
|
||||
[order.payment_method]: { mode: 'book' as const, account: paymentAccount },
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/api/webshop-orders/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
platform: order.platform,
|
||||
store_scope: order.store_scope,
|
||||
payment_method_account_map: map,
|
||||
}),
|
||||
})
|
||||
if (res.ok) {
|
||||
const json = (await res.json()) as { data: WebshopStoreSettings }
|
||||
onSettingsSaved(json.data)
|
||||
}
|
||||
} catch {
|
||||
// Remember is best-effort; the booking itself already succeeded.
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] max-w-3xl overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{isRefund
|
||||
? t('book_refund_title', { number: order.order_number })
|
||||
: t('book_title', { number: order.order_number })}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{formatDate(order.paid_date ?? order.order_date)}
|
||||
{' · '}
|
||||
{formatCurrency(order.total, order.currency)}
|
||||
{methodLabel ? ` · ${methodLabel}` : ''}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{fxUnresolved ? (
|
||||
<p className="text-sm text-muted-foreground">{t('fx_unresolved')}</p>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* One attn line (convention 6), priority order: a VAT compliance
|
||||
warning always outranks the invoice-mode convenience hint
|
||||
(Swedish review: the hint must never suppress a real
|
||||
cross-border VAT advisory). */}
|
||||
{(() => {
|
||||
const warnings = resolveBookingWarnings(order)
|
||||
if (warnings.length > 0) {
|
||||
return (
|
||||
<p className="attn text-[12.5px]">{t(`warning_${warnings[0]}`)}</p>
|
||||
)
|
||||
}
|
||||
if (resolved.invoiceMode && !isRefund) {
|
||||
return <p className="attn text-[12.5px]">{t('invoice_mode_hint')}</p>
|
||||
}
|
||||
return null
|
||||
})()}
|
||||
<div className="flex flex-wrap items-end gap-4">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="order-payment-account" className="text-xs">
|
||||
{t('payment_account_label')}
|
||||
</Label>
|
||||
<Input
|
||||
id="order-payment-account"
|
||||
value={paymentAccount}
|
||||
onChange={(e) => setPaymentAccount(e.target.value.trim())}
|
||||
inputMode="numeric"
|
||||
maxLength={4}
|
||||
className="w-28 tabular-nums"
|
||||
aria-invalid={!accountValid}
|
||||
aria-describedby={!accountValid ? 'order-payment-account-error' : undefined}
|
||||
/>
|
||||
{!accountValid && (
|
||||
<p
|
||||
id="order-payment-account-error"
|
||||
className="text-xs text-destructive"
|
||||
role="alert"
|
||||
>
|
||||
{t('invalid_account')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{order.payment_method && (
|
||||
<label className="flex items-center gap-2 pb-2 text-[12.5px] text-muted-foreground">
|
||||
<Checkbox
|
||||
checked={remember}
|
||||
onCheckedChange={(v) => setRemember(v === true)}
|
||||
/>
|
||||
{t('remember_account', { method: methodLabel })}
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{initialLines && (
|
||||
<JournalEntryForm
|
||||
key={`${order.id}-${paymentAccount}`}
|
||||
bare
|
||||
initialLines={initialLines}
|
||||
initialDate={order.paid_date ?? order.order_date}
|
||||
initialDescription={
|
||||
isRefund
|
||||
? `Återbetalning order ${order.order_number}`
|
||||
: methodLabel
|
||||
? `Order ${order.order_number} (${methodLabel})`
|
||||
: `Order ${order.order_number}`
|
||||
}
|
||||
sourceType="webshop_order"
|
||||
sourceId={order.id}
|
||||
submitUrl={`/api/webshop-orders/${order.id}/book`}
|
||||
onEntryCreated={() => {
|
||||
if (remember) void persistMapping()
|
||||
onBooked()
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
SettingsGroup,
|
||||
SettingsRow,
|
||||
SettingsRowEnd,
|
||||
SettingsRowNote,
|
||||
SettingsInput,
|
||||
} from '@/components/settings/SettingsRows'
|
||||
import { ACCOUNT_NUMBER_RE } from '@/lib/invariants/account-number'
|
||||
import type { WebshopPaymentMethodPolicy, WebshopPlatform, WebshopStoreSettings } from '@/types'
|
||||
|
||||
interface PaymentMethodMappingFormProps {
|
||||
platform: WebshopPlatform
|
||||
storeScope: string
|
||||
/**
|
||||
* Payment methods observed on this store's orders. Omitted: derived from a
|
||||
* sample of the store's synced orders.
|
||||
*/
|
||||
methods?: Array<{ method: string; title: string | null }>
|
||||
}
|
||||
|
||||
type DraftPolicy = { mode: 'book'; account: string } | { mode: 'invoice' }
|
||||
|
||||
/**
|
||||
* Per-store payment-method -> account mapping (prefill only; never books).
|
||||
* Fönster language: flat hairline rows, save appears only when dirty.
|
||||
* "Faktureras" marks a method as invoice-flow: the booking dialog then nudges
|
||||
* toward Skapa faktura for those orders.
|
||||
*/
|
||||
export function PaymentMethodMappingForm({
|
||||
platform,
|
||||
storeScope,
|
||||
methods,
|
||||
}: PaymentMethodMappingFormProps) {
|
||||
const t = useTranslations('webshop_orders')
|
||||
const { toast } = useToast()
|
||||
const [saved, setSaved] = useState<Record<string, WebshopPaymentMethodPolicy>>({})
|
||||
const [draft, setDraft] = useState<Record<string, DraftPolicy>>({})
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [derivedMethods, setDerivedMethods] = useState<
|
||||
Array<{ method: string; title: string | null }>
|
||||
>([])
|
||||
|
||||
useEffect(() => {
|
||||
if (methods !== undefined) return
|
||||
let cancelled = false
|
||||
fetch(
|
||||
`/api/webshop-orders?platform=${platform}&store_scope=${encodeURIComponent(storeScope)}&limit=200`,
|
||||
)
|
||||
.then((r) => (r.ok ? r.json() : { data: [] }))
|
||||
.then(
|
||||
(json: {
|
||||
data: Array<{ payment_method: string | null; payment_method_title: string | null }>
|
||||
}) => {
|
||||
if (cancelled) return
|
||||
const seen = new Map<string, string | null>()
|
||||
for (const row of json.data ?? []) {
|
||||
if (row.payment_method && !seen.has(row.payment_method)) {
|
||||
seen.set(row.payment_method, row.payment_method_title)
|
||||
}
|
||||
}
|
||||
setDerivedMethods(
|
||||
Array.from(seen.entries()).map(([method, title]) => ({ method, title })),
|
||||
)
|
||||
},
|
||||
)
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [methods, platform, storeScope])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
fetch(
|
||||
`/api/webshop-orders/settings?platform=${platform}&store_scope=${encodeURIComponent(storeScope)}`,
|
||||
)
|
||||
.then((r) => (r.ok ? r.json() : { data: [] }))
|
||||
.then((json: { data: WebshopStoreSettings[] }) => {
|
||||
if (cancelled) return
|
||||
const map = json.data[0]?.payment_method_account_map ?? {}
|
||||
setSaved(map)
|
||||
setDraft(map as Record<string, DraftPolicy>)
|
||||
})
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [platform, storeScope])
|
||||
|
||||
// Methods seen on orders plus any mapped-but-no-longer-seen leftovers.
|
||||
const rows = useMemo(() => {
|
||||
const source = methods ?? derivedMethods
|
||||
const known = new Map(source.map((m) => [m.method, m.title]))
|
||||
for (const method of Object.keys(saved)) {
|
||||
if (!known.has(method)) known.set(method, null)
|
||||
}
|
||||
return Array.from(known.entries()).map(([method, title]) => ({ method, title }))
|
||||
}, [methods, derivedMethods, saved])
|
||||
|
||||
const dirty = useMemo(() => JSON.stringify(draft) !== JSON.stringify(saved), [draft, saved])
|
||||
|
||||
const setMode = (method: string, mode: 'book' | 'invoice') => {
|
||||
setDraft((prev) => {
|
||||
const current = prev[method]
|
||||
if (mode === 'invoice') return { ...prev, [method]: { mode: 'invoice' } }
|
||||
return {
|
||||
...prev,
|
||||
[method]: {
|
||||
mode: 'book',
|
||||
account: current?.mode === 'book' ? current.account : '1680',
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const setAccount = (method: string, account: string) => {
|
||||
setDraft((prev) => ({ ...prev, [method]: { mode: 'book', account } }))
|
||||
}
|
||||
|
||||
const invalid = Object.values(draft).some(
|
||||
(p) => p.mode === 'book' && !ACCOUNT_NUMBER_RE.test(p.account),
|
||||
)
|
||||
|
||||
async function save() {
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await fetch('/api/webshop-orders/settings', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
platform,
|
||||
store_scope: storeScope,
|
||||
payment_method_account_map: draft,
|
||||
}),
|
||||
})
|
||||
if (!res.ok) throw new Error(`save failed: ${res.status}`)
|
||||
const json = (await res.json()) as { data: WebshopStoreSettings }
|
||||
setSaved(json.data.payment_method_account_map)
|
||||
setDraft(json.data.payment_method_account_map as Record<string, DraftPolicy>)
|
||||
toast({ title: t('mapping_saved') })
|
||||
} catch {
|
||||
toast({ title: t('mapping_save_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading || rows.length === 0) return null
|
||||
|
||||
return (
|
||||
<SettingsGroup label={t('mapping_title')}>
|
||||
<p className="px-1 pb-1 text-xs leading-relaxed text-muted-foreground">
|
||||
{t('mapping_intro')}
|
||||
</p>
|
||||
{rows.map(({ method, title }) => {
|
||||
const policy = draft[method]
|
||||
const mode = policy?.mode ?? 'book'
|
||||
const account = policy?.mode === 'book' ? policy.account : ''
|
||||
return (
|
||||
<SettingsRow key={method} label={title || method}>
|
||||
<SettingsRowEnd>
|
||||
<select
|
||||
value={policy ? mode : 'unmapped'}
|
||||
onChange={(e) => {
|
||||
if (e.target.value === 'unmapped') {
|
||||
setDraft((prev) => {
|
||||
const next = { ...prev }
|
||||
delete next[method]
|
||||
return next
|
||||
})
|
||||
} else {
|
||||
setMode(method, e.target.value as 'book' | 'invoice')
|
||||
}
|
||||
}}
|
||||
className="rounded-full border border-border bg-transparent px-3 py-[5px] text-[13px]"
|
||||
aria-label={t('mapping_mode_aria', { method: title || method })}
|
||||
>
|
||||
<option value="unmapped">{t('mapping_mode_unmapped')}</option>
|
||||
<option value="book">{t('mapping_mode_book')}</option>
|
||||
<option value="invoice">{t('mapping_mode_invoice')}</option>
|
||||
</select>
|
||||
{policy?.mode === 'book' && (
|
||||
<SettingsInput
|
||||
value={account}
|
||||
onChange={(e) => setAccount(method, e.target.value.trim())}
|
||||
inputMode="numeric"
|
||||
maxLength={4}
|
||||
className="w-20 text-right tabular-nums"
|
||||
aria-label={t('mapping_account_aria', { method: title || method })}
|
||||
/>
|
||||
)}
|
||||
</SettingsRowEnd>
|
||||
</SettingsRow>
|
||||
)
|
||||
})}
|
||||
<div className="flex items-center justify-between px-1 pt-3">
|
||||
<SettingsRowNote>{t('mapping_note')}</SettingsRowNote>
|
||||
{dirty && (
|
||||
<Button size="sm" onClick={save} disabled={saving || invalid}>
|
||||
{saving ? t('mapping_saving') : t('mapping_save')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
)
|
||||
}
|
||||
@@ -34,6 +34,7 @@ const VISIBLE_SOURCE_TYPES: Array<{ key: JournalEntrySourceType; labelKey: strin
|
||||
{ key: 'salary_payment', labelKey: 'salary_payment' },
|
||||
{ key: 'bank_transaction', labelKey: 'bank_transaction' },
|
||||
{ key: 'reminder_fee', labelKey: 'reminder_fee' },
|
||||
{ key: 'webshop_order', labelKey: 'webshop_order' },
|
||||
{ key: 'vat_settlement', labelKey: 'vat_settlement' },
|
||||
{ key: 'opening_balance', labelKey: 'opening_balance' },
|
||||
{ key: 'year_end', labelKey: 'year_end' },
|
||||
@@ -58,6 +59,7 @@ const SV_LABELS: Record<string, string> = {
|
||||
salary_payment: 'Lön',
|
||||
bank_transaction: 'Banktransaktioner',
|
||||
reminder_fee: 'Påminnelseavgifter',
|
||||
webshop_order: 'Webshopordrar',
|
||||
vat_settlement: 'Momsredovisning',
|
||||
opening_balance: 'Ingående balanser',
|
||||
year_end: 'Bokslut',
|
||||
|
||||
@@ -261,7 +261,7 @@ describe('woocommerce extension routes', () => {
|
||||
it('returns 404 without an active connection', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
supabase.auth.getUser.mockResolvedValue({ data: { user: USER }, error: null })
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: [] })
|
||||
const res = await findRoute('POST', '/sync').handler(
|
||||
makeRequest('POST'),
|
||||
makeContext(supabase),
|
||||
@@ -272,12 +272,15 @@ describe('woocommerce extension routes', () => {
|
||||
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' } })
|
||||
enqueue({ data: [{ id: 'conn-1', status: 'active' }] })
|
||||
vi.mocked(syncWooCommerceOrders).mockResolvedValue({
|
||||
fetched: 3,
|
||||
refundsFetched: 1,
|
||||
imported: 4,
|
||||
duplicates: 0,
|
||||
inserted: 4,
|
||||
updated: 0,
|
||||
unchanged: 0,
|
||||
frozenFlagged: 0,
|
||||
crossMarked: 0,
|
||||
errors: 0,
|
||||
})
|
||||
const res = await findRoute('POST', '/sync').handler(
|
||||
@@ -286,7 +289,7 @@ describe('woocommerce extension routes', () => {
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.transactions.imported).toBe(4)
|
||||
expect(body.transactions.inserted).toBe(4)
|
||||
expect(vi.mocked(syncWooCommerceOrders).mock.calls[0][0]).toEqual({ service: true })
|
||||
})
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,19 +16,19 @@ describe('syncSummary', () => {
|
||||
|
||||
it('reports a deadline-truncated run as partial, never as complete', () => {
|
||||
expect(
|
||||
syncSummary({ transactions: { deadlineReached: true, fetched: 120, imported: 80 } }),
|
||||
syncSummary({ transactions: { deadlineReached: true, fetched: 120, inserted: 80 } }),
|
||||
).toEqual({ reason: 'partial', values: { fetched: 120, imported: 80, errors: 0 } })
|
||||
// Even a zero-fetch truncated run is partial, not "empty": the window was
|
||||
// not exhausted, so claiming the store had nothing would be false.
|
||||
expect(
|
||||
syncSummary({ transactions: { deadlineReached: true, fetched: 0, imported: 0 } }),
|
||||
syncSummary({ transactions: { deadlineReached: true, fetched: 0, inserted: 0 } }),
|
||||
).toEqual({ reason: 'partial', values: { fetched: 0, imported: 0, errors: 0 } })
|
||||
})
|
||||
|
||||
it('a truncated run with row errors keeps both facts', () => {
|
||||
expect(
|
||||
syncSummary({
|
||||
transactions: { deadlineReached: true, fetched: 50, imported: 40, errors: 3 },
|
||||
transactions: { deadlineReached: true, fetched: 50, inserted: 40, errors: 3 },
|
||||
}),
|
||||
).toEqual({ reason: 'partial', values: { fetched: 50, imported: 40, errors: 3 } })
|
||||
})
|
||||
@@ -36,9 +36,9 @@ describe('syncSummary', () => {
|
||||
it('distinguishes empty, errors and feed outcomes', () => {
|
||||
expect(syncSummary({ transactions: { fetched: 0 } })).toEqual({ reason: 'empty' })
|
||||
expect(
|
||||
syncSummary({ transactions: { fetched: 3, imported: 2, errors: 1 } }),
|
||||
syncSummary({ transactions: { fetched: 3, inserted: 2, errors: 1 } }),
|
||||
).toEqual({ reason: 'errors', values: { fetched: 3, imported: 2, errors: 1 } })
|
||||
expect(syncSummary({ transactions: { fetched: 3, imported: 3 } })).toEqual({
|
||||
expect(syncSummary({ transactions: { fetched: 3, inserted: 3 } })).toEqual({
|
||||
reason: 'feed',
|
||||
values: { fetched: 3, imported: 3 },
|
||||
})
|
||||
|
||||
@@ -69,21 +69,27 @@ async function guardConnectPreconditions(auth: AuthedContext): Promise<NextRespo
|
||||
}
|
||||
|
||||
/**
|
||||
* Existing-connection preflight for both connect paths: 409 on an active
|
||||
* connection or a fresh pending handshake, and supersede stale pendings so
|
||||
* their oauth_state can never complete a late callback.
|
||||
* Existing-connection preflight for both connect paths, scoped to the SAME
|
||||
* store: 409 when this store is already actively connected or mid-handshake,
|
||||
* and supersede stale pendings for it so their oauth_state can never
|
||||
* complete a late callback. Other stores are untouched: a company may
|
||||
* connect several stores (multi-store, migration 20260811073422).
|
||||
*/
|
||||
async function blockOrSupersedeExisting(auth: AuthedContext): Promise<NextResponse | null> {
|
||||
async function blockOrSupersedeExisting(
|
||||
auth: AuthedContext,
|
||||
storeUrl: string,
|
||||
): Promise<NextResponse | null> {
|
||||
const { data: existing } = await auth.supabase
|
||||
.from('woocommerce_connections')
|
||||
.select('id, status, created_at')
|
||||
.eq('company_id', auth.companyId)
|
||||
.eq('store_url', storeUrl)
|
||||
.in('status', ['active', 'pending'])
|
||||
.order('created_at', { ascending: false })
|
||||
|
||||
if (existing?.some((c) => c.status === 'active')) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Företaget har redan en ansluten WooCommerce-butik. Koppla från den först.' },
|
||||
{ error: 'Butiken är redan ansluten. Koppla från den först om du vill ansluta om den.' },
|
||||
{ status: 409 },
|
||||
)
|
||||
}
|
||||
@@ -106,6 +112,7 @@ async function blockOrSupersedeExisting(auth: AuthedContext): Promise<NextRespon
|
||||
oauth_state: null,
|
||||
})
|
||||
.eq('company_id', auth.companyId)
|
||||
.eq('store_url', storeUrl)
|
||||
.eq('status', 'pending')
|
||||
}
|
||||
return null
|
||||
@@ -119,19 +126,23 @@ export const woocommerceApiRoutes: ApiRouteDefinition[] = [
|
||||
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 pending/error/revoked states.
|
||||
// Multi-store: every active connection, plus the most recent inactive
|
||||
// row when nothing is active (so the panel can show a pending/error/
|
||||
// revoked state instead of an empty list). `connection` mirrors the
|
||||
// first entry for callers of the old single-store shape.
|
||||
const { data: rows } = await auth.supabase
|
||||
.from('woocommerce_connections')
|
||||
.select(STATUS_COLUMNS)
|
||||
.eq('company_id', auth.companyId)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(10)
|
||||
.limit(25)
|
||||
|
||||
const connection = rows?.find((r) => r.status === 'active') ?? rows?.[0] ?? null
|
||||
const active = (rows ?? []).filter((r) => r.status === 'active')
|
||||
const connections = active.length > 0 ? active : rows?.[0] ? [rows[0]] : []
|
||||
const payload: WooCommerceStatusResponse = {
|
||||
configured: isWooCommerceConfigured(),
|
||||
connection,
|
||||
connection: connections[0] ?? null,
|
||||
connections,
|
||||
}
|
||||
return NextResponse.json(payload)
|
||||
},
|
||||
@@ -168,7 +179,7 @@ export const woocommerceApiRoutes: ApiRouteDefinition[] = [
|
||||
)
|
||||
}
|
||||
|
||||
const conflict = await blockOrSupersedeExisting(auth)
|
||||
const conflict = await blockOrSupersedeExisting(auth, storeUrl)
|
||||
if (conflict) return conflict
|
||||
|
||||
// Persist the CSRF state BEFORE handing the user to the store: the
|
||||
@@ -252,7 +263,7 @@ export const woocommerceApiRoutes: ApiRouteDefinition[] = [
|
||||
)
|
||||
}
|
||||
|
||||
const conflict = await blockOrSupersedeExisting(auth)
|
||||
const conflict = await blockOrSupersedeExisting(auth, storeUrl)
|
||||
if (conflict) return conflict
|
||||
|
||||
// Verify before storing: a typo'd key must fail here, not at 03:45.
|
||||
@@ -335,7 +346,7 @@ export const woocommerceApiRoutes: ApiRouteDefinition[] = [
|
||||
{
|
||||
method: 'POST',
|
||||
path: '/sync',
|
||||
handler: async (_request: Request, ctx?: ExtensionContext) => {
|
||||
handler: async (request: Request, ctx?: ExtensionContext) => {
|
||||
const log = ctx?.log ?? console
|
||||
const auth = await requireUserAndCompany(ctx)
|
||||
if (auth instanceof NextResponse) return auth
|
||||
@@ -355,17 +366,23 @@ export const woocommerceApiRoutes: ApiRouteDefinition[] = [
|
||||
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
|
||||
// the service client (cursor updates and upserts are service paths).
|
||||
// The manual button ignores transaction_sync_enabled (that flag gates
|
||||
// the nightly cron): pressing it IS the opt-in. connection_id targets
|
||||
// one store; omitted, every active store syncs within one time budget.
|
||||
const body = (await request.json().catch(() => ({}))) as { connection_id?: string }
|
||||
let query = auth.supabase
|
||||
.from('woocommerce_connections')
|
||||
.select('*')
|
||||
.eq('company_id', auth.companyId)
|
||||
.eq('status', 'active')
|
||||
.maybeSingle()
|
||||
if (body.connection_id) query = query.eq('id', body.connection_id)
|
||||
const { data: connections } = await query.order('last_order_synced_at', {
|
||||
ascending: true,
|
||||
nullsFirst: true,
|
||||
})
|
||||
|
||||
if (!connection) {
|
||||
if (!connections || connections.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Ingen ansluten WooCommerce-butik.' },
|
||||
{ status: 404 },
|
||||
@@ -378,17 +395,44 @@ export const woocommerceApiRoutes: ApiRouteDefinition[] = [
|
||||
// a slow host 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 syncWooCommerceOrders(
|
||||
serviceClient,
|
||||
connection as WooCommerceConnection,
|
||||
undefined,
|
||||
Date.now() + 240_000,
|
||||
)
|
||||
return NextResponse.json({ success: true, transactions: summary })
|
||||
const deadlineMs = Date.now() + 240_000
|
||||
// One entry per processed store, plus an explicit skipped count:
|
||||
// returning only the last summary hid per-store failures and reported
|
||||
// success for zero work when the deadline expired early.
|
||||
const results: Array<{
|
||||
connection_id: string
|
||||
store_url: string
|
||||
summary: Awaited<ReturnType<typeof syncWooCommerceOrders>>
|
||||
}> = []
|
||||
let skipped = 0
|
||||
for (const connection of connections as WooCommerceConnection[]) {
|
||||
if (Date.now() >= deadlineMs) {
|
||||
skipped += 1
|
||||
continue
|
||||
}
|
||||
const summary = await syncWooCommerceOrders(
|
||||
serviceClient,
|
||||
connection,
|
||||
undefined,
|
||||
deadlineMs,
|
||||
)
|
||||
results.push({
|
||||
connection_id: connection.id,
|
||||
store_url: connection.store_url,
|
||||
summary,
|
||||
})
|
||||
}
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
results,
|
||||
skipped,
|
||||
// Single-store shape kept for the panel's toast summary: the panel
|
||||
// always syncs one connection_id, so this IS that store's summary.
|
||||
transactions: results[results.length - 1]?.summary ?? null,
|
||||
})
|
||||
} catch (error) {
|
||||
log.error('[woocommerce] 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.' },
|
||||
@@ -418,17 +462,21 @@ export const woocommerceApiRoutes: ApiRouteDefinition[] = [
|
||||
})
|
||||
if (!rl.ok) return rl.response!
|
||||
|
||||
const body = (await request.json().catch(() => ({}))) as { enabled?: unknown }
|
||||
const body = (await request.json().catch(() => ({}))) as {
|
||||
enabled?: unknown
|
||||
connection_id?: string
|
||||
}
|
||||
if (typeof body.enabled !== 'boolean') {
|
||||
return NextResponse.json({ error: 'enabled (boolean) krävs.' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: updated, error: updateError } = await auth.supabase
|
||||
let updateQuery = auth.supabase
|
||||
.from('woocommerce_connections')
|
||||
.update({ transaction_sync_enabled: body.enabled })
|
||||
.eq('company_id', auth.companyId)
|
||||
.eq('status', 'active')
|
||||
.select('id')
|
||||
if (body.connection_id) updateQuery = updateQuery.eq('id', body.connection_id)
|
||||
const { data: updated, error: updateError } = await updateQuery.select('id')
|
||||
|
||||
if (updateError) {
|
||||
return NextResponse.json(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -107,12 +107,13 @@ export interface WooSyncPayload {
|
||||
transactions?: {
|
||||
fetched?: number
|
||||
refundsFetched?: number
|
||||
imported?: number
|
||||
duplicates?: number
|
||||
inserted?: number
|
||||
updated?: number
|
||||
unchanged?: number
|
||||
errors?: number
|
||||
revoked?: boolean
|
||||
deadlineReached?: boolean
|
||||
}
|
||||
} | null
|
||||
}
|
||||
|
||||
type SyncCounts = {
|
||||
@@ -148,7 +149,8 @@ export function syncSummary(payload: WooSyncPayload | null): WooSyncSummary {
|
||||
if (typeof summary.fetched !== 'number') return { reason: 'unknown' }
|
||||
|
||||
const fetched = summary.fetched
|
||||
const imported = typeof summary.imported === 'number' ? summary.imported : 0
|
||||
// "imported" in the user-facing sentence = new rows this run (inserts).
|
||||
const imported = typeof summary.inserted === 'number' ? summary.inserted : 0
|
||||
const errors = typeof summary.errors === 'number' ? summary.errors : 0
|
||||
|
||||
if (summary.deadlineReached === true) {
|
||||
|
||||
@@ -25,21 +25,27 @@ export interface WooCommerceConnection {
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/** Connection fields safe for the browser (never encrypted credentials). */
|
||||
export type WooCommerceConnectionStatus = Pick<
|
||||
WooCommerceConnection,
|
||||
| 'id'
|
||||
| 'status'
|
||||
| 'store_url'
|
||||
| 'store_name'
|
||||
| 'currency'
|
||||
| 'error_message'
|
||||
| 'connected_at'
|
||||
| 'transaction_sync_enabled'
|
||||
| 'last_order_synced_at'
|
||||
>
|
||||
|
||||
/** Status payload returned by GET /api/extensions/ext/woocommerce/status. */
|
||||
export interface WooCommerceStatusResponse {
|
||||
configured: boolean
|
||||
connection: Pick<
|
||||
WooCommerceConnection,
|
||||
| 'id'
|
||||
| 'status'
|
||||
| 'store_url'
|
||||
| 'store_name'
|
||||
| 'currency'
|
||||
| 'error_message'
|
||||
| 'connected_at'
|
||||
| 'transaction_sync_enabled'
|
||||
| 'last_order_synced_at'
|
||||
> | null
|
||||
/** First entry of `connections`; kept for the old single-store shape. */
|
||||
connection: WooCommerceConnectionStatus | null
|
||||
/** Multi-store: every active connection (or the latest inactive row). */
|
||||
connections: WooCommerceConnectionStatus[]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,7 +65,7 @@ export interface WooOrder {
|
||||
prices_include_tax: boolean
|
||||
date_created_gmt: string
|
||||
date_modified_gmt: string
|
||||
/** Set when payment completed; the feed's inclusion criterion and row date. */
|
||||
/** Set when payment completed; drives is_paid and the paid date. */
|
||||
date_paid_gmt: string | null
|
||||
payment_method: string
|
||||
payment_method_title: string
|
||||
@@ -67,15 +73,73 @@ export interface WooOrder {
|
||||
transaction_id: string
|
||||
/** Summary of refunds against this order; totals are negative strings. */
|
||||
refunds: Array<{ id: number; reason: string; total: string }>
|
||||
/**
|
||||
* The fields below always ride along in the wc/v3 order payload; the feed
|
||||
* historically discarded them at map time. The Orders page persists them
|
||||
* (customer, per-rate VAT, line snapshot), so the type now keeps them.
|
||||
* All are optional-tolerant at runtime: hardened stores and old WC
|
||||
* versions can serve partial payloads.
|
||||
*/
|
||||
billing?: {
|
||||
first_name?: string
|
||||
last_name?: string
|
||||
company?: string
|
||||
email?: string
|
||||
/** ISO 3166-1 alpha-2 (e.g. 'SE'); drives the 0%-sale export/EU hint. */
|
||||
country?: string
|
||||
}
|
||||
line_items?: Array<{
|
||||
id: number
|
||||
name: string
|
||||
quantity: number
|
||||
/** Line net total after discounts, excl. tax. */
|
||||
total: string
|
||||
total_tax: string
|
||||
taxes?: Array<{ id: number; total: string }>
|
||||
}>
|
||||
tax_lines?: Array<{
|
||||
rate_id: number
|
||||
rate_percent?: number
|
||||
label?: string
|
||||
tax_total: string
|
||||
shipping_tax_total: string
|
||||
}>
|
||||
shipping_lines?: Array<{
|
||||
method_title?: string
|
||||
total: string
|
||||
total_tax: string
|
||||
taxes?: Array<{ id: number; total: string }>
|
||||
}>
|
||||
/** Payment surcharges / plugin fees; part of order.total like shipping. */
|
||||
fee_lines?: Array<{
|
||||
name?: string
|
||||
total: string
|
||||
total_tax: string
|
||||
taxes?: Array<{ id: number; total: string }>
|
||||
}>
|
||||
meta_data?: Array<{ key: string; value: unknown }>
|
||||
}
|
||||
|
||||
/** Minimal wc/v3 order-refund shape (GET /orders/{id}/refunds). */
|
||||
/** wc/v3 order-refund shape (GET /orders/{id}/refunds). */
|
||||
export interface WooRefund {
|
||||
id: number
|
||||
/** Refund amount as a positive string. */
|
||||
amount: string
|
||||
reason: string
|
||||
date_created_gmt: string
|
||||
/**
|
||||
* Per-line refund allocation with NEGATIVE totals, present when the
|
||||
* merchant refunded specific lines. Amount-only refunds ship an empty
|
||||
* array; the sync then prorates VAT from the parent order's breakdown.
|
||||
*/
|
||||
line_items?: Array<{
|
||||
id: number
|
||||
name?: string
|
||||
quantity?: number
|
||||
total: string
|
||||
total_tax: string
|
||||
taxes?: Array<{ id: number; total: string }>
|
||||
}>
|
||||
}
|
||||
|
||||
/** Store metadata read at connect time. */
|
||||
|
||||
@@ -274,6 +274,7 @@ export const JournalEntrySourceTypeSchema = z.enum([
|
||||
'rot_rut_payout',
|
||||
'vat_settlement',
|
||||
'stripe_payout',
|
||||
'webshop_order',
|
||||
])
|
||||
|
||||
/** Query params for GET /api/bookkeeping/voucher-sequences/next. */
|
||||
@@ -1411,6 +1412,51 @@ export const BookTransactionSchema = z
|
||||
path: ['expected_duplicate_journal_entry_id'],
|
||||
})
|
||||
|
||||
// ── Webshop orders (Orders page) ──────────────────────────────
|
||||
|
||||
export const WebshopPlatformSchema = z.enum(['woocommerce', 'shopify'])
|
||||
|
||||
export const WebshopOrdersListQuerySchema = z.object({
|
||||
platform: WebshopPlatformSchema.optional(),
|
||||
store_scope: z.string().max(255).optional(),
|
||||
status: z.string().max(64).optional(),
|
||||
row_type: z.enum(['order', 'refund']).optional(),
|
||||
paid: z.enum(['paid', 'unpaid']).optional(),
|
||||
booked: z.enum(['booked', 'unbooked']).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).optional(),
|
||||
offset: z.coerce.number().int().min(0).optional(),
|
||||
})
|
||||
|
||||
export const BookWebshopOrderSchema = z.object({
|
||||
fiscal_period_id: uuid,
|
||||
entry_date: isoDate,
|
||||
description: z.string().min(1, 'Description is required').max(500),
|
||||
lines: z.array(CreateJournalEntryLineSchema).min(2, 'At least two lines are required'),
|
||||
voucher_series: z
|
||||
.string()
|
||||
.regex(/^[A-Z]$/, 'Verifikationsserie måste vara en bokstav A-Z')
|
||||
.optional(),
|
||||
notes: z.string().max(2000).optional(),
|
||||
})
|
||||
|
||||
export const CreateInvoiceFromWebshopOrderSchema = z.object({
|
||||
/** Omitted: match by email/orgnr within the company, else create. */
|
||||
customer_id: uuid.optional(),
|
||||
})
|
||||
|
||||
/** {"<payment_method>": {mode:'book', account:'1930'} | {mode:'invoice'}} */
|
||||
export const WebshopStoreSettingsUpdateSchema = z.object({
|
||||
platform: WebshopPlatformSchema,
|
||||
store_scope: z.string().min(1).max(255),
|
||||
payment_method_account_map: z.record(
|
||||
z.string().min(1).max(64),
|
||||
z.discriminatedUnion('mode', [
|
||||
z.object({ mode: z.literal('book'), account: accountNumber }),
|
||||
z.object({ mode: z.literal('invoice') }),
|
||||
]),
|
||||
),
|
||||
})
|
||||
|
||||
/**
|
||||
* Edit a bank transaction's title (description). Only the working label:
|
||||
* gated server-side to unbooked, unmatched rows. Trimmed; whitespace-only is
|
||||
|
||||
@@ -3343,6 +3343,80 @@ const NETWORK_TRANSIENT_ENTRY: StructuredErrorEntry = {
|
||||
retryable: true,
|
||||
}
|
||||
|
||||
const WEBSHOP_ORDERS: Record<string, StructuredErrorEntry> = {
|
||||
WEBSHOP_ORDER_NOT_FOUND: {
|
||||
httpStatus: 404,
|
||||
message_sv: 'Ordern hittades inte.',
|
||||
message_en: 'The order was not found.',
|
||||
},
|
||||
WEBSHOP_ORDER_ALREADY_BOOKED: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'Ordern är redan bokförd.',
|
||||
message_en: 'The order is already booked.',
|
||||
},
|
||||
WEBSHOP_ORDER_ALREADY_INVOICED: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Ordern är kopplad till en kundfaktura. Bokföringen sker via fakturaflödet, inte direkt från ordern.',
|
||||
message_en:
|
||||
'The order is linked to a customer invoice. Bookkeeping happens through the invoice flow, not directly from the order.',
|
||||
},
|
||||
WEBSHOP_ORDER_NOT_PAID: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Ordern är inte betald ännu. Obetalda ordrar bokförs när betalningen kommer, eller faktureras via Skapa faktura.',
|
||||
message_en:
|
||||
'The order is not paid yet. Unpaid orders are booked when payment arrives, or invoiced via Create invoice.',
|
||||
},
|
||||
WEBSHOP_ORDER_LEGACY_TRANSACTION_OPEN: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Samma order ligger redan som en obokförd transaktion under Transaktioner (importerad av det tidigare orderflödet). Bokför eller ignorera den transaktionen först, så att samma affärshändelse inte bokförs två gånger.',
|
||||
message_en:
|
||||
'The same order already exists as an unbooked transaction under Transactions (imported by the previous order feed). Book or ignore that transaction first so the same business event is not booked twice.',
|
||||
},
|
||||
WEBSHOP_ORDER_LEGACY_TRANSACTION_BOOKED: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Ordern är redan bokförd via en transaktion under Transaktioner (importerad av det tidigare orderflödet).',
|
||||
message_en:
|
||||
'The order is already booked via a transaction under Transactions (imported by the previous order feed).',
|
||||
},
|
||||
WEBSHOP_ORDER_FX_UNRESOLVED: {
|
||||
httpStatus: 422,
|
||||
message_sv:
|
||||
'Växelkursen för orderns valuta kunde inte hämtas ännu. Försök igen om en stund; ordern kan inte bokföras i SEK utan kurs.',
|
||||
message_en:
|
||||
'The exchange rate for the order currency could not be fetched yet. Try again shortly; the order cannot be booked in SEK without a rate.',
|
||||
},
|
||||
WEBSHOP_ORDER_REFUND_NOT_CONVERTIBLE: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Återbetalningar kan inte omvandlas till fakturor. Hantera återbetalningen med en kreditfaktura från kundfakturan, eller bokför återbetalningsraden direkt.',
|
||||
message_en:
|
||||
'Refunds cannot be converted to invoices. Handle the refund with a credit note from the customer invoice, or book the refund row directly.',
|
||||
},
|
||||
WEBSHOP_ORDER_REFUND_PARENT_INVOICED: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Ordern fakturerades via en kundfaktura. Återbetalningen hanteras med en kreditfaktura, inte genom att bokföra återbetalningsraden direkt.',
|
||||
message_en:
|
||||
'The order was invoiced through a customer invoice. Handle the refund with a credit note instead of booking the refund row directly.',
|
||||
},
|
||||
WEBSHOP_ORDER_CREATE_INVOICE_CUSTOMER_FAILED: {
|
||||
httpStatus: 500,
|
||||
message_sv: 'Kunden kunde inte skapas från orderns uppgifter.',
|
||||
message_en: 'The customer could not be created from the order data.',
|
||||
},
|
||||
WEBSHOP_ORDER_CREATE_INVOICE_MISSING_CUSTOMER: {
|
||||
httpStatus: 422,
|
||||
message_sv:
|
||||
'Ordern saknar kunduppgifter. Välj en befintlig kund att fakturera.',
|
||||
message_en:
|
||||
'The order has no customer data. Choose an existing customer to invoice.',
|
||||
},
|
||||
}
|
||||
|
||||
const NODE_SYSTEM: Record<string, StructuredErrorEntry> = {
|
||||
ECONNREFUSED: NETWORK_TRANSIENT_ENTRY,
|
||||
ECONNRESET: NETWORK_TRANSIENT_ENTRY,
|
||||
@@ -3396,6 +3470,7 @@ const REGISTRY: Record<string, StructuredErrorEntry> = {
|
||||
...BOLAGSVERKET,
|
||||
...ASSETS,
|
||||
...DIMENSION,
|
||||
...WEBSHOP_ORDERS,
|
||||
...NODE_SYSTEM,
|
||||
}
|
||||
|
||||
|
||||
@@ -899,6 +899,10 @@ export const MASTER_DATA_DUMP_TABLES: MasterDataTableSpec[] = [
|
||||
// NOTE: the date column on transactions is `date` (a previous spec said
|
||||
// booking_date, which does not exist: every backup got an error stub).
|
||||
{ name: 'transactions', file: 'transactions.json', orderBy: 'date' },
|
||||
// Webshop order rows are booking underlag (and carry customer personal
|
||||
// data), so they belong in the archive like transactions do.
|
||||
{ name: 'webshop_orders', file: 'webshop_orders.json', orderBy: 'order_date' },
|
||||
{ name: 'webshop_store_settings', file: 'webshop_store_settings.json' },
|
||||
{ name: 'transaction_voucher_links', file: 'transaction_voucher_links.json' },
|
||||
{ name: 'bank_file_imports', file: 'bank_file_imports.json', orderBy: 'created_at' },
|
||||
{ name: 'cash_accounts', file: 'cash_accounts.json' },
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildOrderBookingLines,
|
||||
fallbackVatBreakdown,
|
||||
resolveBookingWarnings,
|
||||
resolvePaymentAccount,
|
||||
DEFAULT_PAYMENT_ACCOUNT,
|
||||
} from '../booking-lines'
|
||||
import type { CreateJournalEntryLineInput, WebshopStoreSettings } from '@/types'
|
||||
|
||||
import { roundOre as round } from '@/lib/money'
|
||||
|
||||
function sumDebits(lines: CreateJournalEntryLineInput[]): number {
|
||||
return round(lines.reduce((sum, l) => sum + l.debit_amount, 0))
|
||||
}
|
||||
function sumCredits(lines: CreateJournalEntryLineInput[]): number {
|
||||
return round(lines.reduce((sum, l) => sum + l.credit_amount, 0))
|
||||
}
|
||||
function lineFor(lines: CreateJournalEntryLineInput[], account: string) {
|
||||
return lines.find((l) => l.account_number === account)
|
||||
}
|
||||
|
||||
const settings: WebshopStoreSettings = {
|
||||
id: 's1',
|
||||
company_id: 'c1',
|
||||
user_id: 'u1',
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'butik.example.se',
|
||||
payment_method_account_map: {
|
||||
swish: { mode: 'book', account: '1930' },
|
||||
klarna_payments: { mode: 'book', account: '1580' },
|
||||
bacs: { mode: 'invoice' },
|
||||
},
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
}
|
||||
|
||||
function makeOrder(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
row_type: 'order' as const,
|
||||
order_number: '1042',
|
||||
payment_method: 'swish',
|
||||
payment_method_title: 'Swish',
|
||||
currency: 'SEK',
|
||||
total: 500,
|
||||
total_tax: 100,
|
||||
total_sek: 500,
|
||||
exchange_rate: 1,
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('resolvePaymentAccount', () => {
|
||||
it('resolves a mapped book-mode account', () => {
|
||||
expect(resolvePaymentAccount(makeOrder(), settings)).toEqual({
|
||||
account: '1930',
|
||||
invoiceMode: false,
|
||||
mapped: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('flags invoice-mode methods', () => {
|
||||
const result = resolvePaymentAccount(makeOrder({ payment_method: 'bacs' }), settings)
|
||||
expect(result.invoiceMode).toBe(true)
|
||||
})
|
||||
|
||||
it('falls back to 1680 when unmapped or without settings', () => {
|
||||
expect(resolvePaymentAccount(makeOrder({ payment_method: 'stripe' }), settings).account).toBe(
|
||||
DEFAULT_PAYMENT_ACCOUNT,
|
||||
)
|
||||
expect(resolvePaymentAccount(makeOrder(), null).account).toBe(DEFAULT_PAYMENT_ACCOUNT)
|
||||
expect(resolvePaymentAccount(makeOrder({ payment_method: null }), settings).mapped).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fallbackVatBreakdown', () => {
|
||||
it('infers 25/12/6 from the tax-to-net ratio', () => {
|
||||
expect(fallbackVatBreakdown(500, 100)).toEqual([{ rate: 25, net: 400, tax: 100 }])
|
||||
expect(fallbackVatBreakdown(112, 12)).toEqual([{ rate: 12, net: 100, tax: 12 }])
|
||||
expect(fallbackVatBreakdown(106, 6)).toEqual([{ rate: 6, net: 100, tax: 6 }])
|
||||
})
|
||||
|
||||
it('returns a 0% bucket for tax-free totals', () => {
|
||||
expect(fallbackVatBreakdown(300, 0)).toEqual([{ rate: 0, net: 300, tax: 0 }])
|
||||
})
|
||||
|
||||
it('falls back to a 25% bucket for unrecognizable mixes', () => {
|
||||
expect(fallbackVatBreakdown(500, 50)).toEqual([{ rate: 25, net: 450, tax: 50 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildOrderBookingLines', () => {
|
||||
it('books a SEK 25% order: gross to mapped account, net to 3001, VAT to 2611', () => {
|
||||
const lines = buildOrderBookingLines({ order: makeOrder(), settings })
|
||||
expect(lines).toHaveLength(3)
|
||||
expect(lineFor(lines, '1930')).toMatchObject({ debit_amount: 500, credit_amount: 0 })
|
||||
expect(lineFor(lines, '3001')).toMatchObject({ debit_amount: 0, credit_amount: 400 })
|
||||
expect(lineFor(lines, '2611')).toMatchObject({ debit_amount: 0, credit_amount: 100 })
|
||||
expect(sumDebits(lines)).toBe(sumCredits(lines))
|
||||
})
|
||||
|
||||
it('splits mixed VAT rates across 3001/3002/3003 + 2611/2621/2631', () => {
|
||||
const lines = buildOrderBookingLines({
|
||||
order: makeOrder({
|
||||
total: 723,
|
||||
total_tax: 87,
|
||||
total_sek: 723,
|
||||
vat_breakdown: [
|
||||
{ rate: 25, net: 300, tax: 75 },
|
||||
{ rate: 12, net: 100, tax: 12 },
|
||||
{ rate: 6, net: 200, tax: 12 },
|
||||
{ rate: 0, net: 24, tax: 0 },
|
||||
],
|
||||
}),
|
||||
settings,
|
||||
})
|
||||
expect(lineFor(lines, '3001')?.credit_amount).toBe(300)
|
||||
expect(lineFor(lines, '3002')?.credit_amount).toBe(100)
|
||||
expect(lineFor(lines, '3003')?.credit_amount).toBe(200)
|
||||
expect(lineFor(lines, '3004')?.credit_amount).toBe(24)
|
||||
expect(lineFor(lines, '2611')?.credit_amount).toBe(75)
|
||||
expect(lineFor(lines, '2621')?.credit_amount).toBe(12)
|
||||
expect(lineFor(lines, '2631')?.credit_amount).toBe(12)
|
||||
expect(sumDebits(lines)).toBe(sumCredits(lines))
|
||||
})
|
||||
|
||||
it('sends rounding residual to 3740 and stays balanced', () => {
|
||||
const lines = buildOrderBookingLines({
|
||||
order: makeOrder({
|
||||
total: 500.05,
|
||||
total_sek: 500.05,
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
}),
|
||||
settings,
|
||||
})
|
||||
expect(lineFor(lines, '3740')?.credit_amount).toBe(0.05)
|
||||
expect(sumDebits(lines)).toBe(sumCredits(lines))
|
||||
})
|
||||
|
||||
it('mirrors refund rows: credit the payment account, debit revenue and VAT', () => {
|
||||
const lines = buildOrderBookingLines({
|
||||
order: makeOrder({
|
||||
row_type: 'refund',
|
||||
total: -500,
|
||||
total_tax: -100,
|
||||
total_sek: -500,
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
}),
|
||||
settings,
|
||||
})
|
||||
expect(lineFor(lines, '1930')).toMatchObject({ debit_amount: 0, credit_amount: 500 })
|
||||
expect(lineFor(lines, '3001')).toMatchObject({ debit_amount: 400, credit_amount: 0 })
|
||||
expect(lineFor(lines, '2611')).toMatchObject({ debit_amount: 100, credit_amount: 0 })
|
||||
expect(sumDebits(lines)).toBe(sumCredits(lines))
|
||||
})
|
||||
|
||||
it('books non-SEK orders in SEK with currency metadata on money lines only', () => {
|
||||
const lines = buildOrderBookingLines({
|
||||
order: makeOrder({
|
||||
currency: 'EUR',
|
||||
total: 100,
|
||||
total_tax: 20,
|
||||
total_sek: 1153,
|
||||
exchange_rate: 11.53,
|
||||
vat_breakdown: [{ rate: 25, net: 80, tax: 20 }],
|
||||
}),
|
||||
settings,
|
||||
})
|
||||
const gross = lineFor(lines, '1930')
|
||||
expect(gross).toMatchObject({
|
||||
debit_amount: 1153,
|
||||
currency: 'EUR',
|
||||
amount_in_currency: 100,
|
||||
exchange_rate: 11.53,
|
||||
})
|
||||
expect(lineFor(lines, '3001')).toMatchObject({
|
||||
credit_amount: round(80 * 11.53),
|
||||
amount_in_currency: 80,
|
||||
})
|
||||
const rounding = lineFor(lines, '3740')
|
||||
if (rounding) expect(rounding.currency).toBeUndefined()
|
||||
expect(sumDebits(lines)).toBe(sumCredits(lines))
|
||||
})
|
||||
|
||||
it('honors an explicit payment-account override from the dialog', () => {
|
||||
const lines = buildOrderBookingLines({
|
||||
order: makeOrder(),
|
||||
settings,
|
||||
paymentAccount: '1686',
|
||||
})
|
||||
expect(lineFor(lines, '1686')?.debit_amount).toBe(500)
|
||||
})
|
||||
|
||||
it('uses the fallback breakdown when the sync produced none', () => {
|
||||
const lines = buildOrderBookingLines({
|
||||
order: makeOrder({ vat_breakdown: [] }),
|
||||
settings,
|
||||
})
|
||||
expect(lineFor(lines, '3001')?.credit_amount).toBe(400)
|
||||
expect(lineFor(lines, '2611')?.credit_amount).toBe(100)
|
||||
expect(sumDebits(lines)).toBe(sumCredits(lines))
|
||||
})
|
||||
|
||||
it('books a NEGATIVE discount bucket on the opposite side, never abs-flipped', () => {
|
||||
// Gift-card/discount plugin: 25% product 500+125, 0% discount -100.
|
||||
// The old abs() logic booked C 3004 100 + D 3740 200: balanced, wrong.
|
||||
const lines = buildOrderBookingLines({
|
||||
order: makeOrder({
|
||||
total: 525,
|
||||
total_tax: 125,
|
||||
total_sek: 525,
|
||||
vat_breakdown: [
|
||||
{ rate: 25, net: 500, tax: 125 },
|
||||
{ rate: 0, net: -100, tax: 0 },
|
||||
],
|
||||
}),
|
||||
settings,
|
||||
})
|
||||
expect(lineFor(lines, '1930')).toMatchObject({ debit_amount: 525 })
|
||||
expect(lineFor(lines, '3001')).toMatchObject({ credit_amount: 500 })
|
||||
expect(lineFor(lines, '2611')).toMatchObject({ credit_amount: 125 })
|
||||
expect(lineFor(lines, '3004')).toMatchObject({ debit_amount: 100, credit_amount: 0 })
|
||||
expect(lineFor(lines, '3740')).toBeUndefined()
|
||||
expect(sumDebits(lines)).toBe(sumCredits(lines))
|
||||
})
|
||||
|
||||
it('throws when a non-SEK order has no resolved SEK amount', () => {
|
||||
expect(() =>
|
||||
buildOrderBookingLines({
|
||||
order: makeOrder({ currency: 'EUR', total_sek: null, exchange_rate: null }),
|
||||
settings,
|
||||
}),
|
||||
).toThrow(/exchange rate/i)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveBookingWarnings', () => {
|
||||
it('flags a 0%-amount to a known non-SE country', () => {
|
||||
expect(
|
||||
resolveBookingWarnings({
|
||||
currency: 'SEK',
|
||||
total_tax: 0,
|
||||
vat_breakdown: [{ rate: 0, net: 2000, tax: 0 }],
|
||||
customer_country: 'NO',
|
||||
}),
|
||||
).toEqual(['zero_rate_foreign'])
|
||||
})
|
||||
|
||||
it('stays quiet for domestic momsfri and unknown countries', () => {
|
||||
expect(
|
||||
resolveBookingWarnings({
|
||||
currency: 'SEK',
|
||||
total_tax: 0,
|
||||
vat_breakdown: [{ rate: 0, net: 2000, tax: 0 }],
|
||||
customer_country: 'SE',
|
||||
}),
|
||||
).toEqual([])
|
||||
expect(
|
||||
resolveBookingWarnings({
|
||||
currency: 'SEK',
|
||||
total_tax: 0,
|
||||
vat_breakdown: [{ rate: 0, net: 2000, tax: 0 }],
|
||||
customer_country: null,
|
||||
}),
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('flags VAT charged on a non-SEK order (OSS check)', () => {
|
||||
expect(
|
||||
resolveBookingWarnings({
|
||||
currency: 'EUR',
|
||||
total_tax: 20,
|
||||
vat_breakdown: [{ rate: 25, net: 80, tax: 20 }],
|
||||
customer_country: 'DK',
|
||||
}),
|
||||
).toEqual(['foreign_vat'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,296 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { upsertWebshopOrders } from '../ingest'
|
||||
import type { WebshopOrderUpsert } from '../types'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
vi.mock('@/lib/currency/riksbanken', () => ({
|
||||
fetchExchangeRate: vi.fn(async (currency: string) =>
|
||||
currency === 'SEK'
|
||||
? { currency, rate: 1, date: '2026-08-01' }
|
||||
: currency === 'EUR'
|
||||
? { currency, rate: 11.5, date: '2026-08-01' }
|
||||
: null,
|
||||
),
|
||||
}))
|
||||
|
||||
const COMPANY = 'company-1'
|
||||
const USER = 'user-1'
|
||||
|
||||
function makeUpsert(overrides: Partial<WebshopOrderUpsert> = {}): WebshopOrderUpsert {
|
||||
return {
|
||||
platform: 'woocommerce',
|
||||
store_scope: 'butik.example.se',
|
||||
store_label: 'Butiken',
|
||||
connection_id: 'conn-1',
|
||||
row_type: 'order',
|
||||
parent_external_id: null,
|
||||
external_id: 'woo_butik.example.se_order_1001',
|
||||
platform_order_id: '1001',
|
||||
order_number: '1001',
|
||||
status: 'processing',
|
||||
is_paid: true,
|
||||
order_date: '2026-08-01',
|
||||
paid_date: '2026-08-01',
|
||||
currency: 'SEK',
|
||||
total: 500,
|
||||
total_tax: 100,
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
line_items: [],
|
||||
customer_name: 'Test Person',
|
||||
customer_company: null,
|
||||
customer_email: '[email protected]',
|
||||
customer_orgnr: null,
|
||||
customer_country: 'SE',
|
||||
payment_method: 'swish',
|
||||
payment_method_title: 'Swish',
|
||||
gateway_reference: null,
|
||||
refunded_total: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function existingRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'row-1',
|
||||
external_id: 'woo_butik.example.se_order_1001',
|
||||
journal_entry_id: null,
|
||||
invoice_id: null,
|
||||
legacy_transaction_id: null,
|
||||
remote_changed_after_freeze: false,
|
||||
total: 500,
|
||||
total_tax: 100,
|
||||
total_sek: 500,
|
||||
exchange_rate: 1,
|
||||
currency: 'SEK',
|
||||
order_date: '2026-08-01',
|
||||
paid_date: '2026-08-01',
|
||||
is_paid: true,
|
||||
payment_method: 'swish',
|
||||
payment_method_title: 'Swish',
|
||||
gateway_reference: null,
|
||||
order_number: '1001',
|
||||
status: 'processing',
|
||||
refunded_total: 0,
|
||||
store_label: 'Butiken',
|
||||
connection_id: 'conn-1',
|
||||
customer_name: 'Test Person',
|
||||
customer_company: null,
|
||||
customer_email: '[email protected]',
|
||||
customer_orgnr: null,
|
||||
customer_country: 'SE',
|
||||
vat_breakdown: [{ rate: 25, net: 400, tax: 100 }],
|
||||
line_items: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('upsertWebshopOrders', () => {
|
||||
let mock: ReturnType<typeof createQueuedMockSupabase>
|
||||
const supabase = () => mock.supabase as unknown as SupabaseClient
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mock = createQueuedMockSupabase()
|
||||
})
|
||||
|
||||
it('inserts a new SEK order with resolved FX and no legacy link', async () => {
|
||||
mock.enqueueMany([
|
||||
{ data: [] }, // existing webshop_orders
|
||||
{ data: [] }, // legacy transactions
|
||||
{ data: [{ id: 'new-1', external_id: 'woo_butik.example.se_order_1001' }] }, // insert
|
||||
])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [makeUpsert()])
|
||||
|
||||
expect(result).toMatchObject({ inserted: 1, updated: 0, errors: 0, crossMarked: 0 })
|
||||
const insertArgs = mock.findCall('webshop_orders', 'insert')
|
||||
expect(insertArgs).toBeDefined()
|
||||
const payload = (insertArgs![0] as Record<string, unknown>[])[0]
|
||||
expect(payload).toMatchObject({
|
||||
company_id: COMPANY,
|
||||
user_id: USER,
|
||||
external_id: 'woo_butik.example.se_order_1001',
|
||||
total_sek: 500,
|
||||
exchange_rate: 1,
|
||||
legacy_transaction_id: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('parents a refund to an order inserted in the same call', async () => {
|
||||
mock.enqueueMany([
|
||||
{ data: [] }, // existing (order phase)
|
||||
{ data: [] }, // legacy (order phase)
|
||||
{ data: [{ id: 'order-id-1', external_id: 'woo_butik.example.se_order_1001' }] },
|
||||
{ data: [] }, // existing (refund phase; parent already known via knownIds)
|
||||
{ data: [] }, // legacy (refund phase)
|
||||
{ data: [{ id: 'refund-id-1', external_id: 'woo_butik.example.se_refund_77' }] },
|
||||
])
|
||||
|
||||
const refund = makeUpsert({
|
||||
row_type: 'refund',
|
||||
parent_external_id: 'woo_butik.example.se_order_1001',
|
||||
external_id: 'woo_butik.example.se_refund_77',
|
||||
platform_order_id: '77',
|
||||
total: -500,
|
||||
total_tax: -100,
|
||||
refunded_total: 0,
|
||||
})
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [
|
||||
refund,
|
||||
makeUpsert(),
|
||||
])
|
||||
|
||||
expect(result.inserted).toBe(2)
|
||||
const inserts = mock.findCalls('webshop_orders', 'insert')
|
||||
expect(inserts).toHaveLength(2)
|
||||
const refundPayload = (inserts[1][0] as Record<string, unknown>[])[0]
|
||||
expect(refundPayload).toMatchObject({
|
||||
row_type: 'refund',
|
||||
parent_order_id: 'order-id-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('cross-marks rows whose external_id already exists in the transactions feed', async () => {
|
||||
mock.enqueueMany([
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'txn-9', external_id: 'woo_butik.example.se_order_1001' }] },
|
||||
{ data: [{ id: 'new-1', external_id: 'woo_butik.example.se_order_1001' }] },
|
||||
])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [makeUpsert()])
|
||||
|
||||
expect(result.crossMarked).toBe(1)
|
||||
const payload = (mock.findCall('webshop_orders', 'insert')![0] as Record<string, unknown>[])[0]
|
||||
expect(payload.legacy_transaction_id).toBe('txn-9')
|
||||
})
|
||||
|
||||
it('updates an unfrozen existing row when status moves', async () => {
|
||||
mock.enqueueMany([
|
||||
{ data: [existingRow()] },
|
||||
{ data: [] },
|
||||
{ data: null }, // update
|
||||
])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [
|
||||
makeUpsert({ status: 'completed' }),
|
||||
])
|
||||
|
||||
expect(result).toMatchObject({ inserted: 0, updated: 1, unchanged: 0 })
|
||||
const updateArgs = mock.findCall('webshop_orders', 'update')
|
||||
expect(updateArgs).toBeDefined()
|
||||
expect((updateArgs![0] as Record<string, unknown>).status).toBe('completed')
|
||||
})
|
||||
|
||||
it('counts an identical re-poll as unchanged without writing', async () => {
|
||||
mock.enqueueMany([{ data: [existingRow()] }, { data: [] }])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [makeUpsert()])
|
||||
|
||||
expect(result).toMatchObject({ inserted: 0, updated: 0, unchanged: 1 })
|
||||
expect(mock.findCall('webshop_orders', 'update')).toBeUndefined()
|
||||
expect(mock.findCall('webshop_orders', 'insert')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('treats jsonb-reordered keys as unchanged (Postgres does not preserve key order)', async () => {
|
||||
// What PostgREST returns: same VALUES, different object key order than
|
||||
// what the sync inserts. JSON.stringify comparison falsely flagged every
|
||||
// such row as changed (and every booked row as remote-drifted).
|
||||
mock.enqueueMany([
|
||||
{
|
||||
data: [
|
||||
existingRow({
|
||||
vat_breakdown: [{ net: 400, tax: 100, rate: 25 }],
|
||||
line_items: [],
|
||||
}),
|
||||
],
|
||||
},
|
||||
{ data: [] },
|
||||
])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [makeUpsert()])
|
||||
|
||||
expect(result).toMatchObject({ unchanged: 1, updated: 0, frozenFlagged: 0 })
|
||||
expect(mock.findCall('webshop_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not flag a booked row when only key order differs', async () => {
|
||||
mock.enqueueMany([
|
||||
{
|
||||
data: [
|
||||
existingRow({
|
||||
journal_entry_id: 'je-1',
|
||||
vat_breakdown: [{ tax: 100, rate: 25, net: 400 }],
|
||||
}),
|
||||
],
|
||||
},
|
||||
{ data: [] },
|
||||
])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [makeUpsert()])
|
||||
|
||||
expect(result.frozenFlagged).toBe(0)
|
||||
expect(mock.findCall('webshop_orders', 'update')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('flags a booked row whose financials drifted instead of updating them', async () => {
|
||||
mock.enqueueMany([
|
||||
{ data: [existingRow({ journal_entry_id: 'je-1' })] },
|
||||
{ data: [] },
|
||||
{ data: null }, // safe-field update
|
||||
])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [
|
||||
makeUpsert({ total: 600, status: 'completed' }),
|
||||
])
|
||||
|
||||
expect(result.frozenFlagged).toBe(1)
|
||||
const update = mock.findCall('webshop_orders', 'update')![0] as Record<string, unknown>
|
||||
expect(update.remote_changed_after_freeze).toBe(true)
|
||||
expect(update.status).toBe('completed')
|
||||
expect(update).not.toHaveProperty('total')
|
||||
expect(update).not.toHaveProperty('total_sek')
|
||||
expect(update).not.toHaveProperty('paid_date')
|
||||
})
|
||||
|
||||
it('leaves total_sek null when the exchange rate cannot resolve', async () => {
|
||||
mock.enqueueMany([
|
||||
{ data: [] },
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'new-1', external_id: 'woo_butik.example.se_order_1001' }] },
|
||||
])
|
||||
|
||||
await upsertWebshopOrders(supabase(), COMPANY, USER, [
|
||||
makeUpsert({ currency: 'ISK', total: 900 }),
|
||||
])
|
||||
|
||||
const payload = (mock.findCall('webshop_orders', 'insert')![0] as Record<string, unknown>[])[0]
|
||||
expect(payload.total_sek).toBeNull()
|
||||
expect(payload.exchange_rate).toBeNull()
|
||||
})
|
||||
|
||||
it('converts non-SEK totals with the fetched rate', async () => {
|
||||
mock.enqueueMany([
|
||||
{ data: [] },
|
||||
{ data: [] },
|
||||
{ data: [{ id: 'new-1', external_id: 'woo_butik.example.se_order_1001' }] },
|
||||
])
|
||||
|
||||
await upsertWebshopOrders(supabase(), COMPANY, USER, [
|
||||
makeUpsert({ currency: 'EUR', total: 100, total_tax: 20 }),
|
||||
])
|
||||
|
||||
const payload = (mock.findCall('webshop_orders', 'insert')![0] as Record<string, unknown>[])[0]
|
||||
expect(payload.total_sek).toBe(1150)
|
||||
expect(payload.exchange_rate).toBe(11.5)
|
||||
})
|
||||
|
||||
it('surfaces select errors without throwing', async () => {
|
||||
mock.enqueueMany([{ data: null, error: { message: 'boom', code: '500' } }])
|
||||
|
||||
const result = await upsertWebshopOrders(supabase(), COMPANY, USER, [makeUpsert()])
|
||||
|
||||
expect(result.errors).toBe(1)
|
||||
expect(result.firstError?.message).toBe('boom')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,251 @@
|
||||
import { roundOre as round } from '@/lib/money'
|
||||
import type {
|
||||
CreateJournalEntryLineInput,
|
||||
WebshopOrder,
|
||||
WebshopStoreSettings,
|
||||
WebshopVatBreakdownLine,
|
||||
} from '@/types'
|
||||
|
||||
/**
|
||||
* Pure builder for the journal lines that PREFILL the order booking dialog.
|
||||
* Never books anything on its own: the user reviews and can override every
|
||||
* line (manual-base doctrine), and the server only validates what comes back
|
||||
* through the engine.
|
||||
*
|
||||
* Shape for an order row (Swish 500 kr incl. 25%):
|
||||
* Debit 1930 (mapped by payment_method) 500.00 gross
|
||||
* Credit 3001 400.00 net per rate
|
||||
* Credit 2611 100.00 VAT per rate
|
||||
* Refund rows mirror (debit revenue/VAT, credit the payment account).
|
||||
* A rounding residual goes to 3740 Öresavrundning so the entry balances.
|
||||
*
|
||||
* Non-SEK orders book in SEK via the row's stored exchange_rate (rate date =
|
||||
* paid date, captured at sync); every line carries the currency metadata trio
|
||||
* exactly like the transaction booking dialog does. Callers must not invoke
|
||||
* this while total_sek is null (booking is blocked until FX resolves).
|
||||
*/
|
||||
|
||||
/** Fallback counter-account when no mapping exists: the old feed's ledger. */
|
||||
export const DEFAULT_PAYMENT_ACCOUNT = '1680'
|
||||
|
||||
/** Revenue account per Swedish VAT rate (BAS 2026). */
|
||||
const REVENUE_ACCOUNT_BY_RATE: Record<number, string> = {
|
||||
25: '3001',
|
||||
12: '3002',
|
||||
6: '3003',
|
||||
0: '3004',
|
||||
}
|
||||
|
||||
/** Output VAT account per rate. */
|
||||
const VAT_ACCOUNT_BY_RATE: Record<number, string> = {
|
||||
25: '2611',
|
||||
12: '2621',
|
||||
6: '2631',
|
||||
}
|
||||
|
||||
/** Öresavrundning. */
|
||||
const ROUNDING_ACCOUNT = '3740'
|
||||
|
||||
/**
|
||||
* Resolve the prefilled payment counter-account for an order from the
|
||||
* per-store mapping. Returns the account plus whether the store marked this
|
||||
* payment method as invoice-flow (the dialog then nudges toward Skapa
|
||||
* faktura instead).
|
||||
*/
|
||||
export function resolvePaymentAccount(
|
||||
order: Pick<WebshopOrder, 'payment_method'>,
|
||||
settings: WebshopStoreSettings | null | undefined,
|
||||
): { account: string; invoiceMode: boolean; mapped: boolean } {
|
||||
const method = order.payment_method
|
||||
const policy = method ? settings?.payment_method_account_map?.[method] : undefined
|
||||
if (!policy) return { account: DEFAULT_PAYMENT_ACCOUNT, invoiceMode: false, mapped: false }
|
||||
if (policy.mode === 'invoice') {
|
||||
return { account: DEFAULT_PAYMENT_ACCOUNT, invoiceMode: true, mapped: true }
|
||||
}
|
||||
return { account: policy.account, invoiceMode: false, mapped: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* When the sync could not build a per-rate breakdown (blocked tax endpoints,
|
||||
* plugin-mangled orders), fall back to one bucket whose rate is inferred
|
||||
* from the tax/net ratio; null rate when nothing matches, so the dialog
|
||||
* shows an editable guess instead of silently wrong accounts.
|
||||
*/
|
||||
export function fallbackVatBreakdown(
|
||||
total: number,
|
||||
totalTax: number,
|
||||
): WebshopVatBreakdownLine[] {
|
||||
const net = round(Math.abs(total) - Math.abs(totalTax))
|
||||
const tax = round(Math.abs(totalTax))
|
||||
if (net <= 0) return [{ rate: 0, net: round(Math.abs(total)), tax: 0 }]
|
||||
if (tax === 0) return [{ rate: 0, net, tax: 0 }]
|
||||
const ratio = tax / net
|
||||
for (const rate of [25, 12, 6]) {
|
||||
if (Math.abs(ratio - rate / 100) < 0.005) return [{ rate, net, tax }]
|
||||
}
|
||||
// Unknown mix: present as 25% bucket for the user to correct.
|
||||
return [{ rate: 25, net, tax }]
|
||||
}
|
||||
|
||||
export type BookingWarning = 'zero_rate_foreign' | 'foreign_vat'
|
||||
|
||||
/**
|
||||
* Advisory (never blocking, per the soft-guard rule) compliance hints for
|
||||
* the booking dialog:
|
||||
* - zero_rate_foreign: a 0%-rate amount on an order with a known non-SE
|
||||
* billing country. The prefill's 3004 (ruta 42) is only right for
|
||||
* domestic momsfri sales; export/EU sales belong on 31xx/33xx accounts.
|
||||
* - foreign_vat: VAT charged on a non-SEK order. Swedish 2611-series output
|
||||
* VAT may be wrong if the merchant is over the EU distance-selling
|
||||
* threshold (OSS) — the store's tax setup decides, the user must check.
|
||||
*/
|
||||
export function resolveBookingWarnings(
|
||||
order: Pick<
|
||||
WebshopOrder,
|
||||
'currency' | 'total_tax' | 'vat_breakdown' | 'customer_country'
|
||||
>,
|
||||
): BookingWarning[] {
|
||||
const warnings: BookingWarning[] = []
|
||||
const hasZeroRateAmount = order.vat_breakdown.some(
|
||||
(b) => b.rate === 0 && b.net !== 0,
|
||||
)
|
||||
if (
|
||||
hasZeroRateAmount &&
|
||||
order.customer_country &&
|
||||
order.customer_country.toUpperCase() !== 'SE'
|
||||
) {
|
||||
warnings.push('zero_rate_foreign')
|
||||
}
|
||||
if (order.currency.toUpperCase() !== 'SEK' && order.total_tax !== 0) {
|
||||
warnings.push('foreign_vat')
|
||||
}
|
||||
return warnings
|
||||
}
|
||||
|
||||
export interface OrderBookingLinesInput {
|
||||
order: Pick<
|
||||
WebshopOrder,
|
||||
| 'row_type'
|
||||
| 'order_number'
|
||||
| 'payment_method'
|
||||
| 'payment_method_title'
|
||||
| 'currency'
|
||||
| 'total'
|
||||
| 'total_tax'
|
||||
| 'total_sek'
|
||||
| 'exchange_rate'
|
||||
| 'vat_breakdown'
|
||||
>
|
||||
settings?: WebshopStoreSettings | null
|
||||
/** Explicit override of the payment counter-account (dialog edit). */
|
||||
paymentAccount?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Build balanced prefill lines for one order/refund row. Throws if total_sek
|
||||
* is required but unresolved: callers gate on it first.
|
||||
*/
|
||||
export function buildOrderBookingLines({
|
||||
order,
|
||||
settings,
|
||||
paymentAccount,
|
||||
}: OrderBookingLinesInput): CreateJournalEntryLineInput[] {
|
||||
const isSek = order.currency.toUpperCase() === 'SEK'
|
||||
const rate = isSek ? 1 : order.exchange_rate
|
||||
const grossSek = isSek ? round(order.total) : order.total_sek
|
||||
if (grossSek === null || grossSek === undefined || !rate) {
|
||||
throw new Error('Order is missing a resolved SEK amount; booking is blocked until the exchange rate resolves')
|
||||
}
|
||||
|
||||
const account = paymentAccount ?? resolvePaymentAccount(order, settings).account
|
||||
// Refund rows carry negative totals; build everything from magnitudes and
|
||||
// apply direction at the end so debit/credit never go negative.
|
||||
const isRefund = order.row_type === 'refund'
|
||||
const grossAbs = round(Math.abs(grossSek))
|
||||
|
||||
const breakdown =
|
||||
order.vat_breakdown.length > 0
|
||||
? order.vat_breakdown
|
||||
: fallbackVatBreakdown(order.total, order.total_tax)
|
||||
|
||||
const toSek = (amount: number) => round(Math.abs(amount) * rate)
|
||||
|
||||
const methodLabel = order.payment_method_title || order.payment_method || ''
|
||||
const baseDescription = methodLabel
|
||||
? `Order ${order.order_number} (${methodLabel})`
|
||||
: `Order ${order.order_number}`
|
||||
const description = isRefund
|
||||
? `Återbetalning order ${order.order_number}`
|
||||
: baseDescription
|
||||
|
||||
const currencyMeta = (amountAbs: number): Partial<CreateJournalEntryLineInput> =>
|
||||
isSek
|
||||
? {}
|
||||
: {
|
||||
currency: order.currency.toUpperCase(),
|
||||
amount_in_currency: amountAbs,
|
||||
exchange_rate: rate,
|
||||
}
|
||||
|
||||
const line = (
|
||||
accountNumber: string,
|
||||
sekAbs: number,
|
||||
side: 'debit' | 'credit',
|
||||
originalAbs: number,
|
||||
): CreateJournalEntryLineInput => ({
|
||||
account_number: accountNumber,
|
||||
debit_amount: side === 'debit' ? sekAbs : 0,
|
||||
credit_amount: side === 'credit' ? sekAbs : 0,
|
||||
line_description: description,
|
||||
...currencyMeta(originalAbs),
|
||||
})
|
||||
|
||||
// Order: money in (debit payment account); refund: money out (credit).
|
||||
const grossSide: 'debit' | 'credit' = isRefund ? 'credit' : 'debit'
|
||||
const counterSide: 'debit' | 'credit' = isRefund ? 'debit' : 'credit'
|
||||
|
||||
const lines: CreateJournalEntryLineInput[] = [
|
||||
line(account, grossAbs, grossSide, round(Math.abs(order.total))),
|
||||
]
|
||||
|
||||
// Buckets are SIGNED: a discount/gift-card bucket carries a negative net
|
||||
// and must book on the OPPOSITE side (a revenue reduction), never as
|
||||
// abs-flipped extra revenue with the difference dumped on 3740 (skeptic
|
||||
// finding). counterSum accumulates the signed counter-direction total so
|
||||
// the residual stays a pure öre artifact.
|
||||
let counterSum = 0
|
||||
const pushSigned = (account: string, signedOriginal: number) => {
|
||||
if (signedOriginal === 0) return
|
||||
const amountAbs = round(Math.abs(signedOriginal))
|
||||
const sekAbs = toSek(amountAbs)
|
||||
if (sekAbs === 0) return
|
||||
const side = signedOriginal > 0 ? counterSide : grossSide
|
||||
lines.push(line(account, sekAbs, side, amountAbs))
|
||||
counterSum = round(counterSum + (signedOriginal > 0 ? sekAbs : -sekAbs))
|
||||
}
|
||||
for (const bucket of breakdown) {
|
||||
const revenueAccount =
|
||||
REVENUE_ACCOUNT_BY_RATE[bucket.rate] ?? REVENUE_ACCOUNT_BY_RATE[25]
|
||||
const vatAccount = VAT_ACCOUNT_BY_RATE[bucket.rate] ?? VAT_ACCOUNT_BY_RATE[25]
|
||||
pushSigned(revenueAccount, round(bucket.net))
|
||||
pushSigned(vatAccount, round(bucket.tax))
|
||||
}
|
||||
|
||||
// Balance residual (per-line rounding, FX drift) to öresavrundning. The
|
||||
// residual can fall on either side. No currency metadata: the residual is
|
||||
// an SEK-conversion artifact, not an amount that exists in the order
|
||||
// currency.
|
||||
const residual = round(grossAbs - counterSum)
|
||||
if (residual !== 0) {
|
||||
const side: 'debit' | 'credit' = residual > 0 ? counterSide : grossSide
|
||||
const residualAbs = round(Math.abs(residual))
|
||||
lines.push({
|
||||
account_number: ROUNDING_ACCOUNT,
|
||||
debit_amount: side === 'debit' ? residualAbs : 0,
|
||||
credit_amount: side === 'credit' ? residualAbs : 0,
|
||||
line_description: description,
|
||||
})
|
||||
}
|
||||
|
||||
return lines
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user