Files
accounted/components/invoices/SendInvoiceDialog.tsx
T
Jakob Wennberg 4f0a7b1db0 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>
2026-06-29 15:56:19 +02:00

296 lines
9.9 KiB
TypeScript

'use client'
import { useState, useEffect, useMemo } from 'react'
import { useTranslations } from 'next-intl'
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 { 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'
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 { company, isSandbox } = useCompany()
const canEmail = useCapability(CAPABILITY.email_send)
const t = useTranslations('invoice_send_dialog')
const [isSubmitting, setIsSubmitting] = useState(false)
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)
return
}
let cancelled = false
async function init() {
try {
if (!company?.id) throw new Error(t('no_active_company'))
// Fetch company settings
const { data: settings, error } = await supabase
.from('company_settings')
.select('accounting_method, entity_type')
.eq('company_id', company.id)
.maybeSingle()
if (error) throw new Error(t('company_settings_failed'))
if (cancelled) return
// Fetch fiscal period for the invoice date
const { data: period } = await supabase
.from('fiscal_periods')
.select('name')
.eq('company_id', company.id)
.lte('start_date', invoice.invoice_date)
.gte('end_date', invoice.invoice_date)
.maybeSingle()
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: t('load_failed_title'),
description: err instanceof Error ? err.message : t('try_again'),
variant: 'destructive',
})
onOpenChange(false)
}
}
init()
return () => { cancelled = true }
}, [open, invoice.id, invoice.invoice_date, company?.id])
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 || t('send_failed_fallback'))
}
onSuccess()
if (mode === 'email') {
onOpenChange(false)
toast({
title: t('send_success_title'),
description: data.message || t('send_success_default', { email: invoice.customer.email ?? '' }),
})
} else {
// For manual send, just close — no email to confirm
onOpenChange(false)
toast({
title: t('mark_success_title'),
description: accountingMethod === 'accrual'
? t('mark_success_voucher_created')
: undefined,
})
}
} catch (error) {
toast({
title: t('send_failed_title'),
description: error instanceof Error ? error.message : t('try_again'),
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' ? t('title_email') : t('title_manual')}{invoice.invoice_number ? t('title_suffix', { number: invoice.invoice_number }) : ''}
</DialogTitle>
<DialogDescription>
{formatCurrency(invoice.total, invoice.currency)}
{invoice.currency !== 'SEK' && invoice.total_sek && (
<>{t('description_sek_suffix', { amount: formatCurrency(invoice.total_sek) })}</>
)}
{mode === 'email' && invoice.customer.email && (
<>{t('description_to_email', { email: invoice.customer.email })}</>
)}
</DialogDescription>
</DialogHeader>
{!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">
{isSandbox && mode === 'email' && (
<div className="rounded-lg border border-border bg-secondary/40 px-3 py-2.5 text-sm text-muted-foreground">
E-postutskick är avstängt i sandlådan. Använd istället
&laquo;Markera som skickad&raquo; för att testa det resterande
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 &laquo;Markera som skickad&raquo;.
</div>
)}
{showJournalPreview ? (
<>
<p className="text-sm text-muted-foreground">
{t('journal_preview_intro')}
</p>
<JournalEntryReviewContent
periodName={periodName}
entryDate={invoice.invoice_date}
description={t('voucher_description', {
numberSpace: invoice.invoice_number ? ` ${invoice.invoice_number}` : '',
customerSuffix: 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'
? t('explain_cash')
: mode === 'email'
? t('explain_email', { email: invoice.customer.email ?? '' })
: t('explain_manual')}
</p>
)}
</div>
)}
<DialogFooter>
<Button
variant="outline"
onClick={handleClose}
disabled={isSubmitting}
className="w-full sm:w-auto min-h-11"
>
{t('cancel')}
</Button>
<Button
onClick={handleConfirm}
disabled={isSubmitting || !isInitialized || (mode === 'email' && (isSandbox || !canEmail))}
className="w-full sm:w-auto min-h-11"
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" />
) : mode === 'email' ? (
<Mail className="mr-2 h-4 w-4" />
) : (
<Send className="mr-2 h-4 w-4" />
)}
{mode === 'email' ? t('send_invoice') : t('mark_as_sent')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}