* fix(invoices): reminders, AR ledger, AR reconciliation and deadlines only read fakturor The overdue-reminder run, the kundreskontra, the 1510 reconciliation and the deadlines page selected invoices by status alone. A sent proforma past its due date was chased with a betalningspaminnelse and flipped to 'overdue', and it appeared as a receivable. All four now filter document_type = 'invoice', which is also the precondition for adding quotes (offert): a quote carries a date but never a receivable. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(invoices): offert (quote) document type with its own OF-series, decisions and conversion Adds document_type 'quote' with valid_until, quote_status (open / accepted / declined; expired is derived from valid_until, never stored) and quote_decided_at. Quotes are numbered OF-nnn at insert from company_settings.next_quote_number via generate_quote_number(), the same pattern as delivery notes, so a declined quote never leaves a hole in the F-series the way a proforma does. The column next_quote_number already existed on prod and staging without a migration; the migration adopts it. Engine: build-invoice-write writes the quote columns and keeps remaining_amount at 0; the draft editor refuses accepted or declined quotes; PATCH refuses changing a quote's or delivery note's document type since the number belongs to the series; mark-paid refuses quotes. New POST /api/invoices/[id]/quote-status records the decision and locks once an invoice exists. Conversion is extracted into lib/invoices/convert-to-invoice.ts (one implementation for the route and the MCP staged commit, which had drifted): a converted quote stays and flips to accepted, the invoice links back via converted_from_id and gets its due date from the customer's payment terms; a declined or already invoiced quote is refused. next-number previews the OF-series for quotes. Migration applied to the staging branch and registered as 20260902140000; the pg test runs in CI (pg-real). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(invoices): quote PDF, email and filename surfaces The customer-facing surfaces get a quote sibling for every proforma branch: PDF title OFFERT / QUOTE with Offertdatum and Giltig till instead of the due date, a notice that the document is not an invoice or a payment request, and no payment box, OCR, bankgiro, Swish, QR or payment link. The email says the quote is attached and valid until the expiry, drops the payment details and pay-online button, and asks about the quote rather than the invoice. Filenames read "Offert nr OF-001". Seller VAT number and payment accounts are skipped for quotes as for proformas: a quote is not a faktura under ML 17 kap. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(invoices): offert in the editor, list and detail pages Editor: "Offert" document type with a required "Giltig till" field (default today + 30 days) in place of the due date; the wire body mirrors it into due_date so the shared schema is satisfied. Payment link, ROT/RUT, periodisering and the bank box are already gated on real invoices. The type cannot be switched on an existing quote (its OF-number belongs to the series). List: an Offerter tab beside Proforma, "Ny offert" in the split button, and a status column that shows the decision or the derived expiry: Utgången and Avböjd are exception chips, Öppen and Accepterad muted text. Detail: Acceptera and Skapa faktura in the header, Avböj in the overflow menu; an expired quote asks before accepting or invoicing (bypassable); once an invoice exists the page links to it as Fakturerad and hides the decision actions. Strings in both sv and en. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * feat(mcp,v1): expose offert on the MCP tools and the v1 REST surface MCP: create_invoice takes document_type quote with a required valid_until and allocates the OF-number at insert; the convert tool keeps its id and accepts quotes with the registry refusal codes; new set_quote_status; list_invoices and get_invoice expose valid_until and the effective quote status, including a derived expired filter. The tools/list payload stays under its ceiling without a ledger change. The MCP staged convert now uses the shared converter. v1: POST /invoices/{id}/quote-status (registered in the endpoint registry, scope map and route loader), valid_until and quote_status in the list, create and detail shapes, and a quote_status list filter. Skill atoms mention offert. Decision log lines for the own number series, derived expiry, accepted-not-cancelled conversion and the header action layout. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * test(invoices): pass route params and period id in the new quote tests Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * refactor(invoices): literal update payloads in the converter so the phantom-column guard can read them Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56 * fix(invoices): close the quote review findings in one pass Skeptics (correctness, compliance, regression) and CodeRabbit on #2163: - quote_status is no longer a write-builder output, so a v1 PATCH or MCP update_invoice can never reset a recorded accept/decline; new quotes are opened by the invoices_quote_defaults trigger (20260902141000), which also keeps due_date and valid_until equal. v1 PATCH and the MCP update executor now use the shared editable-draft predicate. - One live invoice per converted source, enforced by a partial unique index; the converter maps 23505 to INVOICE_QUOTE_ALREADY_INVOICED and both quote-status routes compare-and-set on the decision they read. - MCP-created quotes carry remaining_amount 0; mark-paid, transaction match and voucher link refuse non-invoices on the MCP staging tools, the executors and the dashboard link route. - Conversion of a foreign-currency source refetches the rate for the conversion day (ML 8 kap 21-23 paragraphs) and fails closed without one; 0-day payment terms mean due on receipt. - bulk-create refuses quotes per item; list_invoices rejects a quote_status filter combined with another document_type; an omitted document_type on PATCH means unchanged. - attention, push notifications, open-AR count, FX revaluation, year-end and accrual auto-detect and bank-match suggestions only read fakturor. - Quote PDF and email print Summa / Total instead of Att betala. - Regenerated skills/accounted-api for the new v1 endpoint. Declined with reasons in DECISIONS.md: NOT VALID + VALIDATE and CONCURRENTLY on the migrations (repo precedent, 13.8k rows, transactional apply); re-validating VAT treatment at conversion (the converted invoice is a draft the user reviews; follow-up). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * fix(invoices): second review round: migration versions, order links, batch allocation, races - Migrations renamed to 20260902220000 / 20260902221000: #2166 shipped its own 20260902141000 to prod while this PR was in review and prod's head moved past both files; below-head versions are skipped by branching, which would have left the quote trigger off prod. Staging rows renamed. - Quote lines never carry sales_order_item_id (an offer must not count as invoiced kundorder quantity); the converter carries a proforma line's order link onto the invoice. - Converter compare-and-sets the source (proforma cancel, quote accept): a concurrent cancel, proforma-to-order conversion or decision removes the orphan invoice with INVOICE_CONVERT_SOURCE_CHANGED instead of a second document for the same sale. - MCP set_quote_status gets the same compare-and-set as the HTTP routes; 0-row updates report INVOICE_QUOTE_CHANGED_CONCURRENTLY everywhere. quote-status (dashboard, v1, MCP) accepts valid_until so an expired sent quote can be reopened, as the docs promised. - MCP mark-paid refuses only quotes, parity with the dashboard route (a sent proforma marked paid is a supported prepayment record). - Batch allocation (dashboard route and MCP tool) refuses non-invoices before the RPC, which gates on status alone. - Customer AR drill-down, v1 customer open invoices and archive guard, and the calendar feed read fakturor only. - Draft quote PDF says "UTKAST" instead of "not a valid invoice"; the editor locks the document type on existing quotes and delivery notes. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * chore(invoices): use roundOre in the quote MCP summaries and FX test after main tightened the guard baseline Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * fix(invoices): third review round: atomic decision lock, viewer gate, lookup errors, quote payment terms - 20260902222000: BEFORE UPDATE trigger locks an accepted quote while a live converted invoice exists (the compare-and-set in the three decision writers could still be beaten by a conversion landing in between); the routes and the MCP tool map the raise to 409 INVOICE_QUOTE_ALREADY_INVOICED. generate_quote_number now also requires a non-viewer membership so a viewer's session token cannot burn OF-numbers through PostgREST. - Converter checks quote eligibility before the Riksbanken call and treats a failed company_settings read as a failure instead of a 30-day default. - Re-sending the same decision keeps quote_decided_at (idempotent). - gnubok_find_voucher_candidates_for_invoice refuses non-invoices like its write sibling; the dashboard link route surfaces a failed lookup. - Late-fee and credit-term texts never print on a quote. Applied and registered on staging; pg tests added. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs * fix(invoices): review nits: fail-closed batch lookup, dry-run expiry, quote heading, quote-date CHECK - match-batch surfaces a failed document lookup instead of allocating. - v1 quote-status dry-run preview carries the new valid_until. - Quote PDF heading reads Offertinformation / Quote information. - 20260902222000 also pins the date invariants the trigger maintains as a CHECK: a quote always has valid_until = due_date, nothing else has one. Applied on staging. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
542 lines
19 KiB
TypeScript
542 lines
19 KiB
TypeScript
'use client'
|
|
|
|
import { useState, useEffect, useCallback } from 'react'
|
|
import Link from 'next/link'
|
|
import { useTranslations } from 'next-intl'
|
|
import { createClient } from '@/lib/supabase/client'
|
|
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { ToastAction } from '@/components/ui/toast'
|
|
import { DeadlineList } from '@/components/deadlines/DeadlineList'
|
|
import { DeadlineForm, type DeadlineFormValues } from '@/components/deadlines/DeadlineForm'
|
|
import { PageHeader } from '@/components/ui/page-header'
|
|
import { HelpPopover } from '@/components/ui/help-popover'
|
|
import { AttnLine } from '@/components/ui/attn-line'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Skeleton } from '@/components/ui/skeleton'
|
|
import { CalendarPlus, Lock, Plus } from 'lucide-react'
|
|
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
|
import { useCompany } from '@/contexts/CompanyContext'
|
|
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
|
import { formatCurrency } from '@/lib/utils'
|
|
import type { Deadline } from '@/types'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
const supabase = createClient()
|
|
|
|
/**
|
|
* The sentence the route meant to say, from a response it refused.
|
|
*
|
|
* The parsed body goes to the mapper as-is. Wrapping it in `new Error()` first,
|
|
* which every handler here used to do, stringifies the canonical envelope
|
|
* `{ error: { code, message } }` into "[object Object]": the mapper then has
|
|
* nothing to match on and falls through to the generic "Något gick fel",
|
|
* discarding the route's own Swedish reason and its Zod field list. Passing the
|
|
* status as well means a body-less or non-JSON refusal still resolves to the
|
|
* right sentence, so a 403 read-only refusal reads as one instead of as a
|
|
* generic failure.
|
|
*/
|
|
async function describeFailure(response: Response): Promise<string> {
|
|
const body: unknown = await response.json().catch(() => null)
|
|
return getUserErrorMessage(body, { statusCode: response.status })
|
|
}
|
|
|
|
export default function DeadlinesPage() {
|
|
const { company } = useCompany()
|
|
const companyId = company?.id
|
|
const t = useTranslations('deadlines')
|
|
const { canWrite } = useCanWrite()
|
|
const [deadlines, setDeadlines] = useState<Deadline[]>([])
|
|
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([])
|
|
const [overdueInvoices, setOverdueInvoices] = useState<{ count: number; total: number; unconverted: number }>({ count: 0, total: 0, unconverted: 0 })
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
const [isGenerating, setIsGenerating] = useState(false)
|
|
const [showForm, setShowForm] = useState(false)
|
|
const [editingDeadline, setEditingDeadline] = useState<Deadline | null>(null)
|
|
const { toast } = useToast()
|
|
|
|
// Returns whether the list on screen was actually refreshed. Handlers that
|
|
// confirm an outcome to the user need that: claiming a row moved while the
|
|
// reload failed would describe a list the user is not looking at.
|
|
const fetchData = useCallback(async (): Promise<boolean> => {
|
|
if (!companyId) return false
|
|
setIsLoading(true)
|
|
|
|
try {
|
|
const today = new Date().toISOString().split('T')[0]
|
|
|
|
// fetchAllRows: PostgREST silently caps plain selects at 1000 rows,
|
|
// which would truncate the deadline list and undercount overdue
|
|
// invoices for large companies. The secondary .order('id') gives the
|
|
// stable total order paging requires.
|
|
const [deadlineRows, customerRows, overdueRows] = await Promise.all([
|
|
fetchAllRows<Deadline>(({ from, to }) =>
|
|
supabase
|
|
.from('deadlines')
|
|
.select('*, customer:customers(name)')
|
|
.eq('company_id', companyId)
|
|
.is('dismissed_at', null)
|
|
.order('due_date', { ascending: true })
|
|
.order('id', { ascending: true })
|
|
.range(from, to),
|
|
),
|
|
fetchAllRows<{ id: string; name: string }>(({ from, to }) =>
|
|
supabase
|
|
.from('customers')
|
|
.select('id, name')
|
|
.eq('company_id', companyId)
|
|
.is('archived_at', null)
|
|
.order('name', { ascending: true })
|
|
.order('id', { ascending: true })
|
|
.range(from, to),
|
|
),
|
|
fetchAllRows<{ total_sek: number | null; total: number | null; currency: string | null }>(({ from, to }) =>
|
|
supabase
|
|
.from('invoices')
|
|
.select('total_sek, total, currency')
|
|
.eq('company_id', companyId)
|
|
// The open statuses, and only those the CHECK actually allows
|
|
// (draft, sent, paid, partially_paid, overdue, cancelled,
|
|
// credited): draft is not owed yet, paid/cancelled/credited are
|
|
// settled. There is no 'unpaid' status; this filter used to name
|
|
// one, so every invoice the reminder run had already flipped to
|
|
// 'overdue' fell out of the total silently. partially_paid is
|
|
// deliberately absent: the sum below is the invoice total, not
|
|
// remaining_amount, so counting one would report money already
|
|
// received as still owed, and the action link lands on the
|
|
// invoices tab that lists exactly sent + overdue.
|
|
.in('status', ['sent', 'overdue'])
|
|
// Only fakturor are owed: proformas, delivery notes and quotes
|
|
// carry a date but no receivable.
|
|
.eq('document_type', 'invoice')
|
|
.lt('due_date', today)
|
|
.order('id', { ascending: true })
|
|
.range(from, to),
|
|
),
|
|
])
|
|
|
|
// Non-SEK invoices without a stored SEK conversion (rate fetch failed at
|
|
// creation) are excluded from the SEK sum rather than mixed in raw, and
|
|
// surfaced as a count in the attn line instead.
|
|
let overdueTotal = 0
|
|
let unconvertedCount = 0
|
|
for (const inv of overdueRows) {
|
|
if (inv.total_sek != null) overdueTotal += inv.total_sek
|
|
else if (!inv.currency || inv.currency === 'SEK') overdueTotal += inv.total || 0
|
|
else unconvertedCount++
|
|
}
|
|
|
|
setDeadlines(deadlineRows)
|
|
setCustomers(customerRows)
|
|
setOverdueInvoices({ count: overdueRows.length, total: overdueTotal, unconverted: unconvertedCount })
|
|
return true
|
|
} catch {
|
|
toast({
|
|
title: t('load_failed_title'),
|
|
description: t('load_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
return false
|
|
} finally {
|
|
setIsLoading(false)
|
|
}
|
|
}, [companyId, toast, t])
|
|
|
|
useEffect(() => {
|
|
fetchData()
|
|
}, [fetchData])
|
|
|
|
const handleGenerateSystemDeadlines = async () => {
|
|
setIsGenerating(true)
|
|
try {
|
|
const response = await fetch('/api/tax-deadlines/generate', {
|
|
method: 'POST',
|
|
}).catch(() => null)
|
|
|
|
// The request never reached the route (offline, connection reset), so
|
|
// point at the connection rather than the data.
|
|
if (!response) {
|
|
toast({
|
|
title: t('generate_failed_title'),
|
|
description: t('load_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
if (!response.ok) {
|
|
toast({
|
|
title: t('generate_failed_title'),
|
|
description: await describeFailure(response),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
// Only a malformed success body reaches the catch below now.
|
|
const result = await response.json()
|
|
|
|
if ((result.created ?? 0) === 0) {
|
|
// Nothing was generated: the tax settings are genuinely incomplete.
|
|
// Point the user to fill them in (the banner's settings link stays visible).
|
|
toast({
|
|
title: t('generate_none_title'),
|
|
description: t('generate_none_description'),
|
|
})
|
|
return
|
|
}
|
|
|
|
toast({
|
|
title: t('generate_success_title'),
|
|
description: t('generate_success_description', { count: result.created }),
|
|
})
|
|
fetchData()
|
|
} catch (error) {
|
|
toast({
|
|
title: t('generate_failed_title'),
|
|
description: error instanceof Error ? getUserErrorMessage(error) : t('retry'),
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setIsGenerating(false)
|
|
}
|
|
}
|
|
|
|
// Returns whether the create landed. False keeps the form open with the
|
|
// user's input (handleFormSubmit only closes it on success); the toast above
|
|
// each return is the user's copy of why. Not a throw: DeadlineForm's submit
|
|
// wrapper has no catch, so a rejection here would escape as an unhandled
|
|
// promise rejection rather than control flow.
|
|
const handleDeadlineCreate = async (data: DeadlineFormValues): Promise<boolean> => {
|
|
const response = await fetch('/api/deadlines', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(data),
|
|
}).catch(() => null)
|
|
|
|
if (!response) {
|
|
// The request never reached the route (offline, connection reset), so
|
|
// point at the connection rather than the data.
|
|
toast({
|
|
title: t('create_failed_title'),
|
|
description: t('load_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
return false
|
|
}
|
|
|
|
if (!response.ok) {
|
|
toast({
|
|
title: t('create_failed_title'),
|
|
description: await describeFailure(response),
|
|
variant: 'destructive',
|
|
})
|
|
return false
|
|
}
|
|
|
|
toast({
|
|
title: t('created_title'),
|
|
description: t('created_description'),
|
|
})
|
|
|
|
fetchData()
|
|
return true
|
|
}
|
|
|
|
// "Ångra" on the marked-done toast. It lives here rather than inline in the
|
|
// toast so it gets the same treatment as every other mutation on this page:
|
|
// gated on res.ok, refetched, and answered with exactly one sentence. A
|
|
// Skatteverket deadline that is still marked done must never be reported as
|
|
// back on the list, and a failed undo must not look like a successful one.
|
|
const handleUndoComplete = useCallback(
|
|
async (deadline: Deadline) => {
|
|
const response = await fetch(`/api/deadlines/${deadline.id}/complete`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
// The target state, not a toggle: clicking undo twice, or undoing a row
|
|
// something else already un-ticked, must not re-complete the deadline.
|
|
body: JSON.stringify({ is_completed: false }),
|
|
}).catch(() => null)
|
|
|
|
// null: the request never completed (offline, connection reset). Nothing
|
|
// was undone, so point at the connection rather than the data.
|
|
if (!response) {
|
|
toast({
|
|
title: t('undo_failed'),
|
|
description: t('load_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
if (!response.ok) {
|
|
toast({
|
|
title: t('undo_failed'),
|
|
// The route knows why it refused (gone, read-only member); prefer its
|
|
// own message over generic retry copy.
|
|
description: await describeFailure(response),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
// Confirm only once the row is provably back. When the reload failed,
|
|
// fetchData has already said so and TOAST_LIMIT is 1, so a success
|
|
// sentence here would evict that warning and render alone.
|
|
if (!(await fetchData())) return
|
|
|
|
toast({ title: t('marked_not_done', { title: deadline.title }) })
|
|
},
|
|
[fetchData, toast, t],
|
|
)
|
|
|
|
const handleDeadlineToggle = async (deadline: Deadline) => {
|
|
const wasCompleted = deadline.is_completed
|
|
const newCompleted = !wasCompleted
|
|
|
|
const response = await fetch(`/api/deadlines/${deadline.id}/complete`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ is_completed: newCompleted }),
|
|
}).catch(() => null)
|
|
|
|
if (!response) {
|
|
toast({
|
|
title: t('toggle_failed_title'),
|
|
description: t('load_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
if (!response.ok) {
|
|
toast({
|
|
title: t('toggle_failed_title'),
|
|
description: await describeFailure(response),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
fetchData()
|
|
|
|
if (newCompleted) {
|
|
toast({
|
|
title: t('marked_done', { title: deadline.title }),
|
|
action: (
|
|
<ToastAction
|
|
altText={t('undo')}
|
|
onClick={() => {
|
|
void handleUndoComplete(deadline)
|
|
}}
|
|
>
|
|
{t('undo')}
|
|
</ToastAction>
|
|
),
|
|
})
|
|
} else {
|
|
toast({ title: t('marked_not_done', { title: deadline.title }) })
|
|
}
|
|
}
|
|
|
|
// Sends ONLY the form-managed fields: the PUT route whitelists to the same
|
|
// set, and posting a whole Deadline row from here would fabricate system
|
|
// fields (source, status, reminder_offsets) that only the whitelist drops.
|
|
// Returns whether the edit landed, same contract as create: false keeps the
|
|
// form open with the user's input instead of silently discarding it.
|
|
const handleDeadlineEdit = async (id: string, data: DeadlineFormValues): Promise<boolean> => {
|
|
const response = await fetch(`/api/deadlines/${id}`, {
|
|
method: 'PUT',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(data),
|
|
}).catch(() => null)
|
|
|
|
if (!response) {
|
|
toast({
|
|
title: t('update_failed_title'),
|
|
description: t('load_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
return false
|
|
}
|
|
|
|
if (!response.ok) {
|
|
toast({
|
|
title: t('update_failed_title'),
|
|
description: await describeFailure(response),
|
|
variant: 'destructive',
|
|
})
|
|
return false
|
|
}
|
|
|
|
toast({
|
|
title: t('updated_title'),
|
|
description: t('updated_description'),
|
|
})
|
|
|
|
fetchData()
|
|
return true
|
|
}
|
|
|
|
const handleDeadlineDelete = async (deadline: Deadline) => {
|
|
const response = await fetch(`/api/deadlines/${deadline.id}`, {
|
|
method: 'DELETE',
|
|
}).catch(() => null)
|
|
|
|
if (!response) {
|
|
toast({
|
|
title: t('delete_failed_title'),
|
|
description: t('load_failed_description'),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
if (!response.ok) {
|
|
toast({
|
|
title: t('delete_failed_title'),
|
|
description: await describeFailure(response),
|
|
variant: 'destructive',
|
|
})
|
|
return
|
|
}
|
|
|
|
toast({ title: t('deleted_title') })
|
|
fetchData()
|
|
}
|
|
|
|
const handleFormSubmit = async (data: DeadlineFormValues) => {
|
|
const ok = editingDeadline
|
|
? await handleDeadlineEdit(editingDeadline.id, data)
|
|
: await handleDeadlineCreate(data)
|
|
// On failure the handler has already toasted; leave the form open so the
|
|
// user's input survives a retry.
|
|
if (!ok) return
|
|
setShowForm(false)
|
|
setEditingDeadline(null)
|
|
}
|
|
|
|
const openEdit = (deadline: Deadline) => {
|
|
setEditingDeadline(deadline)
|
|
setShowForm(true)
|
|
}
|
|
|
|
const pageHeader = (
|
|
<PageHeader
|
|
title={t('title')}
|
|
help={
|
|
<HelpPopover>
|
|
<p>{t('help_text')}</p>
|
|
<p className="mt-2">
|
|
<Link href="/settings/tax" className="underline underline-offset-2">
|
|
{t('generate_open_settings')}
|
|
</Link>
|
|
</p>
|
|
</HelpPopover>
|
|
}
|
|
action={
|
|
// Stacks full-width on mobile: PageHeader's [&>*]:w-full lands on
|
|
// this wrapper, so the buttons themselves must go w-full below sm
|
|
<div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center [&>*]:w-full sm:[&>*]:w-auto">
|
|
{ENABLED_EXTENSION_IDS.has('calendar') && (
|
|
<Button variant="outline" asChild>
|
|
<Link href="/settings/account">
|
|
<CalendarPlus className="mr-2 h-4 w-4" />
|
|
{t('subscribe_calendar')}
|
|
</Link>
|
|
</Button>
|
|
)}
|
|
<Button
|
|
onClick={() => setShowForm(true)}
|
|
disabled={!canWrite}
|
|
title={!canWrite ? t('read_only_tooltip') : undefined}
|
|
>
|
|
{canWrite ? <Plus className="mr-2 h-4 w-4" /> : <Lock className="mr-2 h-4 w-4" />}
|
|
{t('new_deadline')}
|
|
</Button>
|
|
</div>
|
|
}
|
|
/>
|
|
)
|
|
|
|
if (isLoading) {
|
|
return (
|
|
<div className="space-y-8">
|
|
{pageHeader}
|
|
<div className="space-y-3">
|
|
{[1, 2, 3, 4].map((i) => (
|
|
<div key={i} className="flex items-center gap-3 py-3">
|
|
<Skeleton className="h-7 w-7 rounded-full" />
|
|
<div className="flex-1 space-y-2">
|
|
<Skeleton className="h-4 w-48" />
|
|
<Skeleton className="h-3 w-24" />
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
// Statutory deadlines (moms, arbetsgivardeklaration, F-skatt) are generated
|
|
// from the company's tax settings — none present usually means those
|
|
// settings were never filled in, so point there instead of letting the page
|
|
// read as an empty manual todo list. One attn line per page: this setup
|
|
// nudge outranks the overdue-invoices note because it unlocks the page.
|
|
const hasSystemDeadlines = deadlines.some((d) => d.source === 'system')
|
|
|
|
return (
|
|
<div className="space-y-8">
|
|
{pageHeader}
|
|
|
|
{!hasSystemDeadlines ? (
|
|
<AttnLine
|
|
action={{
|
|
label: isGenerating ? t('generating') : t('generate_action'),
|
|
onClick: () => {
|
|
if (!isGenerating) void handleGenerateSystemDeadlines()
|
|
},
|
|
}}
|
|
>
|
|
{t('no_system_deadlines_title')} {t('no_system_deadlines_description')}
|
|
</AttnLine>
|
|
) : overdueInvoices.count > 0 ? (
|
|
<AttnLine
|
|
action={{ label: t('overdue_invoices_action'), href: '/invoices?status=unpaid' }}
|
|
>
|
|
{t('overdue_invoices', { count: overdueInvoices.count })} ·{' '}
|
|
{formatCurrency(overdueInvoices.total)}
|
|
{overdueInvoices.unconverted > 0
|
|
? ` ${t('overdue_invoices_fx', { count: overdueInvoices.unconverted })}`
|
|
: ''}.
|
|
</AttnLine>
|
|
) : null}
|
|
|
|
<DeadlineList
|
|
deadlines={deadlines}
|
|
onDeadlineToggle={handleDeadlineToggle}
|
|
onDeadlineEdit={openEdit}
|
|
/>
|
|
|
|
<DeadlineForm
|
|
open={showForm}
|
|
onOpenChange={(open) => {
|
|
if (!open) {
|
|
setShowForm(false)
|
|
setEditingDeadline(null)
|
|
}
|
|
}}
|
|
onSubmit={handleFormSubmit}
|
|
onDelete={(deadline) => {
|
|
if (deadline.id) {
|
|
const full = deadlines.find((d) => d.id === deadline.id)
|
|
if (full) void handleDeadlineDelete(full)
|
|
}
|
|
}}
|
|
initialData={editingDeadline || undefined}
|
|
customers={customers}
|
|
/>
|
|
</div>
|
|
)
|
|
}
|