fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,141 @@
|
||||
'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>
|
||||
{/* data-ph-mask: order number and customer name are user data */}
|
||||
<DialogTitle data-ph-mask="">{t('invoice_title', { number: order.order_number })}</DialogTitle>
|
||||
<DialogDescription data-ph-mask="">
|
||||
{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,261 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import type { WebshopOrder } from '@/types'
|
||||
|
||||
interface MarkOrderBookedDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
order: WebshopOrder
|
||||
onMarked: () => void
|
||||
}
|
||||
|
||||
interface EntryCandidate {
|
||||
id: string
|
||||
entry_date: string
|
||||
description: string | null
|
||||
voucher_series?: string | null
|
||||
voucher_number?: number | null
|
||||
/** The list API returns full rows with nested lines; the gross is their debit sum. */
|
||||
lines?: Array<{ debit_amount: number | string | null }>
|
||||
}
|
||||
|
||||
/** Gross amount of a candidate = sum of its debit legs (total_amount is a DB
|
||||
* computed column and not part of the select the list route returns). */
|
||||
function candidateGross(entry: EntryCandidate): number | null {
|
||||
if (!entry.lines || entry.lines.length === 0) return null
|
||||
const sum = entry.lines.reduce((acc, l) => acc + (Number(l.debit_amount) || 0), 0)
|
||||
return roundOre(sum)
|
||||
}
|
||||
|
||||
// ±45 days around the order date: wide enough for a manual booking done in
|
||||
// the same period, narrow enough to keep the candidate list short. Typing a
|
||||
// search drops the window (search over all posted entries instead).
|
||||
const WINDOW_DAYS = 45
|
||||
const CANDIDATE_LIMIT = 30
|
||||
|
||||
function shiftDate(isoDate: string, deltaDays: number): string {
|
||||
const d = new Date(isoDate)
|
||||
if (Number.isNaN(d.getTime())) return isoDate
|
||||
d.setDate(d.getDate() + deltaDays)
|
||||
return d.toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks one order/refund row as already booked/handled outside the
|
||||
* integration (issue #1879): no verifikat is created, the row just leaves
|
||||
* the to-book list. Optionally links the existing posted verifikat that
|
||||
* covers the order, picked from a searchable candidate list.
|
||||
*/
|
||||
export default function MarkOrderBookedDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
order,
|
||||
onMarked,
|
||||
}: MarkOrderBookedDialogProps) {
|
||||
const t = useTranslations('webshop_orders')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const [candidates, setCandidates] = useState<EntryCandidate[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [search, setSearch] = useState('')
|
||||
const [selected, setSelected] = useState('')
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const loadCandidates = useCallback(
|
||||
async (query: string, signal: { cancelled: boolean }) => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const params = new URLSearchParams()
|
||||
params.set('status', 'posted')
|
||||
params.set('exclude_draft', 'true')
|
||||
params.set('limit', String(CANDIDATE_LIMIT))
|
||||
// Newest first: the manual booking is usually recent relative to the
|
||||
// window; default voucher order would surface the year's first
|
||||
// vouchers and hide the relevant ones behind the cap.
|
||||
params.set('sort_by', 'date_desc')
|
||||
if (query) {
|
||||
params.set('search', query)
|
||||
} else {
|
||||
const anchor = order.paid_date ?? order.order_date
|
||||
params.set('date_from', shiftDate(anchor, -WINDOW_DAYS))
|
||||
params.set('date_to', shiftDate(anchor, WINDOW_DAYS))
|
||||
}
|
||||
const res = await fetch(`/api/bookkeeping/journal-entries?${params}`)
|
||||
if (!res.ok) throw new Error(`list failed: ${res.status}`)
|
||||
const json = (await res.json()) as { data: EntryCandidate[] }
|
||||
if (!signal.cancelled) setCandidates(json.data ?? [])
|
||||
} catch {
|
||||
if (!signal.cancelled) setCandidates([])
|
||||
} finally {
|
||||
if (!signal.cancelled) setLoading(false)
|
||||
}
|
||||
},
|
||||
[order.paid_date, order.order_date],
|
||||
)
|
||||
|
||||
// (Re)load when the dialog opens or the search changes (debounced).
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const signal = { cancelled: false }
|
||||
const timer = setTimeout(() => void loadCandidates(search.trim(), signal), 250)
|
||||
return () => {
|
||||
signal.cancelled = true
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}, [open, search, loadCandidates])
|
||||
|
||||
// Reset transient state when the dialog closes.
|
||||
useEffect(() => {
|
||||
if (open) return
|
||||
setCandidates([])
|
||||
setSearch('')
|
||||
setSelected('')
|
||||
}, [open])
|
||||
|
||||
async function handleConfirm() {
|
||||
setSubmitting(true)
|
||||
try {
|
||||
const res = await fetch(`/api/webshop-orders/${order.id}/mark-booked`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(selected ? { journal_entry_id: selected } : {}),
|
||||
})
|
||||
const json = await res.json()
|
||||
if (!res.ok || json.error) {
|
||||
toast({
|
||||
title: t('mark_failed'),
|
||||
description: getErrorMessage(json, {
|
||||
context: 'transaction',
|
||||
statusCode: res.status,
|
||||
locale: errorLocale,
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
onMarked()
|
||||
} catch {
|
||||
toast({ title: t('mark_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const isRefund = order.row_type === 'refund'
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
{/* data-ph-mask: the order number is user data */}
|
||||
<DialogTitle data-ph-mask="">
|
||||
{isRefund
|
||||
? t('mark_refund_title', { number: order.order_number })
|
||||
: t('mark_title', { number: order.order_number })}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{formatDate(order.paid_date ?? order.order_date)}
|
||||
{' · '}
|
||||
{formatCurrency(order.total, order.currency)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<p className="text-sm text-muted-foreground">{t('mark_description')}</p>
|
||||
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">{t('mark_link_label')}</p>
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={t('mark_link_search_placeholder')}
|
||||
aria-label={t('mark_link_search_placeholder')}
|
||||
/>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center gap-2 rounded-lg border border-border py-6 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
{t('mark_link_loading')}
|
||||
</div>
|
||||
) : candidates.length === 0 ? (
|
||||
<p className="rounded-lg border border-border px-3 py-4 text-center text-sm text-muted-foreground">
|
||||
{t('mark_link_empty')}
|
||||
</p>
|
||||
) : (
|
||||
<div
|
||||
role="radiogroup"
|
||||
aria-label={t('mark_link_label')}
|
||||
className="max-h-56 space-y-1 overflow-y-auto rounded-lg border border-border p-1"
|
||||
>
|
||||
{candidates.map((entry) => {
|
||||
const active = selected === entry.id
|
||||
const gross = candidateGross(entry)
|
||||
return (
|
||||
<button
|
||||
key={entry.id}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={active}
|
||||
onClick={() => setSelected(active ? '' : entry.id)}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-3 rounded-sm px-2 py-2 text-left text-[13px] transition-colors duration-150',
|
||||
active ? 'bg-secondary text-foreground' : 'hover:bg-secondary/60',
|
||||
)}
|
||||
>
|
||||
<span className="w-12 shrink-0 font-medium tabular-nums">
|
||||
{formatVoucher(entry)}
|
||||
</span>
|
||||
<span className="shrink-0 tabular-nums text-muted-foreground">
|
||||
{formatDate(entry.entry_date)}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate">{entry.description}</span>
|
||||
<span className="shrink-0 text-right tabular-nums">
|
||||
{gross != null ? formatCurrency(gross) : ''}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{candidates.length >= CANDIDATE_LIMIT
|
||||
? t('mark_link_capped', { count: CANDIDATE_LIMIT })
|
||||
: t('mark_link_optional_hint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={submitting}>
|
||||
{submitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('mark_submitting')}
|
||||
</>
|
||||
) : (
|
||||
t('mark_confirm')
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
'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>
|
||||
{/* data-ph-mask: the order number is user data */}
|
||||
<DialogTitle data-ph-mask="">
|
||||
{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,219 @@
|
||||
'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 { DEFAULT_PAYMENT_ACCOUNT } from '@/lib/webshop-orders/booking-lines'
|
||||
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',
|
||||
// Same constant the booking prefill falls back to: a hardcoded
|
||||
// number here would silently drift from it (it just did).
|
||||
account: current?.mode === 'book' ? current.account : DEFAULT_PAYMENT_ACCOUNT,
|
||||
},
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
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={<span data-ph-mask="">{title || method}</span>}>
|
||||
<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>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user