Last feedback fixes (#116)

* Transaction updates. Email updates. Bookkeeping updates.

* Added email confirmation box

* Update components/invoices/SendInvoiceDialog.tsx

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update app/(dashboard)/invoices/[id]/page.tsx

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: restore deleted useEffect and remove stray JSX closing tag

The SendInvoiceDialog useEffect body was accidentally removed in e32c9b3,
leaving only the dependency array. Also removes a stray `/>` in the
invoice detail page that broke the Turbopack build.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-03-24 12:31:34 +01:00
committed by GitHub
co-authored by Claude Opus 4.6 greptile-apps[bot]
parent 9486b83ae5
commit 3050743013
7 changed files with 473 additions and 69 deletions
+23 -62
View File
@@ -32,6 +32,7 @@ import {
Trash2,
} from 'lucide-react'
import PaymentBookingDialog from '@/components/invoices/PaymentBookingDialog'
import SendInvoiceDialog from '@/components/invoices/SendInvoiceDialog'
import {
Dialog,
DialogContent,
@@ -76,11 +77,12 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
const [originalInvoice, setOriginalInvoice] = useState<Invoice | null>(null)
const [convertedFromInvoice, setConvertedFromInvoice] = useState<Invoice | null>(null)
const [showPaymentDialog, setShowPaymentDialog] = useState(false)
const [showSendDialog, setShowSendDialog] = useState(false)
const [sendDialogMode, setSendDialogMode] = useState<'email' | 'manual'>('email')
const [isConverting, setIsConverting] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const [isUpdating, setIsUpdating] = useState(false)
const [isDownloading, setIsDownloading] = useState(false)
const [isSendingEmail, setIsSendingEmail] = useState(false)
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
@@ -224,48 +226,9 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
setIsUpdating(false)
}
async function sendInvoiceEmail() {
if (!invoice) return
// Check if customer has email
if (!invoice.customer.email) {
toast({
title: 'E-post saknas',
description: 'Kunden saknar e-postadress. Uppdatera kunduppgifterna först.',
variant: 'destructive',
})
return
}
setIsSendingEmail(true)
try {
const response = await fetch(`/api/invoices/${invoice.id}/send`, {
method: 'POST',
})
const data = await response.json()
if (!response.ok) {
throw new Error(data.error || 'Kunde inte skicka fakturan')
}
toast({
title: 'Faktura skickad',
description: data.message,
})
// Refresh to get updated status
fetchInvoice()
} catch (error) {
toast({
title: 'Kunde inte skicka faktura',
description: error instanceof Error ? error.message : 'Försök igen.',
variant: 'destructive',
})
}
setIsSendingEmail(false)
function openSendDialog(mode: 'email' | 'manual') {
setSendDialogMode(mode)
setShowSendDialog(true)
}
async function convertToInvoice() {
@@ -433,16 +396,12 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
)}
{invoice.status === 'draft' && !isDeliveryNote && (
customerHasEmail ? (
<Button onClick={sendInvoiceEmail} disabled={isSendingEmail}>
{isSendingEmail ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Mail className="mr-2 h-4 w-4" />
)}
<Button onClick={() => openSendDialog('email')}>
<Mail className="mr-2 h-4 w-4" />
Skicka via e-post
</Button>
) : (
<Button variant="secondary" onClick={() => updateStatus('sent')} disabled={isUpdating}>
<Button variant="secondary" onClick={() => openSendDialog('manual')}>
<Send className="mr-2 h-4 w-4" />
Skickad manuellt
</Button>
@@ -451,7 +410,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
{isDeliveryNote && invoice.status === 'draft' && (
<Button variant="secondary" onClick={() => updateStatus('sent')} disabled={isUpdating}>
<Send className="mr-2 h-4 w-4" />
Skickad manuellt
Markera som skickad
</Button>
)}
{(invoice.status === 'sent' || invoice.status === 'overdue') && isRealInvoice && (
@@ -880,21 +839,15 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
<>
<Button
className="w-full"
onClick={sendInvoiceEmail}
disabled={isSendingEmail}
onClick={() => openSendDialog('email')}
>
{isSendingEmail ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Mail className="mr-2 h-4 w-4" />
)}
<Mail className="mr-2 h-4 w-4" />
Skicka via e-post
</Button>
<Button
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => updateStatus('sent')}
disabled={isUpdating}
onClick={() => openSendDialog('manual')}
>
<Send className="mr-2 h-4 w-4" />
Skickad manuellt
@@ -915,8 +868,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
)}
<Button
className="w-full"
onClick={() => updateStatus('sent')}
disabled={isUpdating}
onClick={() => openSendDialog('manual')}
>
<Send className="mr-2 h-4 w-4" />
Skickad manuellt
@@ -1002,6 +954,15 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
})
}}
/>
{invoice && (
<SendInvoiceDialog
open={showSendDialog}
onOpenChange={setShowSendDialog}
invoice={invoice}
mode={sendDialogMode}
onSuccess={() => fetchInvoice()}
/>
)}
</div>
)
}
+279
View File
@@ -0,0 +1,279 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
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 { JournalEntryReviewContent } from '@/components/bookkeeping/JournalEntryReviewContent'
import { proposeSendLines } from '@/lib/bookkeeping/propose-send-lines'
import { formatCurrency } from '@/lib/utils'
import { createClient } from '@/lib/supabase/client'
import { CheckCircle2, Loader2, Mail, Send } from 'lucide-react'
import type { Invoice, InvoiceItem, Customer, EntityType } from '@/types'
interface InvoiceWithRelations extends Invoice {
customer: Customer
items: InvoiceItem[]
}
interface SendInvoiceDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
invoice: InvoiceWithRelations
/** 'email' sends via email, 'manual' marks as sent without email */
mode: 'email' | 'manual'
onSuccess: () => void
}
export default function SendInvoiceDialog({
open,
onOpenChange,
invoice,
mode,
onSuccess,
}: SendInvoiceDialogProps) {
const { toast } = useToast()
const supabase = createClient()
const [isSubmitting, setIsSubmitting] = useState(false)
const [sentMessage, setSentMessage] = useState<string | null>(null)
const [accountingMethod, setAccountingMethod] = useState<'accrual' | 'cash'>('accrual')
const [entityType, setEntityType] = useState<EntityType>('enskild_firma')
const [periodName, setPeriodName] = useState('')
const [isInitialized, setIsInitialized] = useState(false)
useEffect(() => {
if (!open) {
setIsInitialized(false)
setSentMessage(null)
return
}
let cancelled = false
async function init() {
try {
// Fetch company settings
const { data: settings, error } = await supabase
.from('company_settings')
.select('accounting_method, entity_type')
.single()
if (error) throw new Error('Kunde inte ladda företagsinställningar')
if (cancelled) return
// Fetch fiscal period for the invoice date
const { data: period } = await supabase
.from('fiscal_periods')
.select('name')
.lte('start_date', invoice.invoice_date)
.gte('end_date', invoice.invoice_date)
.single()
if (cancelled) return
setAccountingMethod((settings?.accounting_method || 'accrual') as 'accrual' | 'cash')
setEntityType((settings?.entity_type as EntityType) || 'enskild_firma')
setPeriodName(period?.name || '')
setIsInitialized(true)
} catch (err) {
if (cancelled) return
toast({
title: 'Kunde inte ladda inställningar',
description: err instanceof Error ? err.message : 'Försök igen.',
variant: 'destructive',
})
onOpenChange(false)
}
}
init()
return () => { cancelled = true }
}, [open, invoice.id, invoice.invoice_date])
const proposedLines = useMemo(() => {
if (!isInitialized || accountingMethod !== 'accrual') return []
return proposeSendLines({
invoice: {
invoice_number: invoice.invoice_number,
total: invoice.total,
total_sek: invoice.total_sek,
subtotal: invoice.subtotal,
subtotal_sek: invoice.subtotal_sek,
vat_amount: invoice.vat_amount,
vat_amount_sek: invoice.vat_amount_sek,
currency: invoice.currency,
exchange_rate: invoice.exchange_rate,
vat_treatment: invoice.vat_treatment,
items: invoice.items,
},
entityType,
})
}, [isInitialized, accountingMethod, entityType, invoice])
const { totalDebit, totalCredit } = useMemo(() => {
let totalDebit = 0
let totalCredit = 0
for (const line of proposedLines) {
totalDebit += parseFloat(line.debit_amount) || 0
totalCredit += parseFloat(line.credit_amount) || 0
}
return { totalDebit, totalCredit }
}, [proposedLines])
const handleConfirm = async () => {
setIsSubmitting(true)
try {
const url = mode === 'email'
? `/api/invoices/${invoice.id}/send`
: `/api/invoices/${invoice.id}/mark-sent`
const response = await fetch(url, { method: 'POST' })
const data = await response.json()
if (!response.ok) {
throw new Error(data.error || 'Kunde inte skicka fakturan')
}
onSuccess()
if (mode === 'email') {
setSentMessage(data.message || `Fakturan har skickats till ${invoice.customer.email}`)
} else {
// For manual send, just close — no email to confirm
onOpenChange(false)
toast({
title: 'Faktura markerad som skickad',
description: accountingMethod === 'accrual'
? 'Bokföringsverifikationen har skapats.'
: undefined,
})
}
} catch (error) {
toast({
title: 'Kunde inte skicka faktura',
description: error instanceof Error ? error.message : 'Försök igen.',
variant: 'destructive',
})
}
setIsSubmitting(false)
}
const handleClose = () => {
onOpenChange(false)
}
const showJournalPreview = accountingMethod === 'accrual' && proposedLines.length > 0
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>
{mode === 'email' ? 'Skicka faktura' : 'Markera som skickad'} — {invoice.invoice_number}
</DialogTitle>
<DialogDescription>
{formatCurrency(invoice.total, invoice.currency)}
{invoice.currency !== 'SEK' && invoice.total_sek && (
<> ({formatCurrency(invoice.total_sek)} SEK)</>
)}
{mode === 'email' && invoice.customer.email && (
<> till {invoice.customer.email}</>
)}
</DialogDescription>
</DialogHeader>
{sentMessage ? (
<div className="flex items-start gap-3 rounded-lg border border-success/30 bg-success/5 p-4">
<CheckCircle2 className="h-5 w-5 text-success shrink-0 mt-0.5" />
<div className="space-y-1 text-sm">
<p className="font-medium">E-post skickad</p>
<p className="text-muted-foreground">{sentMessage}</p>
{accountingMethod === 'accrual' && (
<p className="text-muted-foreground">Bokföringsverifikationen har skapats.</p>
)}
</div>
</div>
) : !isInitialized ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
) : (
<div className="space-y-4">
{showJournalPreview ? (
<>
<p className="text-sm text-muted-foreground">
Följande bokföringsverifikation skapas automatiskt:
</p>
<JournalEntryReviewContent
periodName={periodName}
entryDate={invoice.invoice_date}
description={`Försäljning faktura ${invoice.invoice_number}${invoice.customer.name ? `, ${invoice.customer.name}` : ''}`}
lines={proposedLines}
totalDebit={totalDebit}
totalCredit={totalCredit}
showBalanceBadge={true}
hideDate={!periodName}
/>
</>
) : (
<p className="text-sm text-muted-foreground">
{accountingMethod === 'cash'
? 'Kontantmetoden — bokföring sker vid betalning, inte vid fakturering.'
: mode === 'email'
? `Fakturan skickas till ${invoice.customer.email}.`
: 'Fakturan markeras som skickad.'}
</p>
)}
</div>
)}
<DialogFooter>
{sentMessage ? (
<Button
onClick={handleClose}
className="w-full sm:w-auto min-h-11"
>
Stäng
</Button>
) : (
<>
<Button
variant="outline"
onClick={handleClose}
disabled={isSubmitting}
className="w-full sm:w-auto min-h-11"
>
Avbryt
</Button>
<Button
onClick={handleConfirm}
disabled={isSubmitting || !isInitialized}
className="w-full sm:w-auto min-h-11"
>
{isSubmitting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : mode === 'email' ? (
<Mail className="mr-2 h-4 w-4" />
) : (
<Send className="mr-2 h-4 w-4" />
)}
{mode === 'email' ? 'Skicka faktura' : 'Markera som skickad'}
</Button>
</>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -77,9 +77,9 @@ export default function QuickReviewDialog({
async function fetchAccounts() {
try {
const res = await fetch('/api/bookkeeping/accounts')
const data = await res.json()
if (data.accounts) {
setAccounts(data.accounts)
const { data } = await res.json()
if (data) {
setAccounts(data)
}
} catch {
// Non-critical
@@ -78,9 +78,9 @@ export default function SwipeCategorizationView({
async function fetchAccounts() {
try {
const res = await fetch('/api/bookkeeping/accounts')
const data = await res.json()
if (data.accounts) {
setAccounts(data.accounts)
const { data } = await res.json()
if (data) {
setAccounts(data)
}
} catch {
// Non-critical, AccountCombobox will just be empty
@@ -202,7 +202,7 @@ export default function TransactionInboxCard({
{ts.name_sv}
</div>
<span className="opacity-70 font-normal font-mono text-[10px]">
D: {ts.debit_account} → K: {ts.credit_account}
D: {formatAccountWithName(ts.debit_account)} → K: {formatAccountWithName(ts.credit_account)}
</span>
</div>
</Button>
+6
View File
@@ -40,6 +40,12 @@ const ACCOUNT_NAMES: Record<string, string> = {
// Cost of goods (4xxx)
'4010': 'Varuinköp',
'4060': 'Varuinköp omvänd moms',
'4070': 'Varuinköp EU',
'4100': 'Inköp material/varor',
'4500': 'Övriga inköpskostnader',
'4531': 'Import-/tullkostnader',
'4600': 'Subentreprenader',
// External expenses (5xxx)
'5010': 'Lokalhyra',
+158
View File
@@ -0,0 +1,158 @@
/**
* Pure function to compute proposed journal entry lines for sending an invoice.
* Used by the SendInvoiceDialog to preview the journal entry before committing.
*
* No DB or Supabase dependency — all inputs are plain data.
*/
import { resolveSekAmount } from './currency-utils'
import { getRevenueAccount, getOutputVatAccount } from './invoice-entries'
import { getVatTreatmentForRate } from '@/lib/invoices/vat-rules'
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
import type { EntityType, InvoiceItem, VatTreatment } from '@/types'
export interface ProposeSendLinesInput {
invoice: {
invoice_number: string
total: number
total_sek?: number | null
subtotal: number
subtotal_sek?: number | null
vat_amount: number
vat_amount_sek?: number | null
currency: string
exchange_rate?: number | null
vat_treatment: VatTreatment
items?: InvoiceItem[]
}
entityType: EntityType
}
function toFormAmount(n: number): string {
const rounded = Math.round(n * 100) / 100
return rounded === 0 ? '' : rounded.toString()
}
/**
* Propose journal entry lines for an invoice send (accrual method).
*
* Debit 1510 Kundfordringar [total incl VAT]
* Credit 30xx Försäljning [subtotal per rate]
* Credit 26xx Utgående moms [VAT per rate]
*/
export function proposeSendLines(input: ProposeSendLinesInput): FormLine[] {
const { invoice, entityType } = input
const lines: FormLine[] = []
const isForeign = invoice.currency !== 'SEK'
const desc = `Försäljning faktura ${invoice.invoice_number}`
const toSek = (amount: number): number => {
if (!isForeign) return amount
if (invoice.exchange_rate != null && invoice.exchange_rate > 0) {
return Math.round(amount * invoice.exchange_rate * 100) / 100
}
return amount
}
// Build credit lines per VAT rate group
const creditLines: FormLine[] = []
if (invoice.items && invoice.items.length > 0) {
const hasPerLineVat = invoice.items.some((item) => item.vat_rate !== undefined && item.vat_rate !== null)
if (!hasPerLineVat) {
// Legacy: single rate from invoice level
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
const subtotal = invoice.items.reduce((sum, item) => sum + item.line_total, 0)
creditLines.push({
account_number: revenueAccount,
debit_amount: '',
credit_amount: toFormAmount(toSek(subtotal)),
line_description: desc,
})
const totalVat = invoice.items.reduce((sum, item) => sum + (item.vat_amount || 0), 0)
if (totalVat > 0) {
const vatAccount = getOutputVatAccount(invoice.vat_treatment)
creditLines.push({
account_number: vatAccount,
debit_amount: '',
credit_amount: toFormAmount(toSek(totalVat)),
line_description: 'Utgående moms',
})
}
} else {
// Group items by vat_rate
const rateGroups = new Map<number, { subtotal: number; vatAmount: number }>()
for (const item of invoice.items) {
const rate = item.vat_rate ?? 0
const group = rateGroups.get(rate) || { subtotal: 0, vatAmount: 0 }
group.subtotal += item.line_total
group.vatAmount += item.vat_amount || 0
rateGroups.set(rate, group)
}
for (const [rate, group] of rateGroups) {
const treatment = rate === 0 && (invoice.vat_treatment === 'reverse_charge' || invoice.vat_treatment === 'export')
? invoice.vat_treatment
: getVatTreatmentForRate(rate)
const revenueAccount = getRevenueAccount(treatment, entityType)
creditLines.push({
account_number: revenueAccount,
debit_amount: '',
credit_amount: toFormAmount(Math.round(toSek(group.subtotal) * 100) / 100),
line_description: desc,
})
const roundedVat = Math.round(toSek(group.vatAmount) * 100) / 100
if (roundedVat !== 0) {
const vatAccount = getOutputVatAccount(treatment)
creditLines.push({
account_number: vatAccount,
debit_amount: '',
credit_amount: toFormAmount(roundedVat),
line_description: `Utgående moms ${rate}%`,
})
}
}
}
} else {
// Fallback: invoice-level amounts
const revenueAccount = getRevenueAccount(invoice.vat_treatment, entityType)
const subtotalSek = resolveSekAmount(invoice.subtotal, invoice.subtotal_sek, invoice.currency, invoice.exchange_rate)
creditLines.push({
account_number: revenueAccount,
debit_amount: '',
credit_amount: toFormAmount(subtotalSek),
line_description: desc,
})
if (invoice.vat_amount > 0) {
const vatSek = resolveSekAmount(invoice.vat_amount, invoice.vat_amount_sek, invoice.currency, invoice.exchange_rate)
const vatAccount = getOutputVatAccount(invoice.vat_treatment)
creditLines.push({
account_number: vatAccount,
debit_amount: '',
credit_amount: toFormAmount(vatSek),
line_description: `Utgående moms faktura ${invoice.invoice_number}`,
})
}
}
// Debit: 1510 Kundfordringar — balance guarantee
const totalCredits = creditLines.reduce((sum, l) => sum + (parseFloat(l.credit_amount) || 0), 0)
const debitAmount = isForeign
? Math.round(totalCredits * 100) / 100
: resolveSekAmount(invoice.total, invoice.total_sek, invoice.currency, invoice.exchange_rate)
lines.push({
account_number: '1510',
debit_amount: toFormAmount(debitAmount),
credit_amount: '',
line_description: desc,
})
lines.push(...creditLines)
return lines
}