4c76fb10d7
* feat(transactions): "Ta bort underlag" detach action on a transaction (#2132) Wrong receipt pinned, no way back: the DELETE /api/transactions/[id]/attach-document route and its tests already existed, but nothing in the UI called it. This wires it up, frontend only. - Inbox card and history list: "Ta bort underlag" in the row menu, shown only for writers on unbooked rows that carry a pin (canDetachDocument helper). - Attach dialog: a small "Ta bort underlag" link beside the already-attached hint, the one place the app previously admitted a doc was pinned. - Page: handleDetachDocument confirms (useDestructiveConfirm, warning), then DELETEs; 200 clears document_id in local state (list, dialog snapshot, and the inbox card's optimistic override via a -unlinked window event) and toasts; 409 renders the route's Swedish BFL message verbatim; other errors map through get-error-message. - Strings under tx_detach in sv.json and en.json. - Tests: gate hidden when booked / read-only / no pin / no handler; 409 rendered unchanged; wiring and locale assertions. Out of scope, follow-up: MCP detach tool (new pending-op type + CHECK migration), detaching from the inbox for non-email docs, and clearing invoice_inbox_items.matched_transaction_id on detach so the doc is offered again by inbox-available. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg * fix(transactions): clear the inbox back-link when detaching underlag (#2132) Skeptic finding on PR #2144: DELETE attach-document nulled only transactions.document_id and left invoice_inbox_items.matched_transaction_id pointing at the transaction. propagateUnderlagForBookedTransaction selects on exactly that column at categorize / book / bulk-book time, so the detached receipt would have been re-anchored onto the new verifikation as immutable underlag (BFL 5 kap 7 §), and the doc never reappeared in inbox-available for re-matching. The route now clears the back-link for the detached document, scoped to items not yet consumed by a verifikat (created_journal_entry_id null), mirroring the invoice-inbox extension's unmatch. Best-effort like the POST side: the pin removal is the primary effect. Three DELETE tests cover the filters, the no-pin case, and a failing unlink. DECISIONS.md and the PR body record the accepted bulk-booked-row limitation in the history list. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg * fix(transactions): detach reports a failed inbox unlink instead of success (#2132) Swedish compliance review on PR #2144: the inbox back-link cleanup was fire-and-forget, so a failed UPDATE returned 200 while leaving exactly the stale matched_transaction_id that re-anchors a detached document onto the next verifikation (BFL 5 kap 6-7 §). The unlink is now scoped by transaction only (the unique index on matched_transaction_id means at most one item points here, and a stale item from the replace path would re-anchor just the same), runs even when nothing was pinned so a retry is idempotent, and a failure answers 500 with an honest Swedish partial-failure message, mirroring the POST side's propagation failure. Tests updated accordingly. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg * fix(transactions): release inbox back-link before a compare-and-set pin clear (#2132) Review findings on PR #2144, one pass: - CodeRabbit (major): DELETE cleared the pin and then released the inbox back-link scoped by transaction, so a POST landing in between could end up as "new doc pinned, its inbox item unlinked". The release now runs FIRST, and the pin clear is a compare-and-set on the document that was read (.eq document_id, or .is null when nothing was pinned). Zero rows answers 409 "ändrades samtidigt" and keeps the newer pin. A failed release returns 500 before anything changed, so a retry is trivially idempotent. - Compliance swarm (A.8.15): the unlink failure log carried the raw driver error; it now logs errorCauseTag() only. - CodeRabbit docstring check: JSDoc on handleDetachDocument. Tests: order of the two writes, CAS filters for both pinned and empty states, 409 on concurrent re-attach, coded-cause logging. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YRXN5CqHrfuuDw5LLcSgTg --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
246 lines
8.5 KiB
TypeScript
246 lines
8.5 KiB
TypeScript
'use client'
|
|
|
|
import { useState } from 'react'
|
|
import { useTranslations } from 'next-intl'
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
} from '@/components/ui/dialog'
|
|
import { Button } from '@/components/ui/button'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { formatCurrency, formatDate } from '@/lib/utils'
|
|
import { ArrowUpRight, ArrowDownRight, FileText, Inbox, Loader2, X } from 'lucide-react'
|
|
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
|
|
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
|
|
import InboxDocumentPicker from '@/components/bookkeeping/InboxDocumentPicker'
|
|
import type { AvailableInboxDoc } from '@/components/bookkeeping/InboxDocumentPicker'
|
|
import type { TransactionWithInvoice } from './transaction-types'
|
|
|
|
interface TransactionAttachDocumentDialogProps {
|
|
open: boolean
|
|
onOpenChange: (open: boolean) => void
|
|
transaction: TransactionWithInvoice | null
|
|
onAttached: (transactionId: string, documentId: string) => void
|
|
/** Detach the current pin (#2132). The page owns confirm + DELETE; the
|
|
* dialog only offers the entry point next to the already-attached hint. */
|
|
onDetach?: (transaction: TransactionWithInvoice) => void
|
|
}
|
|
|
|
/**
|
|
* Standalone "Matcha mot underlag" dialog for the /transactions view: the
|
|
* mirror of the Documents view's TransactionMatchPicker (doc → tx direction).
|
|
* Pick an unconsumed inbox document or upload a new file, then pin it to the
|
|
* transaction via POST /api/transactions/[id]/attach-document. The pin is
|
|
* single-valued (transactions.document_id); for booked rows the route
|
|
* propagates the link onto the verifikation immediately.
|
|
*/
|
|
export default function TransactionAttachDocumentDialog({
|
|
open,
|
|
onOpenChange,
|
|
transaction,
|
|
onAttached,
|
|
onDetach,
|
|
}: TransactionAttachDocumentDialogProps) {
|
|
const t = useTranslations('tx_attach_dialog')
|
|
const tDetach = useTranslations('tx_detach')
|
|
const { toast } = useToast()
|
|
const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
|
|
const [pickedDoc, setPickedDoc] = useState<AvailableInboxDoc | null>(null)
|
|
const [inboxPickerOpen, setInboxPickerOpen] = useState(false)
|
|
const [isAttaching, setIsAttaching] = useState(false)
|
|
|
|
if (!transaction) return null
|
|
|
|
const isIncome = transaction.amount > 0
|
|
|
|
// Single selection: transactions.document_id pins exactly one doc, so an
|
|
// inbox pick replaces any upload and vice versa.
|
|
const selectedDocumentId =
|
|
pickedDoc?.document_id ??
|
|
uploadedFiles.find((f) => f.status === 'uploaded' && f.id)?.id ??
|
|
null
|
|
|
|
const reset = () => {
|
|
setUploadedFiles([])
|
|
setPickedDoc(null)
|
|
setInboxPickerOpen(false)
|
|
}
|
|
|
|
const handleAttach = async () => {
|
|
if (!selectedDocumentId || isAttaching) return
|
|
setIsAttaching(true)
|
|
try {
|
|
const res = await fetch(`/api/transactions/${transaction.id}/attach-document`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ document_id: selectedDocumentId }),
|
|
})
|
|
if (!res.ok) {
|
|
const json = (await res.json().catch(() => ({}))) as { error?: unknown }
|
|
// The route returns Swedish domain messages (immutability, locked
|
|
// period) as a plain string: surface them verbatim.
|
|
toast({
|
|
title: t('error_toast'),
|
|
description: typeof json.error === 'string' ? json.error : undefined,
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
toast({ title: t('success_toast') })
|
|
// Same event AgentChat and the booking dialog dispatch: flips the inbox
|
|
// card's indicator optimistically without a refetch.
|
|
window.dispatchEvent(
|
|
new CustomEvent('Accounted:transaction-document-linked', {
|
|
detail: { transaction_id: transaction.id, document_id: selectedDocumentId },
|
|
}),
|
|
)
|
|
onAttached(transaction.id, selectedDocumentId)
|
|
reset()
|
|
onOpenChange(false)
|
|
} catch {
|
|
// Network-level failure: fetch rejected before a response existed.
|
|
toast({ title: t('error_toast'), variant: 'destructive' })
|
|
} finally {
|
|
setIsAttaching(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Dialog
|
|
open={open}
|
|
onOpenChange={(o) => {
|
|
if (!o) reset()
|
|
onOpenChange(o)
|
|
}}
|
|
>
|
|
<DialogContent className="sm:max-w-lg">
|
|
<DialogHeader>
|
|
<DialogTitle>{t('title')}</DialogTitle>
|
|
<DialogDescription>{t('description')}</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{/* Transaction summary: same block as TransactionBookingDialog */}
|
|
<div className="flex items-center gap-3 rounded-lg border p-3">
|
|
<div
|
|
className={`h-9 w-9 rounded-full flex items-center justify-center flex-shrink-0 ${
|
|
isIncome
|
|
? 'text-success'
|
|
: 'text-destructive'
|
|
}`}
|
|
>
|
|
{isIncome ? (
|
|
<ArrowUpRight className="h-4 w-4" />
|
|
) : (
|
|
<ArrowDownRight className="h-4 w-4" />
|
|
)}
|
|
</div>
|
|
<div className="flex-1 min-w-0">
|
|
<p className="font-medium text-sm truncate">{transaction.description}</p>
|
|
<p className="text-xs text-muted-foreground">{formatDate(transaction.date)}</p>
|
|
</div>
|
|
<p className={`font-medium text-sm flex-shrink-0 ${isIncome ? 'text-success' : ''}`}>
|
|
{isIncome ? '+' : ''}
|
|
{formatCurrency(transaction.amount, transaction.currency)}
|
|
</p>
|
|
</div>
|
|
|
|
{transaction.document_id && (
|
|
<p className="text-xs text-muted-foreground">
|
|
{t('already_attached_hint')}
|
|
{onDetach && !transaction.journal_entry_id && (
|
|
<>
|
|
{' '}
|
|
<Button
|
|
type="button"
|
|
variant="link"
|
|
size="sm"
|
|
className="h-auto p-0 text-xs"
|
|
disabled={isAttaching}
|
|
onClick={() => onDetach(transaction)}
|
|
>
|
|
{tDetach('menu_item')}
|
|
</Button>
|
|
</>
|
|
)}
|
|
</p>
|
|
)}
|
|
|
|
<div className="space-y-2">
|
|
<DocumentUploadZone
|
|
files={uploadedFiles}
|
|
onFilesChange={(files) => {
|
|
setUploadedFiles(files)
|
|
if (files.length > 0) setPickedDoc(null)
|
|
}}
|
|
maxFiles={1}
|
|
compact
|
|
disabled={isAttaching}
|
|
/>
|
|
{pickedDoc && (
|
|
<div className="flex items-center gap-2 text-sm py-1.5 px-2 rounded-sm bg-muted/50">
|
|
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
|
|
<span className="truncate flex-1">
|
|
{pickedDoc.supplier_name ?? pickedDoc.file_name}
|
|
</span>
|
|
{pickedDoc.amount != null && (
|
|
<span className="text-xs text-muted-foreground tabular-nums shrink-0">
|
|
{formatCurrency(pickedDoc.amount, pickedDoc.currency ?? 'SEK')}
|
|
</span>
|
|
)}
|
|
<Button
|
|
variant="ghost"
|
|
size="sm"
|
|
className="h-6 w-6 p-0 shrink-0"
|
|
aria-label={t('selected_remove')}
|
|
onClick={() => setPickedDoc(null)}
|
|
>
|
|
<X className="h-3 w-3" />
|
|
</Button>
|
|
</div>
|
|
)}
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
size="sm"
|
|
className="w-full"
|
|
disabled={isAttaching}
|
|
onClick={() => setInboxPickerOpen(true)}
|
|
>
|
|
<Inbox className="h-4 w-4 mr-2" />
|
|
{t('pick_existing')}
|
|
</Button>
|
|
</div>
|
|
|
|
<DialogFooter>
|
|
<Button variant="outline" disabled={isAttaching} onClick={() => onOpenChange(false)}>
|
|
{t('cancel')}
|
|
</Button>
|
|
<Button disabled={!selectedDocumentId || isAttaching} onClick={handleAttach}>
|
|
{isAttaching ? (
|
|
<>
|
|
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
|
{t('attaching')}
|
|
</>
|
|
) : (
|
|
t('confirm')
|
|
)}
|
|
</Button>
|
|
</DialogFooter>
|
|
|
|
<InboxDocumentPicker
|
|
open={inboxPickerOpen}
|
|
onClose={() => setInboxPickerOpen(false)}
|
|
onSelect={(doc) => {
|
|
setPickedDoc(doc)
|
|
setUploadedFiles([])
|
|
}}
|
|
/>
|
|
</DialogContent>
|
|
</Dialog>
|
|
)
|
|
}
|