feat(entitlements): per-company capability paywall — gate, trial seeding, UI upsells, Stripe checkout (#815)
* feat(entitlements): capability-grant gate substrate (paywall + modularity) Two-axis capability primitive behind the SaaS paywall and the per-tenant modularity/marketplace vision: - migration: capability_grants (entitlement axis, polymorphic company/firm scope), company_capability_config (enablement axis), metered_events (append-only), company_has_capability() RPC reusing the 20260619130100 tenant guard; SELECT-only RLS (writes service-role only, no self-grant). - lib/entitlements: hasCapability/requireCapability gate (mirrors guardSandbox, fail-closed, NEXT_PUBLIC_SELF_HOSTED bypass), capability key namespace, metering helper. - unit (11) + pg-real tests (RPC/RLS/tenant-guard incl. no-self-grant). Gate not yet wired into call sites (follow-up commit). Paid keys: ai, bank_sync, skatteverket, email_send. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): enforce capability gate at paid external-service chokepoints Wire the gate into the paid surfaces (keys: ai, email_send, bank_sync, skatteverket): - AI routes (agent invoke/composer/onboarding stream): requireCapability(ai) - Invoice send (web + v1): requireCapability(email_send) - document-extraction event handler: skip Bedrock extract if ai not entitled - enable-banking + skatteverket crons: per-company hasCapability skip in loop - colocated send-route test mocks updated (requireCapability -> null) Free per founder decision: TIC org lookup, VIES VAT validation, FX auto-fetch, cloud backup, BankID login, all internal bookkeeping. DEPLOY ORDER: fail-closed by design — do NOT deploy before trial/comp grant seeding lands, or companies without grants lose these features. Seeding + Stripe checkout/webhook are the next steps. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): seed trial + comp capability grants Makes the fail-closed gate safely deployable — nobody is locked out at cutover: - AFTER INSERT trigger on companies grants every NEW company a 30-day trial on the PAID keys (ai, bank_sync, skatteverket, email_send), on ALL creation paths (RPC/MCP/direct) — so a new signup can use onboarding AI immediately. - one-time backfill for EXISTING companies: created <=2026-06-07 -> trial ends 2026-07-07; created later -> created_at + 30 days. - permanent comp grants for Arcim/Mattsson (matched by name, no hardcoded UUIDs). - pg tests: clearGrants() for controlled resolver tests + trigger coverage. Trigger fn is SECURITY DEFINER so it writes grants regardless of caller RLS (table has no INSERT policy for authenticated — no self-grant). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): client capability visibility + billing page Non-payers get a clean upsell instead of broken/empty features: - CompanyContext gains capabilities[] + useCapability(key); resolved once server-side in the dashboard layout via getCompanyCapabilities (batched, 2 queries), all three provider branches wired. - /settings/billing upgrade page — the destination upsells point to (Stripe Payment Link via NEXT_PUBLIC_STRIPE_PAYMENT_LINK; degrades to 'coming soon' until automated checkout lands). - ChatEmptyState: non-payer sees an Uppgradera CTA (mirrors the sandbox state). - SendInvoiceDialog: email send disabled + upsell note when email_send missing (extends the existing sandbox-disable pattern). Fast-follow: chat input/FAB + document-inbox empty state + bank/skatteverket/ AI-suggest buttons + a shared capability_blocked->toast backstop. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): gate remaining paid UI surfaces with upsell (fast-follow) disable-with-upsell across the rest of the paid surfaces (keys: bank_sync, skatteverket, ai): - BankSyncNowButton: sync/reconnect disabled + note when !bank_sync (CSV/SIE stays free) - AGIPanel: AGI submit-to-Skatteverket disabled + note when !skatteverket - SkatteverketConnectPanel: BankID connect/reconnect disabled + upsell - ApprovalCard: AI re-propose (correction) gated; manual approve/reject stay free - InvoiceInboxWorkspace: upsell when extraction empty AND !ai (deterministic parse + manual entry unaffected) - AgentTrigger FAB: routes to /settings/billing when !ai (no dead chat) - settings nav: 'Abonnemang'/'Subscription' link to /settings/billing (sv/en) TaxPaymentPanel + TransactionInboxCard intentionally untouched — only local/ deterministic actions there, nothing paid+external to gate. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(entitlements): automated Stripe subscription checkout + webhook Self-serve revenue wired to the same capability-grant primitive: - migration: company_subscriptions (company<->Stripe link/status) + stripe_webhook_events (idempotency) - lib/stripe: getStripe singleton, plan->price mapping, subscription-sync (statusGrantsAccess / subscriptionToState / applySubscriptionState / handleStripeEvent). Active sub -> upsert source='stripe' grants for PAID keys (expiry = period_end + 3d grace); canceled/unpaid -> remove ONLY stripe grants (freeze-and-retain). - routes: POST /api/billing/checkout (hosted subscription Checkout, company_id metadata), POST /api/billing/portal (Customer Portal), POST /api/stripe/webhook (raw-body signature verify, event-id dedup; handles checkout.session.completed + customer.subscription.*) - billing page: real plan-toggle Checkout CTA / manage-subscription portal, gated on isStripeConfigured() - adds stripe@22; unit tests for sync logic Provisioning is webhook-driven (never trusts the success redirect). Needs env: STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_PRICE_MONTHLY, STRIPE_PRICE_YEARLY. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(entitlements): validate UUIDs in capability filter + log webhook errors Addresses PR review (Superagent Security / PR Agent): - has-capability.ts: validate companyId/teamId as UUIDs before interpolating into the PostgREST .or() filter (fail-closed) — removes the latent injection vector flagged in the entitlement gate. Unit tests updated to use UUIDs. - stripe/webhook: log processing failures with event id + type before the generic 500, so a failing webhook is visible to operators. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(salary): always-free AGI XML download for manual filing; only direct API submit is paid Per founder decision on the swedish-compliance-review finding: AGI is a mandatory statutory filing, so producing/downloading the AGI XML must never be paywalled. Adds a free 'Ladda ner AGI-fil' button (generates + downloads the XML for manual upload to Skatteverket's e-service) on all tiers; the gated 'Skicka in underlag' stays the paid convenience (direct API submission — which also requires the paid BankID connection). Upsell reworded to point to the manual path. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(entitlements): harden comp-grant match after prod verification Verified Arcim/Mattsson in prod (pwxtzglxptnnvjrpixpg): the name match was case-sensitive (missed the active 'Arcim technology AB' lowercase variant) and would have granted 3 archived dupes. Now match by org_number (5595386219 / 5595719864) OR case-insensitive name, active companies only — hits exactly the 3 active comp companies, excludes archived dupes and the unrelated 'Amnäs Mattsson, Emil' enskild firma. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
fce6faff2c
commit
4f0a7b1db0
@@ -1,9 +1,11 @@
|
||||
'use client'
|
||||
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { usePathname, useRouter } from 'next/navigation'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import { routeToIntent } from '@/lib/agent/intents/route-mapping'
|
||||
import { useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
// Floating trigger sits above the page bottom-right, opens the AgentSheet when
|
||||
// clicked. Hidden when the sheet is already open so the icon doesn't double up.
|
||||
@@ -25,6 +27,8 @@ import { routeToIntent } from '@/lib/agent/intents/route-mapping'
|
||||
export default function AgentTrigger() {
|
||||
const { openAgentSheet, isOpen, identity } = useAgentSheet()
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
const hasAi = useCapability(CAPABILITY.ai)
|
||||
|
||||
if (isOpen) return null
|
||||
// The /chat surface IS the chat — a floating "Fråga …" pill on top of it
|
||||
@@ -48,18 +52,25 @@ export default function AgentTrigger() {
|
||||
|
||||
const name = identity.displayName?.trim() || 'min assistent'
|
||||
const dispatch = routeToIntent(pathname)
|
||||
const labelText = dispatch.labelSuffix
|
||||
? `Fråga ${name} ${dispatch.labelSuffix}`
|
||||
: `Fråga ${name}`
|
||||
// AI assistant runs on a paid cloud service. Without the capability, opening
|
||||
// the sheet would land the user in a chat whose send is dead. Keep the FAB
|
||||
// visible (it's the conversion surface) but route it to billing instead.
|
||||
const labelText = !hasAi
|
||||
? `Uppgradera för att använda ${name}`
|
||||
: dispatch.labelSuffix
|
||||
? `Fråga ${name} ${dispatch.labelSuffix}`
|
||||
: `Fråga ${name}`
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() =>
|
||||
openAgentSheet({
|
||||
intentId: dispatch.intentId,
|
||||
intentArgs: dispatch.intentArgs,
|
||||
contextRef: dispatch.contextRef,
|
||||
})
|
||||
!hasAi
|
||||
? router.push('/settings/billing')
|
||||
: openAgentSheet({
|
||||
intentId: dispatch.intentId,
|
||||
intentArgs: dispatch.intentArgs,
|
||||
contextRef: dispatch.contextRef,
|
||||
})
|
||||
}
|
||||
// Mobile: sit above the bottom nav (h-16 = 64px) AND the iOS home
|
||||
// indicator (env(safe-area-inset-bottom)). Desktop: standard 20px lift,
|
||||
|
||||
@@ -6,6 +6,8 @@ import { Check, X, Loader2, AlertTriangle, Lock, ShieldCheck, ArrowRight } from
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import type { PendingOperationRejectionCategory } from '@/types'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
@@ -81,6 +83,11 @@ export default function ApprovalCard({
|
||||
periodStatus,
|
||||
onRequestCorrection,
|
||||
}: Props) {
|
||||
// Gating the AI re-propose path only: approving/rejecting the staged
|
||||
// operation is manual ledger work and stays enabled without the AI add-on.
|
||||
// What's paid is feeding a rejection back so the agent generates a *new*
|
||||
// proposal (an LLM call) — that's suppressed when the company lacks `ai`.
|
||||
const hasAi = useCapability(CAPABILITY.ai)
|
||||
const [state, setState] = useState<State>('pending')
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
const [confirmText, setConfirmText] = useState('')
|
||||
@@ -190,7 +197,7 @@ export default function ApprovalCard({
|
||||
// Feed the correction back so the agent re-proposes — only when the user
|
||||
// actually said what was wrong. A bare reject just stops here.
|
||||
const parts = [categoryLabel, reason].filter(Boolean) as string[]
|
||||
if (parts.length > 0) {
|
||||
if (hasAi && parts.length > 0) {
|
||||
onRequestCorrection?.(
|
||||
`Jag avvisade förslaget. Det som var fel: ${parts.join(' — ')}. Föreslå en korrigerad bokning.`,
|
||||
)
|
||||
@@ -345,9 +352,20 @@ export default function ApprovalCard({
|
||||
className="text-xs"
|
||||
aria-label="Notering"
|
||||
/>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Med en anledning eller notering föreslår assistenten en korrigerad bokning direkt.
|
||||
</p>
|
||||
{hasAi ? (
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Med en anledning eller notering föreslår assistenten en korrigerad bokning direkt.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
Din anledning sparas på förslaget. Vill du att assistenten automatiskt
|
||||
föreslår en korrigerad bokning?{' '}
|
||||
<Link href="/settings/billing" className="font-medium text-foreground hover:underline">
|
||||
Uppgradera
|
||||
</Link>
|
||||
.
|
||||
</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
|
||||
@@ -6,7 +6,8 @@ import { useRouter } from 'next/navigation'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAgentSheet } from './AgentSheetProvider'
|
||||
import AgentAvatar from './AgentAvatar'
|
||||
import { useCompanyOptional } from '@/contexts/CompanyContext'
|
||||
import { useCompanyOptional, useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
|
||||
// Tiny client component for /chat empty state. Reads the agent identity from
|
||||
@@ -37,6 +38,7 @@ export default function ChatEmptyState() {
|
||||
const companyCtx = useCompanyOptional()
|
||||
const router = useRouter()
|
||||
const isSandbox = companyCtx?.isSandbox ?? false
|
||||
const hasAi = useCapability(CAPABILITY.ai)
|
||||
const name = identity.displayName?.trim() || 'din assistent'
|
||||
|
||||
if (isSandbox) {
|
||||
@@ -74,6 +76,29 @@ export default function ChatEmptyState() {
|
||||
)
|
||||
}
|
||||
|
||||
if (!hasAi) {
|
||||
return (
|
||||
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
|
||||
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
|
||||
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
|
||||
<div className="rounded-lg border border-border bg-secondary/40 px-5 py-4 max-w-md mb-6 text-left">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Ingår i abonnemanget
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
|
||||
AI-assistenten använder en betald molntjänst. Uppgradera för att låta
|
||||
{' '}{name} kategorisera transaktioner, granska leverantörsfakturor
|
||||
och svara på frågor om din bokföring.
|
||||
</p>
|
||||
</div>
|
||||
<Button size="lg" asChild>
|
||||
<Link href="/settings/billing">Uppgradera för att använda {name}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Hidden on mobile — the sidebar IS the page when no conversation is open.
|
||||
// On desktop, fills the right pane with a centered prompt.
|
||||
return (
|
||||
|
||||
@@ -32,10 +32,13 @@ import {
|
||||
Circle,
|
||||
X,
|
||||
ChevronDown,
|
||||
Sparkles,
|
||||
} from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import type { WorkspaceComponentProps } from '@/lib/extensions/workspace-registry'
|
||||
import type { InvoiceExtractionResult } from '@/types'
|
||||
import BookDirectlyDialog from '@/components/extensions/general/BookDirectlyDialog'
|
||||
@@ -105,6 +108,24 @@ function pickSupplierName(item: InboxItem): string | null {
|
||||
return item.extracted_data?.supplier?.name ?? null
|
||||
}
|
||||
|
||||
// True when extraction produced at least one usable field. Distinguishes a
|
||||
// deterministically-parsed underlag (fields present — render the editable
|
||||
// list) from an item whose extracted_data is null/empty (AI never ran, or ran
|
||||
// and found nothing). Currency is ignored because emptyExtraction() seeds it
|
||||
// to 'SEK', so it is never a sign that extraction actually happened.
|
||||
function hasAnyExtractedField(data: InvoiceExtractionResult | null): boolean {
|
||||
if (!data) return false
|
||||
const s = data.supplier
|
||||
const inv = data.invoice
|
||||
const t = data.totals
|
||||
return Boolean(
|
||||
s?.name || s?.orgNumber || s?.vatNumber || s?.bankgiro || s?.plusgiro ||
|
||||
inv?.invoiceNumber || inv?.invoiceDate || inv?.dueDate || inv?.paymentReference ||
|
||||
t?.subtotal != null || t?.vatAmount != null || t?.total != null ||
|
||||
(data.lineItems?.length ?? 0) > 0 || (data.vatBreakdown?.length ?? 0) > 0
|
||||
)
|
||||
}
|
||||
|
||||
// Lifecycle stage of an inbox item. Single source of truth shared by the list
|
||||
// filter, the count pills, and the row icons so they never drift apart.
|
||||
//
|
||||
@@ -1427,6 +1448,7 @@ function FieldsRail({
|
||||
onRetryRequested: () => Promise<void>
|
||||
}) {
|
||||
const { toast } = useToast()
|
||||
const hasAi = useCapability(CAPABILITY.ai)
|
||||
const data = item.extracted_data
|
||||
const isProcessed = !!item.created_supplier_invoice_id
|
||||
const isBookedDirectly = !isProcessed && !!item.created_journal_entry_id
|
||||
@@ -1557,6 +1579,24 @@ function FieldsRail({
|
||||
<Skeleton key={i} className="h-8 w-full" />
|
||||
))}
|
||||
</div>
|
||||
) : !hasAnyExtractedField(data) && !hasAi ? (
|
||||
// No fields were extracted (AI never ran) and the company doesn't have
|
||||
// the AI capability. Show an upsell in place of the blank field list —
|
||||
// upload and manual entry stay available via the actions below.
|
||||
<div className="rounded-lg border border-border bg-secondary/40 px-4 py-3 text-left">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
AI-tolkning ingår i abonnemanget
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1.5 leading-relaxed">
|
||||
Uppgradera för att låta accounted läsa av leverantör, belopp och
|
||||
moms automatiskt. Du kan fortfarande fylla i fälten manuellt eller
|
||||
koppla dokumentet till en transaktion nedan.
|
||||
</p>
|
||||
<Button size="sm" className="mt-3" asChild>
|
||||
<Link href="/settings/billing">Uppgradera</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<EditableFieldsList
|
||||
itemId={item.id}
|
||||
|
||||
@@ -16,7 +16,8 @@ import { JournalEntryReviewContent } from '@/components/bookkeeping/JournalEntry
|
||||
import { proposeSendLines } from '@/lib/bookkeeping/propose-send-lines'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCompany, useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { Loader2, Mail, Send } from 'lucide-react'
|
||||
import type { Invoice, InvoiceItem, Customer, EntityType } from '@/types'
|
||||
|
||||
@@ -44,6 +45,7 @@ export default function SendInvoiceDialog({
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
const { company, isSandbox } = useCompany()
|
||||
const canEmail = useCapability(CAPABILITY.email_send)
|
||||
const t = useTranslations('invoice_send_dialog')
|
||||
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
@@ -216,6 +218,15 @@ export default function SendInvoiceDialog({
|
||||
flödet.
|
||||
</div>
|
||||
)}
|
||||
{!isSandbox && !canEmail && mode === 'email' && (
|
||||
<div className="rounded-lg border border-border bg-secondary/40 px-3 py-2.5 text-sm text-muted-foreground">
|
||||
E-postutskick kräver ett abonnemang.{' '}
|
||||
<a href="/settings/billing" className="underline underline-offset-2">
|
||||
Uppgradera
|
||||
</a>{' '}
|
||||
eller använd «Markera som skickad».
|
||||
</div>
|
||||
)}
|
||||
{showJournalPreview ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
@@ -258,9 +269,15 @@ export default function SendInvoiceDialog({
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirm}
|
||||
disabled={isSubmitting || !isInitialized || (isSandbox && mode === 'email')}
|
||||
disabled={isSubmitting || !isInitialized || (mode === 'email' && (isSandbox || !canEmail))}
|
||||
className="w-full sm:w-auto min-h-11"
|
||||
title={isSandbox && mode === 'email' ? 'E-postutskick är avstängt i sandlådan' : undefined}
|
||||
title={
|
||||
mode === 'email' && isSandbox
|
||||
? 'E-postutskick är avstängt i sandlådan'
|
||||
: mode === 'email' && !canEmail
|
||||
? 'E-postutskick kräver ett abonnemang'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
} from 'lucide-react'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
interface AGIPanelProps {
|
||||
salaryRunId: string
|
||||
@@ -112,6 +114,8 @@ export function AGIPanel(props: AGIPanelProps) {
|
||||
onChange,
|
||||
} = props
|
||||
|
||||
const hasSkatteverket = useCapability(CAPABILITY.skatteverket)
|
||||
|
||||
const [extensionDisabled, setExtensionDisabled] = useState(false)
|
||||
const [status, setStatus] = useState<ConnectionStatus | null>(null)
|
||||
const [submission, setSubmission] = useState<SubmissionState | null>(null)
|
||||
@@ -411,6 +415,35 @@ export function AGIPanel(props: AGIPanelProps) {
|
||||
* On DONE_REJECTED we surface the validation findings; the user can still
|
||||
* choose to save (so they can fix it in Mina Sidor) or abort.
|
||||
*/
|
||||
// Always-free: generate + download the AGI XML so the user can file manually
|
||||
// in Skatteverket's e-service. AGI is a mandatory statutory filing, so this
|
||||
// path must never be paywalled — only the direct API submission below is paid.
|
||||
const handleDownloadXml = async () => {
|
||||
setActionLoading('download')
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/salary/runs/${salaryRunId}/agi/xml`)
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}))
|
||||
throw new Error(data.error || 'Kunde inte generera AGI-filen')
|
||||
}
|
||||
const blob = await res.blob()
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = `AGI_${period ?? 'underlag'}.xml`
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
a.remove()
|
||||
URL.revokeObjectURL(url)
|
||||
onChange?.()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Kunde inte ladda ner AGI-filen')
|
||||
} finally {
|
||||
setActionLoading(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setActionLoading('submit')
|
||||
setError(null)
|
||||
@@ -870,11 +903,30 @@ export function AGIPanel(props: AGIPanelProps) {
|
||||
|
||||
{!readOnly && !isSigned && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleDownloadXml}
|
||||
disabled={actionLoading === 'download'}
|
||||
title="Ladda ner AGI-filen (XML) för manuell inlämning hos Skatteverket"
|
||||
>
|
||||
{actionLoading === 'download' ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<Download className="mr-1.5 h-3.5 w-3.5" />
|
||||
)}
|
||||
Ladda ner AGI-fil
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={handleSubmit}
|
||||
disabled={actionLoading === 'submit'}
|
||||
disabled={actionLoading === 'submit' || !hasSkatteverket}
|
||||
title={
|
||||
!hasSkatteverket
|
||||
? 'Inlämning av AGI till Skatteverket ingår i en uppgraderad plan.'
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{actionLoading === 'submit' ? (
|
||||
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
|
||||
@@ -925,6 +977,17 @@ export function AGIPanel(props: AGIPanelProps) {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!readOnly && !isSigned && !hasSkatteverket && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Ladda ner AGI-filen ovan och lämna in den manuellt i Skatteverkets
|
||||
e-tjänst — eller{' '}
|
||||
<a href="/settings/billing" className="font-medium underline hover:no-underline">
|
||||
uppgradera
|
||||
</a>{' '}
|
||||
för att skicka in direkt härifrån.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import type { BillingPlan } from '@/lib/stripe/client'
|
||||
|
||||
/**
|
||||
* Client CTA for the billing page. Active subscribers get the Stripe Customer
|
||||
* Portal (manage/cancel); everyone else gets a plan toggle + Checkout. Both
|
||||
* POST to a route that returns a hosted Stripe URL we redirect to.
|
||||
*/
|
||||
export function BillingActions({ isActive, configured }: { isActive: boolean; configured: boolean }) {
|
||||
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 }
|
||||
if (!res.ok || !data.url) throw new Error(data.error || 'Något gick fel')
|
||||
window.location.href = data.url
|
||||
} catch (e) {
|
||||
toast({
|
||||
title: 'Kunde inte öppna betalningen',
|
||||
description: e instanceof Error ? e.message : undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (isActive) {
|
||||
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 sm:w-auto">
|
||||
Uppgradering öppnar snart
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="inline-flex rounded-lg border border-border p-1 text-sm">
|
||||
{(['monthly', 'yearly'] as BillingPlan[]).map((p) => (
|
||||
<button
|
||||
key={p}
|
||||
type="button"
|
||||
onClick={() => setPlan(p)}
|
||||
className={`rounded-md px-3 py-1.5 transition-colors ${
|
||||
plan === p ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground'
|
||||
}`}
|
||||
>
|
||||
{p === 'monthly' ? 'Månadsvis' : 'Årsvis'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div>
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={() => go('/api/billing/checkout', { plan })}
|
||||
disabled={loading}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
Uppgradera
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { CheckCircle2, ExternalLink, ShieldOff, FlaskConical, ShieldAlert } from 'lucide-react'
|
||||
|
||||
type Environment = 'test' | 'prod'
|
||||
@@ -25,6 +27,7 @@ type Status =
|
||||
export function SkatteverketConnectPanel() {
|
||||
const t = useTranslations('settings_skatteverket_connect')
|
||||
const { toast } = useToast()
|
||||
const hasSkatteverket = useCapability(CAPABILITY.skatteverket)
|
||||
const [status, setStatus] = useState<Status | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [disconnecting, setDisconnecting] = useState(false)
|
||||
@@ -118,7 +121,19 @@ export function SkatteverketConnectPanel() {
|
||||
code: (chunks) => <span className="font-mono">{chunks}</span>,
|
||||
})}
|
||||
</div>
|
||||
<Button onClick={startConnect} disabled={status?.disabled}>
|
||||
{!hasSkatteverket && (
|
||||
<div className="rounded-lg border border-border bg-secondary/40 px-3 py-2.5 text-sm text-muted-foreground">
|
||||
Anslutning till Skatteverket kräver ett abonnemang.{' '}
|
||||
<a href="/settings/billing" className="underline underline-offset-2">
|
||||
Uppgradera
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={startConnect}
|
||||
disabled={status?.disabled || !hasSkatteverket}
|
||||
title={!hasSkatteverket ? 'Anslutning till Skatteverket kräver ett abonnemang' : undefined}
|
||||
>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
{t('connect_with_bankid')}
|
||||
</Button>
|
||||
@@ -204,7 +219,11 @@ export function SkatteverketConnectPanel() {
|
||||
|
||||
<div className="flex gap-2 pt-2">
|
||||
{(status.expired || !status.canRefresh || !scopes.includes('skattekonto') || !scopes.includes('agd')) && (
|
||||
<Button onClick={startConnect} disabled={status.disabled}>
|
||||
<Button
|
||||
onClick={startConnect}
|
||||
disabled={status.disabled || !hasSkatteverket}
|
||||
title={!hasSkatteverket ? 'Anslutning till Skatteverket kräver ett abonnemang' : undefined}
|
||||
>
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
{t('reconnect')}
|
||||
</Button>
|
||||
|
||||
@@ -47,6 +47,7 @@ export function useSettingsNavItems(): { items: SettingsNavItem[]; groups: Setti
|
||||
// Importera/Exportera. Team stays hidden (show:false) until enabled.
|
||||
const defs: Array<SettingsNavItem & { show: boolean }> = [
|
||||
{ id: 'account', href: '/settings/account', label: t('account'), group: 'account', show: true },
|
||||
{ id: 'billing', href: '/settings/billing', label: t('billing'), group: 'account', show: true },
|
||||
{ id: 'company', href: '/settings/company', label: t('company'), group: 'company', show: hasCompany },
|
||||
{ id: 'bookkeeping', href: '/settings/bookkeeping', label: t('bookkeeping'), group: 'accounting', show: hasCompany },
|
||||
{ id: 'tax', href: '/settings/tax', label: t('tax'), group: 'accounting', show: hasCompany },
|
||||
|
||||
@@ -14,7 +14,8 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCompany, useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
interface BankConn {
|
||||
id: string
|
||||
@@ -38,6 +39,7 @@ export default function BankSyncNowButton() {
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
const { company } = useCompany()
|
||||
const hasBankSync = useCapability(CAPABILITY.bank_sync)
|
||||
const [connections, setConnections] = useState<BankConn[] | null>(null)
|
||||
const [busyId, setBusyId] = useState<string | null>(null)
|
||||
|
||||
@@ -148,35 +150,54 @@ export default function BankSyncNowButton() {
|
||||
const isBusy = busyId !== null
|
||||
const syncLabel = isBusy ? t('bank_sync_button_syncing') : t('bank_sync_button_now')
|
||||
|
||||
// Bank sync (and reconnect) is a paid external PSD2 call. Without the
|
||||
// capability we keep the button VISIBLE as the conversion surface but inert,
|
||||
// and surface an Uppgradera link. CSV/SIE import stays free (separate UI).
|
||||
const gateTitle = !hasBankSync ? 'Bankkoppling kräver ett abonnemang' : undefined
|
||||
const upsellNote = !hasBankSync ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Kräver abonnemang.{' '}
|
||||
<a href="/settings/billing" className="underline underline-offset-2">
|
||||
Uppgradera
|
||||
</a>
|
||||
</span>
|
||||
) : null
|
||||
|
||||
if (connections.length === 1) {
|
||||
const conn = connections[0]
|
||||
const needsReconnect = conn.status !== 'active'
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1.5 px-2.5 text-xs"
|
||||
disabled={isBusy}
|
||||
onClick={() => runFor(conn)}
|
||||
>
|
||||
{isBusy ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
)}
|
||||
<span>{needsReconnect ? t('bank_reconnect') : syncLabel}</span>
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1.5 px-2.5 text-xs"
|
||||
disabled={isBusy || !hasBankSync}
|
||||
title={gateTitle}
|
||||
onClick={() => runFor(conn)}
|
||||
>
|
||||
{isBusy ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3.5 w-3.5" />
|
||||
)}
|
||||
<span>{needsReconnect ? t('bank_reconnect') : syncLabel}</span>
|
||||
</Button>
|
||||
{upsellNote}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1.5 px-2.5 text-xs"
|
||||
disabled={isBusy}
|
||||
disabled={isBusy || !hasBankSync}
|
||||
title={gateTitle}
|
||||
>
|
||||
{isBusy ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
@@ -200,5 +221,7 @@ export default function BankSyncNowButton() {
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{upsellNote}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user