Files
accounted/components/settings/BillingActions.tsx
T
Mattsson e11f70b347 Bug/gh issues fiz (#1103)
* refactor: optimize page loading and data fetching

* fix: resolve recurring production runtime errors

* feat: add MCP company and customer updates

* fix: handle year-end tax adjustments

* feat: harden annual report compliance

* fix: expand invoice logo and font support

* fix: sanitize API route error responses

* fix: sanitize user-facing error messages

* feat: persist onboarding and tax assessment notices

* fix: reduce cloud backup audit churn

* feat: refine invoice editor layout

* fix: show saved tax adjustments in INK2

* fix: complete annual report API mappings

* docs: record operational safeguards and decisions

* fix: harden annual report review findings

* fix: adjust column span for description based on VAT registration

* New css class name
2026-07-21 23:00:15 +02:00

138 lines
4.6 KiB
TypeScript

'use client'
import { useState, type ReactNode } from 'react'
import { ChevronRight } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { formatDateLong } from '@/lib/utils'
import type { BillingPlan } from '@/lib/stripe/client'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
const PRICE: Record<BillingPlan, { amount: string; suffix: string; sub: string; cta: string }> = {
monthly: {
amount: '199 kr',
suffix: '/ mån exkl. moms',
sub: '248,75 kr/mån inkl. moms. Faktureras månadsvis.',
cta: 'Aktivera abonnemang: 199 kr/mån',
},
yearly: {
amount: '166 kr',
suffix: '/ mån exkl. moms',
sub: '1 999 kr/år exkl. moms (2 498,75 kr inkl.). Du betalar för 10 månader.',
cta: 'Aktivera årsabonnemang: 1 999 kr/år',
},
}
/**
* Interactive billing CTA. Paying companies get the Stripe Customer Portal
* (manage/cancel); everyone else gets a reactive plan picker + Checkout. Both
* POST to a route that returns a hosted Stripe URL we redirect to.
*
* `firstChargeAt`: when the checkout route will defer the first charge to the
* trial's end (see billing/checkout), the date it lands. Shifts the CTA from
* "pay now" to "0 kr idag": the strongest risk-reversal we can make truthfully.
*/
export function BillingActions({
isPaying,
configured,
firstChargeAt = null,
}: {
isPaying: boolean
configured: boolean
firstChargeAt?: string | null
}) {
const { toast } = useToast()
const [loading, setLoading] = useState(false)
const [plan, setPlan] = useState<BillingPlan>('yearly')
async function go(endpoint: string, payload?: Record<string, unknown>) {
setLoading(true)
try {
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload ?? {}),
})
const data = (await res.json().catch(() => ({}))) as {
url?: string
error?: string | { message?: string }
}
const errorMessage = typeof data.error === 'string' ? data.error : data.error?.message
if (!res.ok || !data.url) throw new Error(errorMessage || 'Något gick fel')
window.location.href = data.url
} catch (e) {
toast({
title: 'Kunde inte öppna betalningen',
description: e instanceof Error ? getUserErrorMessage(e) : undefined,
variant: 'destructive',
})
setLoading(false)
}
}
if (isPaying) {
return (
<Button size="lg" onClick={() => go('/api/billing/portal')} disabled={loading} className="w-full sm:w-auto">
Hantera abonnemang
</Button>
)
}
if (!configured) {
return (
<Button size="lg" disabled className="w-full">
Uppgradering öppnar snart
</Button>
)
}
const segment = (p: BillingPlan, label: ReactNode) => (
<button
type="button"
onClick={() => setPlan(p)}
className={`flex items-center rounded-md px-3 py-2 transition-colors ${
plan === p ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground'
}`}
>
{label}
</button>
)
return (
<div className="space-y-4">
<div>
<div className="flex items-baseline gap-2">
<span className="font-display text-3xl tracking-tight tabular-nums">{PRICE[plan].amount}</span>
<span className="text-muted-foreground">{PRICE[plan].suffix}</span>
</div>
<p className="text-sm text-muted-foreground mt-1">{PRICE[plan].sub}</p>
</div>
<div className="inline-flex rounded-lg border border-border p-1 text-sm">
{segment('monthly', 'Månadsvis')}
{segment(
'yearly',
<>
Årsvis
<span className="ml-2 text-xs text-muted-foreground">Spara 2 mån</span>
</>,
)}
</div>
<Button size="lg" onClick={() => go('/api/billing/checkout', { plan })} disabled={loading} className="w-full">
{loading ? 'Öppnar…' : firstChargeAt ? 'Starta abonnemanget: 0 kr idag' : PRICE[plan].cta}
{!loading && <ChevronRight className="h-4 w-4" />}
</Button>
{firstChargeAt && (
<p className="text-xs text-muted-foreground text-center">
Första debiteringen sker {formatDateLong(firstChargeAt)}, när provperioden slutar. Avslutar du innan dess
kostar det ingenting.
</p>
)}
<p className="text-xs text-muted-foreground text-center">
Ingen bindningstid · Avsluta när du vill · Säker betalning via Stripe
</p>
</div>
)
}