feat: add user locale preference to user_preferences table (#555)
* feat: add user locale preference to user_preferences table
- Introduced a new column 'locale' in the user_preferences table to store per-user UI language preferences.
- Added a CHECK constraint to ensure only supported locales ('sv', 'en') are allowed.
- Triggered a schema reload notification for the changes.
chore: declare CSS module support in TypeScript
- Added a declaration for CSS modules in globals.d.ts to enable TypeScript support for importing CSS files.
* feat: add Swish as an invoice payment method in company settings
This commit is contained in:
@@ -352,6 +352,54 @@ Never create a NUL/nul file: \gnubok\NUL
|
||||
|
||||
---
|
||||
|
||||
## i18n
|
||||
|
||||
The app is Swedish-first and bilingual (Swedish + English) for UI chrome. Locale is per-user on `user_preferences.locale` (`'sv' | 'en'`, default `'sv'`), resolved server-side via next-intl. The user picker lives at `/settings/account`.
|
||||
|
||||
**Pattern for new UI:**
|
||||
|
||||
```tsx
|
||||
// Server component
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
const t = await getTranslations('namespace')
|
||||
|
||||
// Client component
|
||||
'use client'
|
||||
import { useTranslations } from 'next-intl'
|
||||
const t = useTranslations('namespace')
|
||||
|
||||
// In JSX
|
||||
<button>{t('save')}</button>
|
||||
```
|
||||
|
||||
Add new strings to both `messages/sv.json` and `messages/en.json` under the matching namespace (`common`, `nav`, `auth`, `settings`, `empty`, etc.). Never ship an English key without a Swedish counterpart — Swedish is the default and the fallback.
|
||||
|
||||
**Locale-aware formatters:**
|
||||
- `formatCurrency(amount)` — stays SEK with sv-SE conventions in BOTH locales (Swedish accounting standard, not a UI string).
|
||||
- `formatDate(date)` — ISO `yyyy-MM-dd`, locale-independent.
|
||||
- `formatDateLong(date, locale)` — accepts locale. In client components use `useFormat()` (`lib/hooks/use-format.ts`) which pulls the active locale.
|
||||
|
||||
**Error messages:** `getErrorMessage(err, { locale, context })` from `lib/errors/get-error-message.ts` is bilingual on the primary maps (Postgres codes, HTTP statuses, context fallbacks, generic fallback). The structured error envelope (`{ error: { code, message, message_en } }`) already carries both; the function picks the right one from `locale`. Pass `useLocale()` / `getLocale()` as the locale arg.
|
||||
|
||||
**Stays Swedish — do NOT translate:**
|
||||
|
||||
| Surface | Reason |
|
||||
|---|---|
|
||||
| Invoice PDFs (`lib/invoices/pdf-template.tsx`) | Sent to the user's customers, who are typically Swedish |
|
||||
| Customer email templates (`lib/email/invoice-templates.ts`, `reminder-templates.ts`) | Same — recipient is the customer, not the app user |
|
||||
| Year-end wizard (`app/(dashboard)/bookkeeping/year-end/page.tsx`) | Statutory bokslut terminology; English would be misleading |
|
||||
| Journal entry editor (`app/(dashboard)/bookkeeping/[id]/page.tsx`) | Deeply regulatory (verifikat, voucher numbers, BAS) |
|
||||
| INK2 / NE-bilaga / SRU (`lib/reports/ink2/**`, `lib/reports/ne-bilaga/**`, `lib/reports/sru-*`) | Skatteverket forms — field codes and labels are statutory |
|
||||
| SIE export (`lib/reports/sie-export.ts`) | SIE format is Swedish-only by spec (#KONTO, #VER, etc.) |
|
||||
| BAS chart names (`lib/bookkeeping/bas-data/**`) | Standardized Swedish account names per BAS 2026 |
|
||||
| VAT declaration ruta labels (`lib/reports/vat-declaration*.ts`) | Momsdeklaration field labels are Skatteverket form labels |
|
||||
| Salary AGI / KU (`lib/salary/agi*`, `lib/salary/ku*`) | Skatteverket-bound forms |
|
||||
| Bookkeeping engine domain errors ("Verifikationen balanserar inte", "Bokföringen är låst") | Regulatory concepts; English equivalents would be ambiguous |
|
||||
|
||||
Anything in the table above stays Swedish in BOTH locales. If you find yourself reaching for `t()` inside one of these files, stop and reconsider.
|
||||
|
||||
---
|
||||
|
||||
## Design Context
|
||||
|
||||
### Users
|
||||
|
||||
+65
-63
@@ -2,6 +2,7 @@
|
||||
|
||||
import { Suspense, useState, useEffect } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import Link from 'next/link'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -10,7 +11,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Mail, ArrowLeft, KeyRound } from 'lucide-react'
|
||||
import Image from 'next/image'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { isBankIdEnabled } from '@/lib/auth/bankid'
|
||||
import { BankIdAuth } from '@/components/auth/BankIdAuth'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
@@ -43,6 +44,9 @@ function LoginPageContent() {
|
||||
const callbackError = searchParams.get('error')
|
||||
const supabase = createClient()
|
||||
const bankIdEnabled = isBankIdEnabled()
|
||||
const tAuth = useTranslations('auth')
|
||||
const tCommon = useTranslations('common')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
// Reset cooldown timer
|
||||
useEffect(() => {
|
||||
@@ -72,8 +76,8 @@ function LoginPageContent() {
|
||||
|
||||
if (result.error) {
|
||||
toast({
|
||||
title: 'Inloggning misslyckades',
|
||||
description: 'Kunde inte slutföra BankID-inloggningen.',
|
||||
title: tAuth('login_failed_title'),
|
||||
description: tAuth('login_failed_bankid'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -89,8 +93,8 @@ function LoginPageContent() {
|
||||
if (error) {
|
||||
console.error('[login] BankID verifyOtp failed', error)
|
||||
toast({
|
||||
title: 'Inloggning misslyckades',
|
||||
description: 'Kunde inte slutfora BankID-inloggningen.',
|
||||
title: tAuth('login_failed_title'),
|
||||
description: tAuth('login_failed_bankid'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -126,8 +130,8 @@ function LoginPageContent() {
|
||||
} catch (error) {
|
||||
console.error('[login] BankID complete error', error)
|
||||
toast({
|
||||
title: 'Inloggning misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: tAuth('login_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -150,10 +154,10 @@ function LoginPageContent() {
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: 'Inloggning misslyckades',
|
||||
title: tAuth('login_failed_title'),
|
||||
description: error.message === 'Invalid login credentials'
|
||||
? 'Fel e-post eller lösenord.'
|
||||
: getErrorMessage(error, { context: 'auth' }),
|
||||
? tAuth('login_invalid_credentials')
|
||||
: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -195,8 +199,8 @@ function LoginPageContent() {
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Inloggning misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: tAuth('login_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -218,8 +222,8 @@ function LoginPageContent() {
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: 'Kunde inte skicka återställningslänk',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: tAuth('reset_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -229,13 +233,13 @@ function LoginPageContent() {
|
||||
setResetCooldownUntil(Date.now() + 60_000)
|
||||
setIsEmailSent(true)
|
||||
toast({
|
||||
title: 'Återställningslänk skickad!',
|
||||
description: 'Kolla din inkorg för att återställa lösenordet.',
|
||||
title: tAuth('reset_sent_title'),
|
||||
description: tAuth('reset_sent_body'),
|
||||
})
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Kunde inte skicka återställningslänk',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: tAuth('reset_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -255,17 +259,23 @@ function LoginPageContent() {
|
||||
</div>
|
||||
|
||||
<div className="text-center space-y-2">
|
||||
<h1 className="text-2xl font-medium tracking-tight">Kolla din e-post</h1>
|
||||
<h1 className="text-2xl font-medium tracking-tight">{tAuth('email_sent_title')}</h1>
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
Vi har skickat en {showResetPassword ? 'återställningslänk' : 'inloggningslänk'} till{' '}
|
||||
<span className="font-medium text-foreground">{email}</span>
|
||||
{showResetPassword
|
||||
? tAuth.rich('email_sent_body_reset', {
|
||||
email,
|
||||
strong: (chunks) => <span className="font-medium text-foreground">{chunks}</span>,
|
||||
})
|
||||
: tAuth.rich('email_sent_body_login', {
|
||||
email,
|
||||
strong: (chunks) => <span className="font-medium text-foreground">{chunks}</span>,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border bg-card p-4">
|
||||
<p className="text-sm text-muted-foreground text-center leading-relaxed">
|
||||
Klicka på länken i e-posten för att {showResetPassword ? 'återställa ditt lösenord' : 'logga in'}.
|
||||
Länken är giltig i 1 timme.
|
||||
{showResetPassword ? tAuth('email_sent_hint_reset') : tAuth('email_sent_hint_login')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -278,7 +288,7 @@ function LoginPageContent() {
|
||||
}}
|
||||
>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
{tCommon('back')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -296,22 +306,22 @@ function LoginPageContent() {
|
||||
<KeyRound className="h-7 w-7 text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="text-2xl font-medium tracking-tight">Återställ lösenord</h1>
|
||||
<h1 className="text-2xl font-medium tracking-tight">{tAuth('reset_title')}</h1>
|
||||
<p className="text-muted-foreground text-sm mt-2">
|
||||
Ange din e-postadress så skickar vi en återställningslänk
|
||||
{tAuth('reset_subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border bg-card p-6" style={{ boxShadow: 'var(--shadow-md)' }}>
|
||||
<form onSubmit={handleResetPassword} className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-postadress</Label>
|
||||
<Label htmlFor="email">{tAuth('email_label')}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="[email protected]"
|
||||
placeholder={tAuth('email_placeholder')}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
@@ -323,12 +333,12 @@ function LoginPageContent() {
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Skickar...
|
||||
{tAuth('reset_sending')}
|
||||
</>
|
||||
) : resetCooldownUntil ? (
|
||||
`Vänta ${resetCooldownRemaining}s`
|
||||
tAuth('reset_cooldown', { seconds: resetCooldownRemaining })
|
||||
) : (
|
||||
'Skicka återställningslänk'
|
||||
tAuth('reset_button')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
@@ -340,7 +350,7 @@ function LoginPageContent() {
|
||||
onClick={() => setShowResetPassword(false)}
|
||||
>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka till inloggning
|
||||
{tAuth('back_to_login')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -360,7 +370,7 @@ function LoginPageContent() {
|
||||
priority
|
||||
/>
|
||||
<p className="text-muted-foreground text-sm mt-3">
|
||||
Logga in för att hantera din ekonomi
|
||||
{tAuth('login_subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -368,16 +378,16 @@ function LoginPageContent() {
|
||||
{callbackError === 'auth_error' && (
|
||||
<div className="mb-5 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
|
||||
<p className="text-sm font-medium text-destructive">
|
||||
Återställningslänken fungerade inte
|
||||
{tAuth('callback_error_title')}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-destructive/90">
|
||||
Länken har gått ut eller använts redan.{' '}
|
||||
{tAuth('callback_error_body')}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowResetPassword(true)}
|
||||
className="font-medium underline underline-offset-2"
|
||||
>
|
||||
Begär en ny återställningslänk
|
||||
{tAuth('request_new_reset_link')}
|
||||
</button>
|
||||
.
|
||||
</p>
|
||||
@@ -388,10 +398,10 @@ function LoginPageContent() {
|
||||
{bankIdNoAccount ? (
|
||||
<div className="mb-5 rounded-lg border border-amber-200 bg-amber-50 p-4 dark:border-amber-900 dark:bg-amber-950/30">
|
||||
<p className="text-sm font-medium text-amber-800 dark:text-amber-200">
|
||||
Hej {bankIdNoAccount.givenName}!
|
||||
{tAuth('bankid_no_account_greeting', { name: bankIdNoAccount.givenName ?? '' })}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-amber-700 dark:text-amber-300">
|
||||
Vi hittade inget konto kopplat till ditt BankID. Logga in med e-post nedan och koppla sedan BankID i installningar.
|
||||
{tAuth('bankid_no_account_body')}
|
||||
</p>
|
||||
<p className="mt-2">
|
||||
<button
|
||||
@@ -399,7 +409,7 @@ function LoginPageContent() {
|
||||
onClick={() => setBankIdNoAccount(null)}
|
||||
className="text-xs text-amber-600 underline underline-offset-2 hover:text-amber-800 dark:text-amber-400"
|
||||
>
|
||||
Eller skapa ett nytt konto
|
||||
{tAuth('bankid_no_account_create')}
|
||||
</button>
|
||||
</p>
|
||||
</div>
|
||||
@@ -413,7 +423,7 @@ function LoginPageContent() {
|
||||
<div className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">eller logga in med e-post</span>
|
||||
<span className="bg-card px-2 text-muted-foreground">{tAuth('or_email_divider')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
@@ -421,30 +431,22 @@ function LoginPageContent() {
|
||||
{bankIdUnavailable && (
|
||||
<div className="mb-5 rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-900 dark:bg-blue-950/30">
|
||||
<p className="text-sm font-medium text-blue-800 dark:text-blue-200">
|
||||
Har du inget lösenord?
|
||||
{tAuth('bankid_unavailable_title')}
|
||||
</p>
|
||||
<p className="mt-1 text-sm text-blue-700 dark:text-blue-300">
|
||||
Om du skapade ditt konto med BankID kan du använda{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowResetPassword(true)}
|
||||
className="font-medium underline underline-offset-2"
|
||||
>
|
||||
"Glömt lösenord?"
|
||||
</button>{' '}
|
||||
för att få en inloggningslänk via e-post.
|
||||
{tAuth('bankid_unavailable_body')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
<form onSubmit={handlePasswordLogin} className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-postadress</Label>
|
||||
<Label htmlFor="email">{tAuth('email_label')}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="[email protected]"
|
||||
placeholder={tAuth('email_placeholder')}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
@@ -454,13 +456,13 @@ function LoginPageContent() {
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label htmlFor="password">Lösenord</Label>
|
||||
<Label htmlFor="password">{tAuth('password_label')}</Label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowResetPassword(true)}
|
||||
className="text-xs text-muted-foreground hover:text-foreground transition-colors underline underline-offset-2"
|
||||
>
|
||||
Glömt lösenord?
|
||||
{tAuth('forgot_password')}
|
||||
</button>
|
||||
</div>
|
||||
<Input
|
||||
@@ -468,7 +470,7 @@ function LoginPageContent() {
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="Ditt lösenord"
|
||||
placeholder={tAuth('password_placeholder')}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
@@ -480,10 +482,10 @@ function LoginPageContent() {
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Loggar in...
|
||||
{tAuth('logging_in')}
|
||||
</>
|
||||
) : (
|
||||
'Logga in'
|
||||
tAuth('login_button')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
@@ -493,7 +495,7 @@ function LoginPageContent() {
|
||||
<div className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">eller</span>
|
||||
<span className="bg-card px-2 text-muted-foreground">{tAuth('or_divider')}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -503,19 +505,19 @@ function LoginPageContent() {
|
||||
asChild
|
||||
>
|
||||
<Link href="/register">
|
||||
Skapa konto
|
||||
{tAuth('no_account')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p className="mt-4 text-center text-xs text-muted-foreground leading-relaxed">
|
||||
Genom att logga in godkänner du våra{' '}
|
||||
{tAuth('terms_prefix')}{' '}
|
||||
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
|
||||
villkor
|
||||
{tAuth('terms_link')}
|
||||
</a>{' '}
|
||||
och{' '}
|
||||
{tAuth('terms_and')}{' '}
|
||||
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
|
||||
integritetspolicy
|
||||
{tAuth('privacy_link')}
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -11,6 +12,8 @@ import { Loader2, ShieldCheck, LogOut } from 'lucide-react'
|
||||
import { SupportLink } from '@/components/ui/support-link'
|
||||
|
||||
export default function MfaVerifyPage() {
|
||||
const t = useTranslations('mfa')
|
||||
const tCommon = useTranslations('common')
|
||||
const [code, setCode] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [factorId, setFactorId] = useState<string | null>(null)
|
||||
@@ -29,7 +32,6 @@ export default function MfaVerifyPage() {
|
||||
if (verifiedFactor) {
|
||||
setFactorId(verifiedFactor.id)
|
||||
} else {
|
||||
// No MFA factor enrolled — shouldn't be here
|
||||
router.push('/')
|
||||
}
|
||||
}
|
||||
@@ -38,7 +40,6 @@ export default function MfaVerifyPage() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// Lockout countdown timer
|
||||
useEffect(() => {
|
||||
if (!lockoutUntil) return
|
||||
const tick = () => {
|
||||
@@ -64,8 +65,8 @@ export default function MfaVerifyPage() {
|
||||
|
||||
if (challengeError) {
|
||||
toast({
|
||||
title: 'Verifiering misslyckades',
|
||||
description: 'Kunde inte starta verifiering. Försök igen.',
|
||||
title: t('verify_failed_title'),
|
||||
description: t('verify_challenge_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsLoading(false)
|
||||
@@ -82,7 +83,6 @@ export default function MfaVerifyPage() {
|
||||
const attempts = failedAttempts + 1
|
||||
setFailedAttempts(attempts)
|
||||
|
||||
// Exponential backoff after 3 failed attempts: 5s, 15s, 30s
|
||||
if (attempts >= 3) {
|
||||
const delays = [5_000, 15_000, 30_000]
|
||||
const delay = delays[Math.min(attempts - 3, delays.length - 1)]
|
||||
@@ -90,8 +90,8 @@ export default function MfaVerifyPage() {
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Fel kod',
|
||||
description: 'Kontrollera koden och försök igen.',
|
||||
title: t('wrong_code_title'),
|
||||
description: t('wrong_code_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setCode('')
|
||||
@@ -100,7 +100,6 @@ export default function MfaVerifyPage() {
|
||||
return
|
||||
}
|
||||
|
||||
// Check for pending invite token
|
||||
const cookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
|
||||
const inviteToken = cookieMatch?.[1]
|
||||
|
||||
@@ -127,8 +126,8 @@ export default function MfaVerifyPage() {
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Verifiering misslyckades',
|
||||
description: 'Ett oväntat fel uppstod. Försök igen.',
|
||||
title: t('verify_failed_title'),
|
||||
description: t('unexpected_error'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -150,16 +149,16 @@ export default function MfaVerifyPage() {
|
||||
<ShieldCheck className="h-7 w-7 text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="text-2xl font-medium tracking-tight">Tvåfaktorsverifiering</h1>
|
||||
<h1 className="text-2xl font-medium tracking-tight">{t('verify_title')}</h1>
|
||||
<p className="text-muted-foreground text-sm mt-2">
|
||||
Ange den 6-siffriga koden från din autentiseringsapp
|
||||
{t('verify_subtitle_full')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border bg-card p-6" style={{ boxShadow: 'var(--shadow-md)' }}>
|
||||
<form onSubmit={handleVerify} className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="code">Verifieringskod</Label>
|
||||
<Label htmlFor="code">{t('verify_code_label')}</Label>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
id="code"
|
||||
@@ -184,12 +183,12 @@ export default function MfaVerifyPage() {
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Verifierar...
|
||||
{t('verifying')}
|
||||
</>
|
||||
) : lockoutUntil ? (
|
||||
`Vänta ${lockoutRemaining}s`
|
||||
t('wait_seconds', { seconds: lockoutRemaining })
|
||||
) : (
|
||||
'Verifiera'
|
||||
t('verify_button')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
@@ -201,13 +200,13 @@ export default function MfaVerifyPage() {
|
||||
onClick={handleLogout}
|
||||
>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Logga ut
|
||||
{tCommon('logout')}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center mt-4">
|
||||
Förlorat din autentiseringsapp?{' '}
|
||||
<SupportLink variant="muted" subject="MFA-problem — kan inte logga in" className="inline">
|
||||
Kontakta support
|
||||
{t('lost_authenticator')}{' '}
|
||||
<SupportLink variant="muted" subject="MFA — cannot sign in" className="inline">
|
||||
{t('contact_support')}
|
||||
</SupportLink>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect, Suspense } from 'react'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
@@ -10,7 +11,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Mail, ArrowLeft } from 'lucide-react'
|
||||
import Image from 'next/image'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { isBankIdEnabled } from '@/lib/auth/bankid'
|
||||
import { BankIdAuth } from '@/components/auth/BankIdAuth'
|
||||
import type { BankIdResult } from '@/components/auth/BankIdAuth'
|
||||
@@ -46,6 +47,8 @@ function RegisterPageContent() {
|
||||
const router = useRouter()
|
||||
const supabase = createClient()
|
||||
const bankIdEnabled = isBankIdEnabled()
|
||||
const t = useTranslations('register')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
// When arriving from an invite link, fetch the invite info to pre-fill
|
||||
// and lock the email field so the user registers with the correct address.
|
||||
@@ -74,8 +77,8 @@ function RegisterPageContent() {
|
||||
|
||||
if (result.error) {
|
||||
toast({
|
||||
title: 'BankID misslyckades',
|
||||
description: 'Kunde inte verifiera din identitet.',
|
||||
title: t('bankid_failed_title'),
|
||||
description: t('bankid_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -108,21 +111,21 @@ function RegisterPageContent() {
|
||||
if (!res.ok) {
|
||||
if (json.error === 'already_linked') {
|
||||
toast({
|
||||
title: 'BankID redan kopplat',
|
||||
description: 'Detta BankID ar redan kopplat till ett konto. Forsok logga in istallet.',
|
||||
title: t('bankid_already_linked_title'),
|
||||
description: t('bankid_already_linked_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else if (json.error === 'account_exists') {
|
||||
toast({
|
||||
title: 'Kontot finns redan',
|
||||
description: 'Ett konto med den har e-postadressen finns redan. Logga in och koppla BankID i installningarna.',
|
||||
title: t('account_exists_title'),
|
||||
description: t('account_exists_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
router.push('/login')
|
||||
} else {
|
||||
toast({
|
||||
title: 'Registrering misslyckades',
|
||||
description: json.message || json.error || 'Ett ovantat fel uppstod.',
|
||||
title: t('register_failed_title'),
|
||||
description: json.message || json.error || t('register_failed_default'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -138,8 +141,8 @@ function RegisterPageContent() {
|
||||
if (error) {
|
||||
console.error('[register] BankID verifyOtp failed', error)
|
||||
toast({
|
||||
title: 'Kunde inte slutfora registreringen',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: t('register_failed_complete'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -150,8 +153,8 @@ function RegisterPageContent() {
|
||||
} catch (error) {
|
||||
console.error('[register] BankID signup error', error)
|
||||
toast({
|
||||
title: 'Registrering misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: t('register_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -178,8 +181,8 @@ function RegisterPageContent() {
|
||||
|
||||
if (!isStrongPassword(passwordValue)) {
|
||||
toast({
|
||||
title: 'Lösenordet är för svagt',
|
||||
description: 'Lösenordet måste vara minst 8 tecken och innehålla versaler, gemener, siffror och specialtecken.',
|
||||
title: t('weak_password_title'),
|
||||
description: t('weak_password_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsLoading(false)
|
||||
@@ -188,8 +191,8 @@ function RegisterPageContent() {
|
||||
|
||||
if (passwordValue !== confirmValue) {
|
||||
toast({
|
||||
title: 'Lösenorden matchar inte',
|
||||
description: 'Kontrollera att du skrev samma lösenord i båda fälten.',
|
||||
title: t('password_mismatch_title'),
|
||||
description: t('password_mismatch_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsLoading(false)
|
||||
@@ -224,8 +227,8 @@ function RegisterPageContent() {
|
||||
fullError: JSON.stringify(error, Object.getOwnPropertyNames(error)),
|
||||
})
|
||||
toast({
|
||||
title: 'Registrering misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: t('register_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -298,8 +301,8 @@ function RegisterPageContent() {
|
||||
constructor: error?.constructor?.name,
|
||||
})
|
||||
toast({
|
||||
title: 'Registrering misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
title: t('register_failed_title'),
|
||||
description: getErrorMessage(error, { context: 'auth', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -318,23 +321,23 @@ function RegisterPageContent() {
|
||||
</div>
|
||||
|
||||
<div className="text-center space-y-2">
|
||||
<h1 className="text-2xl font-medium tracking-tight">Kontot finns redan</h1>
|
||||
<h1 className="text-2xl font-medium tracking-tight">{t('duplicate_title')}</h1>
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
Det finns redan ett konto kopplat till{' '}
|
||||
{t('duplicate_body_prefix')}{' '}
|
||||
<span className="font-medium text-foreground">{duplicateEmail}</span>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border bg-card p-4">
|
||||
<p className="text-sm text-muted-foreground text-center leading-relaxed">
|
||||
Logga in med din e-post och lösenord. Om du har glömt lösenordet kan du återställa det via "Glömt lösenord?" på inloggningssidan.
|
||||
{t('duplicate_hint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Button className="w-full" asChild>
|
||||
<Link href={`/login?email=${encodeURIComponent(duplicateEmail)}`}>
|
||||
Logga in
|
||||
{t('sign_in')}
|
||||
</Link>
|
||||
</Button>
|
||||
<Button
|
||||
@@ -343,7 +346,7 @@ function RegisterPageContent() {
|
||||
onClick={() => setDuplicateEmail(null)}
|
||||
>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
{t('back')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -362,24 +365,25 @@ function RegisterPageContent() {
|
||||
</div>
|
||||
|
||||
<div className="text-center space-y-2">
|
||||
<h1 className="text-2xl font-medium tracking-tight">Bekräfta din e-post</h1>
|
||||
<h1 className="text-2xl font-medium tracking-tight">{t('confirm_email_title')}</h1>
|
||||
<p className="text-muted-foreground text-sm leading-relaxed">
|
||||
Vi har skickat en bekräftelselänk till{' '}
|
||||
<span className="font-medium text-foreground">{email}</span>
|
||||
{t.rich('confirm_email_body', {
|
||||
email,
|
||||
strong: (chunks) => <span className="font-medium text-foreground">{chunks}</span>,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border bg-card p-4">
|
||||
<p className="text-sm text-muted-foreground text-center leading-relaxed">
|
||||
Klicka på länken i e-posten för att aktivera ditt konto.
|
||||
Länken är giltig i 24 timmar.
|
||||
{t('confirm_email_hint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button variant="ghost" className="w-full text-muted-foreground" asChild>
|
||||
<Link href="/login">
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka till inloggning
|
||||
{t('back_to_login')}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
@@ -400,7 +404,7 @@ function RegisterPageContent() {
|
||||
priority
|
||||
/>
|
||||
<p className="text-muted-foreground text-sm mt-3">
|
||||
Skapa ett konto för att komma igång
|
||||
{t('subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -415,7 +419,7 @@ function RegisterPageContent() {
|
||||
<div className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">eller skapa konto med e-post</span>
|
||||
<span className="bg-card px-2 text-muted-foreground">{t('or_email_divider')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
@@ -424,7 +428,7 @@ function RegisterPageContent() {
|
||||
{bankIdUnavailable && !bankIdUser && (
|
||||
<div className="mb-5 rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-900 dark:bg-blue-950/30">
|
||||
<p className="text-sm text-blue-700 dark:text-blue-300">
|
||||
Skapa konto med e-post och lösenord nedan istället. Du kan koppla BankID i inställningar senare.
|
||||
{t('bankid_unavailable_body')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -436,17 +440,17 @@ function RegisterPageContent() {
|
||||
{bankIdUser.givenName} {bankIdUser.surname}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Verifierad med BankID
|
||||
{t('bankid_verified')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="bankid_email">E-postadress</Label>
|
||||
<Label htmlFor="bankid_email">{t('email_label')}</Label>
|
||||
<Input
|
||||
id="bankid_email"
|
||||
name="bankid_email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="[email protected]"
|
||||
placeholder={t('email_placeholder')}
|
||||
value={bankIdEmail}
|
||||
onChange={(e) => setBankIdEmail(e.target.value)}
|
||||
required
|
||||
@@ -454,17 +458,17 @@ function RegisterPageContent() {
|
||||
className="h-11"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Anvands for inloggning och notifieringar.
|
||||
{t('bankid_email_hint')}
|
||||
</p>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11" disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Skapar konto...
|
||||
{t('creating')}
|
||||
</>
|
||||
) : (
|
||||
'Skapa konto'
|
||||
t('create_account')
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
@@ -477,19 +481,19 @@ function RegisterPageContent() {
|
||||
}}
|
||||
>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
{t('back')}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<form onSubmit={handleRegister} className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">E-postadress</Label>
|
||||
<Label htmlFor="email">{t('email_label')}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
placeholder="[email protected]"
|
||||
placeholder={t('email_placeholder')}
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
@@ -499,18 +503,18 @@ function RegisterPageContent() {
|
||||
/>
|
||||
{inviteEmail && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Inbjudan skickades till denna adress.
|
||||
{t('invite_email_hint')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Lösenord</Label>
|
||||
<Label htmlFor="password">{t('password_label')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="Minst 8 tecken, Aa1!"
|
||||
placeholder={t('password_placeholder')}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
@@ -520,13 +524,13 @@ function RegisterPageContent() {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirm_password">Bekräfta lösenord</Label>
|
||||
<Label htmlFor="confirm_password">{t('confirm_password_label')}</Label>
|
||||
<Input
|
||||
id="confirm_password"
|
||||
name="confirm_password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="Upprepa lösenordet"
|
||||
placeholder={t('confirm_password_placeholder')}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
@@ -539,10 +543,10 @@ function RegisterPageContent() {
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Skapar konto...
|
||||
{t('creating')}
|
||||
</>
|
||||
) : (
|
||||
'Skapa konto'
|
||||
t('create_account')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
@@ -550,23 +554,23 @@ function RegisterPageContent() {
|
||||
</div>
|
||||
|
||||
<p className="mt-6 text-center text-sm text-muted-foreground">
|
||||
Har du redan ett konto?{' '}
|
||||
{t('already_have_account')}{' '}
|
||||
<Link
|
||||
href="/login"
|
||||
className="font-medium text-foreground underline underline-offset-2 hover:text-primary transition-colors"
|
||||
>
|
||||
Logga in
|
||||
{t('sign_in')}
|
||||
</Link>
|
||||
</p>
|
||||
|
||||
<p className="mt-4 text-center text-xs text-muted-foreground leading-relaxed">
|
||||
Genom att skapa konto godkänner du våra{' '}
|
||||
{t('terms_prefix')}{' '}
|
||||
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
|
||||
villkor
|
||||
{t('terms_link')}
|
||||
</a>{' '}
|
||||
och{' '}
|
||||
{t('terms_and')}{' '}
|
||||
<a href="#" className="underline underline-offset-2 hover:text-foreground transition-colors">
|
||||
integritetspolicy
|
||||
{t('privacy_link')}
|
||||
</a>
|
||||
.
|
||||
</p>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
@@ -9,6 +10,7 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, KeyRound } from 'lucide-react'
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
const t = useTranslations('reset_password')
|
||||
const [password, setPassword] = useState('')
|
||||
const [confirmPassword, setConfirmPassword] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
@@ -27,8 +29,8 @@ export default function ResetPasswordPage() {
|
||||
|
||||
if (!strong) {
|
||||
toast({
|
||||
title: 'Lösenordet är för svagt',
|
||||
description: 'Lösenordet måste vara minst 8 tecken och innehålla versaler, gemener, siffror och specialtecken.',
|
||||
title: t('weak_title'),
|
||||
description: t('weak_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsLoading(false)
|
||||
@@ -37,8 +39,8 @@ export default function ResetPasswordPage() {
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
toast({
|
||||
title: 'Lösenorden matchar inte',
|
||||
description: 'Kontrollera att du skrev samma lösenord i båda fälten.',
|
||||
title: t('mismatch_title'),
|
||||
description: t('weak_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsLoading(false)
|
||||
@@ -60,24 +62,24 @@ export default function ResetPasswordPage() {
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
toast({
|
||||
title: 'Kunde inte uppdatera lösenord',
|
||||
description: body.error || 'Försök igen senare.',
|
||||
title: t('save_failed_title'),
|
||||
description: body.error || t('save_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Lösenord uppdaterat',
|
||||
description: 'Ditt lösenord har ändrats.',
|
||||
title: t('saved_title'),
|
||||
description: t('saved_description'),
|
||||
})
|
||||
|
||||
router.push('/')
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Något gick fel',
|
||||
description: 'Försök igen senare.',
|
||||
title: t('save_failed_title'),
|
||||
description: t('save_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -94,21 +96,21 @@ export default function ResetPasswordPage() {
|
||||
<KeyRound className="h-7 w-7 text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
<h1 className="text-2xl font-medium tracking-tight">Nytt lösenord</h1>
|
||||
<h1 className="text-2xl font-medium tracking-tight">{t('title')}</h1>
|
||||
<p className="text-muted-foreground text-sm mt-2">
|
||||
Ange ditt nya lösenord nedan
|
||||
{t('subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl border bg-card p-6" style={{ boxShadow: 'var(--shadow-md)' }}>
|
||||
<form onSubmit={handleResetPassword} className="space-y-5">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Nytt lösenord</Label>
|
||||
<Label htmlFor="password">{t('new_password_label')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="Minst 8 tecken, Aa1!"
|
||||
placeholder={t('new_password_placeholder')}
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
@@ -118,12 +120,12 @@ export default function ResetPasswordPage() {
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirm_password">Bekräfta lösenord</Label>
|
||||
<Label htmlFor="confirm_password">{t('confirm_password_label')}</Label>
|
||||
<Input
|
||||
id="confirm_password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
placeholder="Upprepa lösenordet"
|
||||
placeholder={t('confirm_password_placeholder')}
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
required
|
||||
@@ -136,10 +138,10 @@ export default function ResetPasswordPage() {
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Sparar...
|
||||
{t('submitting')}
|
||||
</>
|
||||
) : (
|
||||
'Spara nytt lösenord'
|
||||
t('submit')
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -21,23 +22,23 @@ import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import type { Asset, AssetCategory } from '@/types'
|
||||
import { CreateAssetDialog } from '@/components/bookkeeping/assets/CreateAssetDialog'
|
||||
|
||||
const CATEGORY_LABELS: Record<AssetCategory, string> = {
|
||||
immaterial: 'Immateriell',
|
||||
building: 'Byggnad',
|
||||
land_improvement: 'Markanläggning',
|
||||
machinery: 'Maskin',
|
||||
equipment: 'Inventarier',
|
||||
vehicle: 'Fordon',
|
||||
computer: 'Dator',
|
||||
other_tangible: 'Övriga materiella',
|
||||
const CATEGORY_LABEL_KEYS: Record<AssetCategory, string> = {
|
||||
immaterial: 'category_immaterial',
|
||||
building: 'category_building',
|
||||
land_improvement: 'category_land_improvement',
|
||||
machinery: 'category_machinery',
|
||||
equipment: 'category_equipment',
|
||||
vehicle: 'category_vehicle',
|
||||
computer: 'category_computer',
|
||||
other_tangible: 'category_other_tangible',
|
||||
}
|
||||
|
||||
export default function AssetsPage() {
|
||||
const t = useTranslations('assets')
|
||||
const [assets, setAssets] = useState<Asset[] | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
|
||||
// Bumped on create to re-trigger the effect.
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -46,7 +47,7 @@ export default function AssetsPage() {
|
||||
.then(async (res) => {
|
||||
if (cancelled) return
|
||||
if (!res.ok) {
|
||||
setError('Kunde inte ladda tillgångar')
|
||||
setError(t('load_failed'))
|
||||
return
|
||||
}
|
||||
const { data } = (await res.json()) as { data: Asset[] }
|
||||
@@ -55,12 +56,12 @@ export default function AssetsPage() {
|
||||
setAssets(data)
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setError('Kunde inte ladda tillgångar')
|
||||
if (!cancelled) setError(t('load_failed'))
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [reloadKey])
|
||||
}, [reloadKey, t])
|
||||
|
||||
const handleCreated = useCallback(() => {
|
||||
setDialogOpen(false)
|
||||
@@ -70,10 +71,10 @@ export default function AssetsPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Anläggningstillgångar"
|
||||
title={t('title')}
|
||||
action={
|
||||
<Button onClick={() => setDialogOpen(true)}>
|
||||
<Plus className="mr-1 h-4 w-4" /> Ny tillgång
|
||||
<Plus className="mr-1 h-4 w-4" /> {t('new_asset')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
@@ -96,9 +97,9 @@ export default function AssetsPage() {
|
||||
{assets !== null && assets.length === 0 && (
|
||||
<EmptyState
|
||||
icon={Package}
|
||||
title="Inga tillgångar än"
|
||||
description="Lägg till anläggningstillgångar (datorer, möbler, fordon, maskiner) så räknar bokslutet planenliga avskrivningar automatiskt."
|
||||
actionLabel="Ny tillgång"
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
actionLabel={t('new_asset')}
|
||||
onAction={() => setDialogOpen(true)}
|
||||
/>
|
||||
)}
|
||||
@@ -109,12 +110,12 @@ export default function AssetsPage() {
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Namn</TableHead>
|
||||
<TableHead>Kategori</TableHead>
|
||||
<TableHead>Anskaffat</TableHead>
|
||||
<TableHead className="text-right">Anskaffningsvärde</TableHead>
|
||||
<TableHead>Avskrivningstid</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>{t('th_name')}</TableHead>
|
||||
<TableHead>{t('th_category')}</TableHead>
|
||||
<TableHead>{t('th_acquired')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_acquisition_cost')}</TableHead>
|
||||
<TableHead>{t('th_useful_life')}</TableHead>
|
||||
<TableHead>{t('th_status')}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -123,7 +124,7 @@ export default function AssetsPage() {
|
||||
return (
|
||||
<TableRow key={asset.id}>
|
||||
<TableCell className="font-medium">{asset.name}</TableCell>
|
||||
<TableCell className="text-sm">{CATEGORY_LABELS[asset.category]}</TableCell>
|
||||
<TableCell className="text-sm">{t(CATEGORY_LABEL_KEYS[asset.category])}</TableCell>
|
||||
<TableCell className="tabular-nums">
|
||||
{formatDate(asset.acquisition_date)}
|
||||
</TableCell>
|
||||
@@ -131,13 +132,13 @@ export default function AssetsPage() {
|
||||
{formatCurrency(Number(asset.acquisition_cost))}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{years} år ({asset.useful_life_months} mån)
|
||||
{t('useful_life_format', { years, months: asset.useful_life_months })}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{asset.disposed_at ? (
|
||||
<Badge variant="secondary">Avyttrad</Badge>
|
||||
<Badge variant="secondary">{t('status_disposed')}</Badge>
|
||||
) : (
|
||||
<Badge variant="success">Aktiv</Badge>
|
||||
<Badge variant="success">{t('status_active')}</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect, useCallback, use } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
@@ -11,7 +12,7 @@ import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock, MessageSquare, Penc
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
|
||||
import JournalEntryStatusBadge, { sourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge'
|
||||
import JournalEntryStatusBadge, { useSourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge'
|
||||
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
|
||||
import CorrectionChain from '@/components/bookkeeping/CorrectionChain'
|
||||
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
@@ -24,6 +25,8 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
const router = useRouter()
|
||||
const { canWrite } = useCanWrite()
|
||||
const { toast } = useToast()
|
||||
const t = useTranslations('journal_detail')
|
||||
const sourceTypeLabels = useSourceTypeLabels()
|
||||
const [entry, setEntry] = useState<JournalEntry | null>(null)
|
||||
const [chain, setChain] = useState<JournalEntry[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
@@ -45,7 +48,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
const res = await fetch(`/api/bookkeeping/journal-entries/${id}/chain`)
|
||||
if (!res.ok) {
|
||||
const { error: msg } = await res.json()
|
||||
setError(msg || 'Kunde inte hämta verifikation')
|
||||
setError(msg || t('error_load_failed'))
|
||||
return
|
||||
}
|
||||
const { data } = await res.json()
|
||||
@@ -53,11 +56,11 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
setChain(data.chain)
|
||||
setIsLastInSeries(data.is_last_in_series ?? false)
|
||||
} catch {
|
||||
setError('Kunde inte hämta verifikation')
|
||||
setError(t('error_load_failed'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [id])
|
||||
}, [id, t])
|
||||
|
||||
const saveNotes = useCallback(async (value: string) => {
|
||||
setSavingNotes(true)
|
||||
@@ -71,14 +74,14 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
setEntry(prev => prev ? { ...prev, notes: value || null } : prev)
|
||||
setEditingNotes(false)
|
||||
} else {
|
||||
toast({ title: 'Kunde inte spara anteckning', variant: 'destructive' })
|
||||
toast({ title: t('toast_save_note_failed'), variant: 'destructive' })
|
||||
}
|
||||
} catch {
|
||||
toast({ title: 'Kunde inte spara anteckning', variant: 'destructive' })
|
||||
toast({ title: t('toast_save_note_failed'), variant: 'destructive' })
|
||||
} finally {
|
||||
setSavingNotes(false)
|
||||
}
|
||||
}, [id, toast])
|
||||
}, [id, toast, t])
|
||||
|
||||
const handleCommit = useCallback(async () => {
|
||||
setIsCommitting(true)
|
||||
@@ -88,19 +91,19 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
if (res.ok) {
|
||||
const posted = result.data
|
||||
toast({
|
||||
title: 'Verifikat bokfört',
|
||||
description: `Verifikat ${posted?.voucher_series ?? ''}${posted?.voucher_number ?? ''} har bokförts.`,
|
||||
title: t('toast_posted_title'),
|
||||
description: t('toast_posted_description', { voucher: `${posted?.voucher_series ?? ''}${posted?.voucher_number ?? ''}` }),
|
||||
})
|
||||
await fetchData()
|
||||
} else {
|
||||
toast({ title: 'Kunde inte bokföra', description: getErrorMessage(result, { context: 'journal_entry' }), variant: 'destructive' })
|
||||
toast({ title: t('toast_post_failed'), description: getErrorMessage(result, { context: 'journal_entry' }), variant: 'destructive' })
|
||||
}
|
||||
} catch {
|
||||
toast({ title: 'Kunde inte bokföra verifikat', variant: 'destructive' })
|
||||
toast({ title: t('toast_post_failed_generic'), variant: 'destructive' })
|
||||
} finally {
|
||||
setIsCommitting(false)
|
||||
}
|
||||
}, [id, toast, fetchData])
|
||||
}, [id, toast, fetchData, t])
|
||||
|
||||
const handleDelete = useCallback(async () => {
|
||||
setIsDeleting(true)
|
||||
@@ -110,23 +113,23 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
if (res.ok) {
|
||||
const wasDraft = result.data?.was_draft === true
|
||||
toast({
|
||||
title: wasDraft ? 'Utkast raderat' : 'Verifikat raderat',
|
||||
title: wasDraft ? t('toast_delete_draft_title') : t('toast_delete_entry_title'),
|
||||
description: wasDraft
|
||||
? 'Utkastet har tagits bort.'
|
||||
: `Verifikat ${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''} har raderats.`,
|
||||
? t('toast_delete_draft_description')
|
||||
: t('toast_delete_entry_description', { voucher: `${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''}` }),
|
||||
})
|
||||
router.push('/bookkeeping')
|
||||
} else {
|
||||
toast({ title: 'Kunde inte radera', description: getErrorMessage(result, { context: 'journal_entry' }), variant: 'destructive' })
|
||||
toast({ title: t('toast_delete_failed'), description: getErrorMessage(result, { context: 'journal_entry' }), variant: 'destructive' })
|
||||
setShowDeleteConfirm(false)
|
||||
}
|
||||
} catch {
|
||||
toast({ title: 'Kunde inte radera verifikat', variant: 'destructive' })
|
||||
toast({ title: t('toast_delete_failed_generic'), variant: 'destructive' })
|
||||
setShowDeleteConfirm(false)
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
}
|
||||
}, [id, router, toast])
|
||||
}, [id, router, toast, t])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
@@ -136,7 +139,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-24">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground mb-3" />
|
||||
<p className="text-sm text-muted-foreground">Laddar verifikation...</p>
|
||||
<p className="text-sm text-muted-foreground">{t('loading')}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -149,11 +152,11 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Tillbaka till bokföring
|
||||
{t('back')}
|
||||
</Link>
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12">
|
||||
<p className="text-sm text-muted-foreground">{error || 'Verifikation hittades inte'}</p>
|
||||
<p className="text-sm text-muted-foreground">{error || t('error_not_found')}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
@@ -190,7 +193,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Tillbaka till bokföring
|
||||
{t('back')}
|
||||
</Link>
|
||||
|
||||
{/* Header */}
|
||||
@@ -213,10 +216,10 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
className="w-full sm:w-auto"
|
||||
onClick={handleCommit}
|
||||
disabled={!canWrite || isCommitting}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite ? <Lock className="mr-2 h-4 w-4" /> : isCommitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Bokför
|
||||
{t('post')}
|
||||
</Button>
|
||||
)}
|
||||
{(entry.status === 'draft' || isLastInSeries) && (
|
||||
@@ -226,10 +229,10 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() => setShowDeleteConfirm(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
|
||||
{entry.status === 'draft' ? 'Radera utkast' : 'Radera verifikat'}
|
||||
{entry.status === 'draft' ? t('delete_draft') : t('delete_entry')}
|
||||
</Button>
|
||||
)}
|
||||
{canCorrect && (
|
||||
@@ -239,10 +242,10 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() => setShowCorrection(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
|
||||
Skapa ändringsverifikation
|
||||
{t('create_correction')}
|
||||
</Button>
|
||||
)}
|
||||
{entry.status === 'posted' && (
|
||||
@@ -252,10 +255,10 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
className="w-full sm:w-auto"
|
||||
onClick={() => router.push(`/bookkeeping?copy_from=${entry.id}`)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('read_only_tooltip') : undefined}
|
||||
>
|
||||
{!canWrite ? <Lock className="mr-2 h-4 w-4" /> : <Copy className="mr-2 h-4 w-4" />}
|
||||
Kopiera verifikat
|
||||
{t('copy_entry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -266,26 +269,26 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Verifikationsdetaljer</CardTitle>
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">{t('details_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Datum</span>
|
||||
<span className="text-muted-foreground">{t('field_date')}</span>
|
||||
<span>{formatDate(entry.entry_date)}</span>
|
||||
</div>
|
||||
{entry.committed_at && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Bokförd</span>
|
||||
<span className="text-muted-foreground">{t('field_posted_at')}</span>
|
||||
<span>{new Date(entry.committed_at).toLocaleDateString('sv-SE')}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Typ</span>
|
||||
<span className="text-muted-foreground">{t('field_type')}</span>
|
||||
<span>{sourceTypeLabels[entry.source_type] || entry.source_type}</span>
|
||||
</div>
|
||||
{entry.source_voucher_series && entry.source_voucher_number != null && (
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Ursprungligt verifikat</span>
|
||||
<span className="text-muted-foreground">{t('field_source_voucher')}</span>
|
||||
<span className="font-mono tabular-nums">
|
||||
{entry.source_voucher_series}{entry.source_voucher_number}
|
||||
</span>
|
||||
@@ -296,14 +299,14 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
<div className="flex items-center justify-between mb-1">
|
||||
<span className="text-muted-foreground flex items-center gap-1">
|
||||
<MessageSquare className="h-3.5 w-3.5" />
|
||||
Anteckning
|
||||
{t('field_note')}
|
||||
</span>
|
||||
{!editingNotes && canWrite && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => { setNotesValue(entry.notes || ''); setEditingNotes(true) }}
|
||||
aria-label="Redigera anteckning"
|
||||
aria-label={t('edit_note_aria')}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
@@ -314,7 +317,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
<Textarea
|
||||
value={notesValue}
|
||||
onChange={(e) => setNotesValue(e.target.value)}
|
||||
placeholder="Intern anteckning..."
|
||||
placeholder={t('note_placeholder')}
|
||||
className="resize-none text-sm"
|
||||
rows={3}
|
||||
maxLength={2000}
|
||||
@@ -342,7 +345,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground italic">
|
||||
{entry.notes || 'Ingen anteckning'}
|
||||
{entry.notes || t('no_note')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -351,23 +354,23 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Summering</CardTitle>
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">{t('summary_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2 text-sm">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Debet</span>
|
||||
<span className="text-muted-foreground">{t('summary_debit')}</span>
|
||||
<span className="tabular-nums font-medium">
|
||||
{totalDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Kredit</span>
|
||||
<span className="text-muted-foreground">{t('summary_credit')}</span>
|
||||
<span className="tabular-nums font-medium">
|
||||
{totalCredit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Antal rader</span>
|
||||
<span className="text-muted-foreground">{t('summary_lines')}</span>
|
||||
<span>{lines.length}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -375,19 +378,19 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">Underlag</CardTitle>
|
||||
<CardTitle className="text-sm font-medium text-muted-foreground">{t('attachments_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
{attachmentCount > 0 ? (
|
||||
<>
|
||||
<Paperclip className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{attachmentCount} {attachmentCount === 1 ? 'dokument' : 'dokument'}</span>
|
||||
<span>{t('attachments_count', { count: attachmentCount })}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<AlertTriangle className="h-4 w-4 text-warning-foreground" />
|
||||
<span className="text-muted-foreground">Inga underlag bifogade</span>
|
||||
<span className="text-muted-foreground">{t('no_attachments')}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -400,11 +403,11 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground mb-2">
|
||||
Valutaomräkning
|
||||
{t('currency_title')}
|
||||
</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-sm">
|
||||
<div className="flex justify-between sm:block">
|
||||
<span className="text-muted-foreground">Kurs</span>
|
||||
<span className="text-muted-foreground">{t('currency_rate')}</span>
|
||||
<span className="tabular-nums sm:block">
|
||||
{foreignExchangeRate
|
||||
? `1 ${foreignCurrency} = ${foreignExchangeRate.toLocaleString('sv-SE', { minimumFractionDigits: 4, maximumFractionDigits: 4 })} SEK`
|
||||
@@ -412,7 +415,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between sm:block">
|
||||
<span className="text-muted-foreground">Ursprungsbelopp</span>
|
||||
<span className="text-muted-foreground">{t('currency_original_amount')}</span>
|
||||
<span className="tabular-nums sm:block">
|
||||
{foreignTotal.toLocaleString('sv-SE', { minimumFractionDigits: 2 })} {foreignCurrency}
|
||||
</span>
|
||||
@@ -425,7 +428,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
{/* Lines table */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm font-medium">Kontorader</CardTitle>
|
||||
<CardTitle className="text-sm font-medium">{t('lines_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{/* Desktop table */}
|
||||
@@ -433,10 +436,10 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
<table className="w-full text-sm">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b text-left">
|
||||
<th className="py-2 w-48">Konto</th>
|
||||
<th className="py-2">Beskrivning</th>
|
||||
<th className="py-2 w-28 text-right">Debet</th>
|
||||
<th className="py-2 w-28 text-right">Kredit</th>
|
||||
<th className="py-2 w-48">{t('col_account')}</th>
|
||||
<th className="py-2">{t('col_description')}</th>
|
||||
<th className="py-2 w-28 text-right">{t('col_debit')}</th>
|
||||
<th className="py-2 w-28 text-right">{t('col_credit')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -476,7 +479,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="font-semibold">
|
||||
<td colSpan={2} className="py-2">Summa</td>
|
||||
<td colSpan={2} className="py-2">{t('sum')}</td>
|
||||
<td className="py-2 text-right tabular-nums">
|
||||
{totalDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
|
||||
</td>
|
||||
@@ -526,7 +529,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
)
|
||||
})}
|
||||
<div className="flex justify-between font-semibold text-sm pt-1">
|
||||
<span>Summa</span>
|
||||
<span>{t('sum')}</span>
|
||||
<div className="flex gap-3 tabular-nums">
|
||||
<span>D: {totalDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}</span>
|
||||
<span>K: {totalCredit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}</span>
|
||||
@@ -539,7 +542,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
{/* Attachments */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm font-medium">Underlag</CardTitle>
|
||||
<CardTitle className="text-sm font-medium">{t('attachments_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<JournalEntryAttachments
|
||||
@@ -553,7 +556,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
{chain.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm font-medium">Ändringshistorik</CardTitle>
|
||||
<CardTitle className="text-sm font-medium">{t('history_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CorrectionChain currentEntryId={id} chain={fullChain} />
|
||||
@@ -580,22 +583,20 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
|
||||
onOpenChange={setShowDeleteConfirm}
|
||||
onConfirm={handleDelete}
|
||||
isSubmitting={isDeleting}
|
||||
title={entry?.status === 'draft' ? 'Radera utkast' : 'Radera verifikat'}
|
||||
title={entry?.status === 'draft' ? t('delete_draft') : t('delete_entry')}
|
||||
warningText={
|
||||
entry?.status === 'draft'
|
||||
? 'Utkastet har aldrig bokförts och kan tas bort utan att påverka verifikationsserien. Eventuella kopplade underlag behålls men avlänkas. Denna åtgärd kan inte ångras.'
|
||||
: `Verifikat ${entry?.voucher_series ?? ''}${entry?.voucher_number ?? ''} raderas permanent. Eventuella kopplade underlag behålls men avlänkas. Denna åtgärd kan inte ångras.`
|
||||
? t('delete_warning_draft')
|
||||
: t('delete_warning_entry', { voucher: `${entry?.voucher_series ?? ''}${entry?.voucher_number ?? ''}` })
|
||||
}
|
||||
confirmLabel="Radera permanent"
|
||||
confirmLabel={t('delete_confirm_label')}
|
||||
>
|
||||
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive mt-0.5 shrink-0" />
|
||||
<div className="text-sm">
|
||||
<p className="font-medium mb-1">Permanent radering</p>
|
||||
<p className="font-medium mb-1">{t('delete_dialog_heading')}</p>
|
||||
<p className="text-muted-foreground">
|
||||
{entry?.status === 'draft'
|
||||
? 'Utkastet och dess kontorader tas bort. Kopplade fakturor och transaktioner påverkas inte — de stannar kvar som obokförda. Underlag (kvitton, dokument) behålls men avlänkas.'
|
||||
: 'Verifikatet och dess kontorader tas bort. Kopplade transaktioner och fakturor behåller sina uppgifter men markeras som ej bokförda. Underlag (kvitton, dokument) behålls men avlänkas.'}
|
||||
{entry?.status === 'draft' ? t('delete_dialog_draft_body') : t('delete_dialog_entry_body')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import JournalEntryList from '@/components/bookkeeping/JournalEntryList'
|
||||
@@ -46,6 +47,7 @@ export default function BookkeepingPage() {
|
||||
const [copyPrefill, setCopyPrefill] = useState<CopyPrefill | null>(null)
|
||||
const [isLoadingCopy, setIsLoadingCopy] = useState(false)
|
||||
const [nextVoucher, setNextVoucher] = useState<NextVoucher | null>(null)
|
||||
const t = useTranslations('bookkeeping')
|
||||
|
||||
// React to copy_from in URL: switch tab, fetch source entry, then clean URL.
|
||||
// useSearchParams keeps this reactive even when navigation happens within the
|
||||
@@ -64,8 +66,8 @@ export default function BookkeepingPage() {
|
||||
.then(({ data, error }: { data?: JournalEntry; error?: string }) => {
|
||||
if (error || !data) {
|
||||
toast({
|
||||
title: 'Kunde inte kopiera verifikat',
|
||||
description: error || 'Källverifikatet hittades inte.',
|
||||
title: t('copy_failed_title'),
|
||||
description: error || t('copy_source_missing'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -93,8 +95,8 @@ export default function BookkeepingPage() {
|
||||
})
|
||||
.catch(() => {
|
||||
toast({
|
||||
title: 'Kunde inte kopiera verifikat',
|
||||
description: 'Källverifikatet kunde inte hämtas.',
|
||||
title: t('copy_failed_title'),
|
||||
description: t('copy_fetch_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
})
|
||||
@@ -132,12 +134,12 @@ export default function BookkeepingPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Bokföring"
|
||||
title={t('title')}
|
||||
action={
|
||||
<Button variant="outline" asChild className="w-full sm:w-auto">
|
||||
<Link href="/bookkeeping/year-end">
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Årsbokslut
|
||||
{t('year_end')}
|
||||
</Link>
|
||||
</Button>
|
||||
}
|
||||
@@ -145,16 +147,16 @@ export default function BookkeepingPage() {
|
||||
|
||||
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as TabValue)}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="journal">Verifikationer</TabsTrigger>
|
||||
<TabsTrigger value="journal">{t('tab_journal')}</TabsTrigger>
|
||||
<TabsTrigger value="new-entry">
|
||||
Ny verifikation
|
||||
{t('tab_new_entry')}
|
||||
{nextVoucher && (
|
||||
<span className="ml-1 text-muted-foreground tabular-nums">
|
||||
({nextVoucher.series}{nextVoucher.next})
|
||||
</span>
|
||||
)}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="accounts">Kontoplan</TabsTrigger>
|
||||
<TabsTrigger value="accounts">{t('tab_accounts')}</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="journal" className="space-y-4">
|
||||
@@ -166,7 +168,7 @@ export default function BookkeepingPage() {
|
||||
{isLoadingCopy ? (
|
||||
<div className="flex items-center gap-2 py-12 justify-center text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">Laddar källverifikat...</span>
|
||||
<span className="text-sm">{t('loading_source_voucher')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
@@ -175,12 +177,10 @@ export default function BookkeepingPage() {
|
||||
<Copy className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" />
|
||||
<div className="flex-1">
|
||||
<p className="font-medium">
|
||||
Kopia av verifikat {copyPrefill.sourceVoucherLabel || '(okänt nummer)'}
|
||||
{t('copy_banner_title', { label: copyPrefill.sourceVoucherLabel || t('copy_banner_unknown_label') })}
|
||||
</p>
|
||||
<p className="text-muted-foreground mt-0.5">
|
||||
Ett nytt, fristående verifikat skapas med egen verifikationsserie och nummer.
|
||||
Detta är <strong>inte</strong> en rättelse eller storno av originalet — använd
|
||||
"Skapa ändringsverifikation" om du vill korrigera källverifikatet.
|
||||
{t('copy_banner_body')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { use } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -30,11 +31,11 @@ import { cn, formatDate } from '@/lib/utils'
|
||||
import { invoiceNumberDisplay } from '@/lib/invoices/display'
|
||||
import type { Customer, CustomerType, CreateCustomerInput } from '@/types'
|
||||
|
||||
const customerTypeLabels: Record<CustomerType, string> = {
|
||||
individual: 'Privatperson',
|
||||
swedish_business: 'Svenskt företag eller organisation',
|
||||
eu_business: 'EU-företag',
|
||||
non_eu_business: 'Utanför EU',
|
||||
const CUSTOMER_TYPE_KEY: Record<CustomerType, string> = {
|
||||
individual: 'type_individual',
|
||||
swedish_business: 'type_swedish_business',
|
||||
eu_business: 'type_eu_business',
|
||||
non_eu_business: 'type_non_eu_business',
|
||||
}
|
||||
|
||||
const customerTypeIcons: Record<CustomerType, React.ElementType> = {
|
||||
@@ -68,6 +69,7 @@ export default function CustomerDetailPage({
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const t = useTranslations('customer_detail')
|
||||
const [customer, setCustomer] = useState<CustomerWithRelations | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isEditOpen, setIsEditOpen] = useState(false)
|
||||
@@ -89,8 +91,8 @@ export default function CustomerDetailPage({
|
||||
setCustomer(data)
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte ladda kund',
|
||||
description: 'Kunden hittades inte.',
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
router.push('/customers')
|
||||
@@ -113,15 +115,15 @@ export default function CustomerDetailPage({
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Kund uppdaterad',
|
||||
title: t('updated_title'),
|
||||
description: data.name,
|
||||
})
|
||||
setIsEditOpen(false)
|
||||
fetchCustomer()
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte uppdatera kund',
|
||||
description: 'Försök igen.',
|
||||
title: t('update_failed_title'),
|
||||
description: t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -132,9 +134,9 @@ export default function CustomerDetailPage({
|
||||
async function handleDelete() {
|
||||
if (!customer) return
|
||||
const ok = await confirmAction({
|
||||
title: `Ta bort ${customer.name}`,
|
||||
description: 'Kunden och tillhörande data tas bort permanent. Denna åtgärd kan inte ångras.',
|
||||
confirmLabel: 'Ta bort',
|
||||
title: t('delete_confirm_title', { name: customer.name }),
|
||||
description: t('delete_confirm_description'),
|
||||
confirmLabel: t('delete_confirm_label'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
if (!ok) return
|
||||
@@ -149,14 +151,14 @@ export default function CustomerDetailPage({
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Kund borttagen',
|
||||
title: t('deleted_title'),
|
||||
description: customer.name,
|
||||
})
|
||||
router.push('/customers')
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte ta bort kund',
|
||||
description: 'Försök igen.',
|
||||
title: t('delete_failed_title'),
|
||||
description: t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -194,7 +196,7 @@ export default function CustomerDetailPage({
|
||||
className="text-sm text-muted-foreground hover:text-foreground flex items-center gap-1 mb-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
Tillbaka till kunder
|
||||
{t('back')}
|
||||
</Link>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
@@ -202,7 +204,7 @@ export default function CustomerDetailPage({
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{customer.name}</h1>
|
||||
<Badge variant="secondary">{customerTypeLabels[customer.customer_type]}</Badge>
|
||||
<Badge variant="secondary">{t(CUSTOMER_TYPE_KEY[customer.customer_type])}</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -213,10 +215,10 @@ export default function CustomerDetailPage({
|
||||
size="sm"
|
||||
onClick={() => setIsEditOpen(true)}
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? <Edit2 className="h-4 w-4 mr-1" /> : <Lock className="h-4 w-4 mr-1" />}
|
||||
Redigera
|
||||
{t('edit')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -224,10 +226,10 @@ export default function CustomerDetailPage({
|
||||
onClick={handleDelete}
|
||||
className="text-destructive hover:text-destructive"
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? <Trash2 className="h-4 w-4 mr-1" /> : <Lock className="h-4 w-4 mr-1" />}
|
||||
Ta bort
|
||||
{t('delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -237,7 +239,7 @@ export default function CustomerDetailPage({
|
||||
{/* Contact */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Kontaktuppgifter</CardTitle>
|
||||
<CardTitle className="text-base">{t('section_contact')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{customer.email && (
|
||||
@@ -268,7 +270,7 @@ export default function CustomerDetailPage({
|
||||
</div>
|
||||
)}
|
||||
{!customer.email && !customer.phone && !customer.address_line1 && !customer.city && (
|
||||
<p className="text-sm text-muted-foreground">Inga kontaktuppgifter</p>
|
||||
<p className="text-sm text-muted-foreground">{t('no_contact_info')}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -276,30 +278,30 @@ export default function CustomerDetailPage({
|
||||
{/* Business details */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Företagsuppgifter</CardTitle>
|
||||
<CardTitle className="text-base">{t('section_business')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{customer.org_number && (
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Org.nr: </span>
|
||||
<span className="text-muted-foreground">{t('label_org_number')} </span>
|
||||
{customer.org_number}
|
||||
</div>
|
||||
)}
|
||||
{customer.vat_number && (
|
||||
<div className="text-sm flex items-center gap-2">
|
||||
<span className="text-muted-foreground">VAT: </span>
|
||||
<span className="text-muted-foreground">{t('label_vat')} </span>
|
||||
{customer.vat_number}
|
||||
{customer.vat_number_validated && (
|
||||
<Badge variant="success" className="text-xs">Verifierad</Badge>
|
||||
<Badge variant="success" className="text-xs">{t('verified')}</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Betalningsvillkor: </span>
|
||||
{customer.default_payment_terms || 30} dagar
|
||||
<span className="text-muted-foreground">{t('label_payment_terms')} </span>
|
||||
{t('payment_terms_value', { days: customer.default_payment_terms || 30 })}
|
||||
</div>
|
||||
{!customer.org_number && !customer.vat_number && (
|
||||
<p className="text-sm text-muted-foreground">Inga företagsuppgifter</p>
|
||||
<p className="text-sm text-muted-foreground">{t('no_business_info')}</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -307,12 +309,12 @@ export default function CustomerDetailPage({
|
||||
{/* Summary */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Översikt</CardTitle>
|
||||
<CardTitle className="text-base">{t('section_summary')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Receipt className="h-4 w-4 text-muted-foreground" />
|
||||
<span>{customer.invoices?.length || 0} fakturor</span>
|
||||
<span>{t('invoice_count', { count: customer.invoices?.length || 0 })}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -322,7 +324,7 @@ export default function CustomerDetailPage({
|
||||
{customer.notes && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Anteckningar</CardTitle>
|
||||
<CardTitle className="text-base">{t('section_notes')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground whitespace-pre-wrap">{customer.notes}</p>
|
||||
@@ -335,7 +337,7 @@ export default function CustomerDetailPage({
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<Receipt className="h-4 w-4" />
|
||||
Fakturor
|
||||
{t('section_invoices')}
|
||||
{customer.invoices?.length > 0 && (
|
||||
<Badge variant="secondary">{customer.invoices.length}</Badge>
|
||||
)}
|
||||
@@ -359,7 +361,11 @@ export default function CustomerDetailPage({
|
||||
{formatCurrency(invoice.total, invoice.currency)}
|
||||
</span>
|
||||
<Badge variant={invoice.payment_status === 'paid' ? 'success' : 'secondary'}>
|
||||
{invoice.payment_status === 'paid' ? 'Betald' : invoice.payment_status === 'overdue' ? 'Förfallen' : 'Obetald'}
|
||||
{invoice.payment_status === 'paid'
|
||||
? t('invoice_status_paid')
|
||||
: invoice.payment_status === 'overdue'
|
||||
? t('invoice_status_overdue')
|
||||
: t('invoice_status_unpaid')}
|
||||
</Badge>
|
||||
</div>
|
||||
</Link>
|
||||
@@ -367,7 +373,7 @@ export default function CustomerDetailPage({
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground text-center py-4">
|
||||
Inga fakturor kopplade till denna kund
|
||||
{t('no_invoices')}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -379,7 +385,7 @@ export default function CustomerDetailPage({
|
||||
<Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Redigera kund</DialogTitle>
|
||||
<DialogTitle>{t('edit_dialog_title')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CustomerForm
|
||||
onSubmit={handleUpdate}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -8,7 +9,7 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { Plus, Search, Users, Lock } from 'lucide-react'
|
||||
import CustomerForm from '@/components/customers/CustomerForm'
|
||||
import { EmptyCustomers, EmptyState } from '@/components/ui/empty-state'
|
||||
@@ -18,11 +19,11 @@ import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Customer, CustomerType, CreateCustomerInput } from '@/types'
|
||||
|
||||
const customerTypeLabels: Record<CustomerType, string> = {
|
||||
individual: 'Privatperson',
|
||||
swedish_business: 'Svenskt företag eller organisation',
|
||||
eu_business: 'EU-företag',
|
||||
non_eu_business: 'Utanför EU',
|
||||
const CUSTOMER_TYPE_LABEL_KEYS: Record<CustomerType, string> = {
|
||||
individual: 'type_individual',
|
||||
swedish_business: 'type_swedish_business',
|
||||
eu_business: 'type_eu_business',
|
||||
non_eu_business: 'type_non_eu_business',
|
||||
}
|
||||
|
||||
function getInitials(name: string): string {
|
||||
@@ -44,6 +45,8 @@ export default function CustomersPage() {
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
const t = useTranslations('customers')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
async function fetchCustomers() {
|
||||
if (!company) return
|
||||
@@ -56,8 +59,8 @@ export default function CustomersPage() {
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: 'Kunde inte ladda kunder',
|
||||
description: 'Kontrollera din anslutning och försök igen.',
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
@@ -83,14 +86,14 @@ export default function CustomersPage() {
|
||||
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: 'Kunde inte skapa kund',
|
||||
description: getErrorMessage(result, { context: 'customer' }),
|
||||
title: t('create_failed_title'),
|
||||
description: getErrorMessage(result, { context: 'customer', locale: errorLocale }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: 'Kund skapad',
|
||||
description: `${data.name} har lagts till`,
|
||||
title: t('created_title'),
|
||||
description: t('created_description', { name: data.name }),
|
||||
})
|
||||
setCustomers([...customers, result.data])
|
||||
setIsDialogOpen(false)
|
||||
@@ -108,25 +111,25 @@ export default function CustomersPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Kunder"
|
||||
title={t('title')}
|
||||
action={
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Ny kund
|
||||
{t('new_customer')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Lägg till kund</DialogTitle>
|
||||
<DialogTitle>{t('add_customer')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CustomerForm
|
||||
onSubmit={handleCreateCustomer}
|
||||
@@ -141,7 +144,7 @@ export default function CustomersPage() {
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Sök kunder"
|
||||
placeholder={t('search_placeholder')}
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-10"
|
||||
@@ -169,8 +172,8 @@ export default function CustomersPage() {
|
||||
{searchTerm ? (
|
||||
<EmptyState
|
||||
icon={Users}
|
||||
title="Inga träffar"
|
||||
description={`Inga kunder matchar "${searchTerm}".`}
|
||||
title={t('no_search_results_title')}
|
||||
description={t('no_search_results_description', { term: searchTerm })}
|
||||
/>
|
||||
) : (
|
||||
<EmptyCustomers onAction={() => setIsDialogOpen(true)} />
|
||||
@@ -190,7 +193,7 @@ export default function CustomersPage() {
|
||||
<div className="min-w-0">
|
||||
<CardTitle className="text-base truncate group-hover:text-primary transition-colors">{customer.name}</CardTitle>
|
||||
<Badge variant="secondary" className="mt-1">
|
||||
{customerTypeLabels[customer.customer_type]}
|
||||
{t(CUSTOMER_TYPE_LABEL_KEYS[customer.customer_type])}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
@@ -204,7 +207,7 @@ export default function CustomersPage() {
|
||||
<div className="flex items-center gap-2">
|
||||
<span>{customer.org_number}</span>
|
||||
{customer.vat_number_validated && (
|
||||
<Badge variant="success" className="text-xs">Verifierad</Badge>
|
||||
<Badge variant="success" className="text-xs">{t('verified')}</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { ToastAction } from '@/components/ui/toast'
|
||||
@@ -15,6 +16,7 @@ const supabase = createClient()
|
||||
|
||||
export default function DeadlinesPage() {
|
||||
const { company } = useCompany()
|
||||
const t = useTranslations('deadlines')
|
||||
const [deadlines, setDeadlines] = useState<Deadline[]>([])
|
||||
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([])
|
||||
const [overdueInvoices, setOverdueInvoices] = useState<{ count: number; total: number }>({ count: 0, total: 0 })
|
||||
@@ -49,14 +51,14 @@ export default function DeadlinesPage() {
|
||||
setOverdueInvoices({ count: overdueCount, total: overdueTotal })
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte ladda deadlines',
|
||||
description: 'Kontrollera din anslutning och försök igen.',
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [toast])
|
||||
}, [toast, t])
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
@@ -78,15 +80,15 @@ export default function DeadlinesPage() {
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Deadline skapad',
|
||||
description: 'Din deadline har sparats',
|
||||
title: t('created_title'),
|
||||
description: t('created_description'),
|
||||
})
|
||||
|
||||
fetchData()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Kunde inte skapa deadline',
|
||||
description: error instanceof Error ? error.message : 'Försök igen.',
|
||||
title: t('create_failed_title'),
|
||||
description: error instanceof Error ? error.message : t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
throw error
|
||||
@@ -113,9 +115,9 @@ export default function DeadlinesPage() {
|
||||
|
||||
if (newCompleted) {
|
||||
toast({
|
||||
title: `"${deadline.title}" markerad som klar`,
|
||||
title: t('marked_done', { title: deadline.title }),
|
||||
action: (
|
||||
<ToastAction altText="Ångra" onClick={async () => {
|
||||
<ToastAction altText={t('undo')} onClick={async () => {
|
||||
try {
|
||||
await fetch(`/api/deadlines/${deadline.id}/complete`, {
|
||||
method: 'POST',
|
||||
@@ -124,22 +126,22 @@ export default function DeadlinesPage() {
|
||||
})
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte ångra',
|
||||
title: t('undo_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}}>
|
||||
Ångra
|
||||
{t('undo')}
|
||||
</ToastAction>
|
||||
),
|
||||
})
|
||||
} else {
|
||||
toast({ title: `"${deadline.title}" markerad som ej klar` })
|
||||
toast({ title: t('marked_not_done', { title: deadline.title }) })
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Kunde inte uppdatera status',
|
||||
description: error instanceof Error ? error.message : 'Försök igen.',
|
||||
title: t('toggle_failed_title'),
|
||||
description: error instanceof Error ? error.message : t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -159,15 +161,15 @@ export default function DeadlinesPage() {
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Deadline uppdaterad',
|
||||
description: 'Dina ändringar har sparats',
|
||||
title: t('updated_title'),
|
||||
description: t('updated_description'),
|
||||
})
|
||||
|
||||
fetchData()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Kunde inte spara ändringar',
|
||||
description: error instanceof Error ? error.message : 'Försök igen.',
|
||||
title: t('update_failed_title'),
|
||||
description: error instanceof Error ? error.message : t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -184,12 +186,12 @@ export default function DeadlinesPage() {
|
||||
throw new Error(result.error || 'Failed to delete deadline')
|
||||
}
|
||||
|
||||
toast({ title: 'Deadline borttagen' })
|
||||
toast({ title: t('deleted_title') })
|
||||
fetchData()
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Kunde inte ta bort deadline',
|
||||
description: error instanceof Error ? error.message : 'Försök igen.',
|
||||
title: t('delete_failed_title'),
|
||||
description: error instanceof Error ? error.message : t('retry'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -198,7 +200,7 @@ export default function DeadlinesPage() {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader title="Deadlines" />
|
||||
<PageHeader title={t('title')} />
|
||||
<div className="space-y-3">
|
||||
{[1, 2, 3, 4].map((i) => (
|
||||
<div key={i} className="rounded-lg border p-4 animate-pulse">
|
||||
@@ -223,7 +225,7 @@ export default function DeadlinesPage() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title="Deadlines" />
|
||||
<PageHeader title={t('title')} />
|
||||
|
||||
{/* Overdue invoices alert */}
|
||||
{overdueInvoices.count > 0 && (
|
||||
@@ -232,7 +234,7 @@ export default function DeadlinesPage() {
|
||||
<div className="flex items-center gap-3">
|
||||
<AlertTriangle className="h-4 w-4 text-destructive flex-shrink-0" />
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{overdueInvoices.count} förfallna fakturor</span>
|
||||
<span className="font-medium">{t('overdue_invoices', { count: overdueInvoices.count })}</span>
|
||||
<span className="text-muted-foreground ml-1.5">
|
||||
{overdueInvoices.total.toLocaleString('sv-SE')} kr
|
||||
</span>
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { notFound } from 'next/navigation'
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
import { getExtensionDefinition, getSector } from '@/lib/extensions/sectors'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import {
|
||||
extensionNameKey,
|
||||
extensionDescriptionKey,
|
||||
extensionLongDescriptionKey,
|
||||
sectorNameKey,
|
||||
} from '@/lib/extensions/i18n'
|
||||
import type { SectorSlug } from '@/lib/extensions/types'
|
||||
import CategoryBadge from '@/components/extensions/CategoryBadge'
|
||||
import { WORKSPACES } from '@/lib/extensions/_generated/workspace-map'
|
||||
@@ -19,14 +26,29 @@ export default async function ExtensionDetailPage({
|
||||
|
||||
const sector = getSector(sectorSlug as SectorSlug)
|
||||
|
||||
const t = await getTranslations('extensions')
|
||||
|
||||
const nameKey = extensionNameKey(definition.slug)
|
||||
const descriptionKey = extensionDescriptionKey(definition.slug)
|
||||
const longDescriptionKey = extensionLongDescriptionKey(definition.slug)
|
||||
const extensionName = nameKey ? t(nameKey) : definition.name
|
||||
const extensionDescription = descriptionKey ? t(descriptionKey) : definition.description
|
||||
const extensionLongDescription = longDescriptionKey ? t(longDescriptionKey) : definition.longDescription
|
||||
|
||||
const sectorLabel = (() => {
|
||||
if (!sector) return sectorSlug
|
||||
const key = sectorNameKey(sector.slug)
|
||||
return key ? t(key) : sector.name
|
||||
})()
|
||||
|
||||
const Icon = resolveIcon(definition.icon)
|
||||
|
||||
const hasWorkspace = `${sectorSlug}/${extensionSlug}` in WORKSPACES
|
||||
|
||||
const dataPatternLabels: Record<string, string> = {
|
||||
core: 'Använder bokföringsdata',
|
||||
manual: 'Manuell inmatning',
|
||||
both: 'Bokföringsdata + manuell inmatning',
|
||||
core: t('data_pattern_core'),
|
||||
manual: t('data_pattern_manual'),
|
||||
both: t('data_pattern_both'),
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -34,17 +56,17 @@ export default async function ExtensionDetailPage({
|
||||
{/* Breadcrumb */}
|
||||
<nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-6">
|
||||
<Link href="/extensions" className="hover:text-foreground transition-colors">
|
||||
Tillägg
|
||||
{t('breadcrumb')}
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<Link
|
||||
href={`/extensions/${sectorSlug}`}
|
||||
className="hover:text-foreground transition-colors"
|
||||
>
|
||||
{sector?.name ?? sectorSlug}
|
||||
{sectorLabel}
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<span className="text-foreground">{definition.name}</span>
|
||||
<span className="text-foreground">{extensionName}</span>
|
||||
</nav>
|
||||
|
||||
{/* Header */}
|
||||
@@ -54,8 +76,8 @@ export default async function ExtensionDetailPage({
|
||||
<Icon className="h-7 w-7 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{definition.name}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{definition.description}</p>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{extensionName}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{extensionDescription}</p>
|
||||
<div className="mt-2">
|
||||
<CategoryBadge category={definition.category} />
|
||||
</div>
|
||||
@@ -64,7 +86,7 @@ export default async function ExtensionDetailPage({
|
||||
{hasWorkspace && (
|
||||
<Button asChild>
|
||||
<Link href={`/e/${sectorSlug}/${extensionSlug}`}>
|
||||
Öppna
|
||||
{t('open')}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
@@ -73,20 +95,20 @@ export default async function ExtensionDetailPage({
|
||||
{/* Details */}
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold mb-2">Beskrivning</h2>
|
||||
<h2 className="text-sm font-semibold mb-2">{t('description_heading')}</h2>
|
||||
<p className="text-sm text-muted-foreground leading-relaxed">
|
||||
{definition.longDescription}
|
||||
{extensionLongDescription}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-sm font-semibold mb-2">Datakälla</h2>
|
||||
<h2 className="text-sm font-semibold mb-2">{t('data_source_heading')}</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{dataPatternLabels[definition.dataPattern]}
|
||||
</p>
|
||||
{definition.readsCoreTables && definition.readsCoreTables.length > 0 && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Läser från: {definition.readsCoreTables.join(', ')}
|
||||
{t('reads_from', { tables: definition.readsCoreTables.join(', ') })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { notFound } from 'next/navigation'
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
import { getSector } from '@/lib/extensions/sectors'
|
||||
import { resolveIcon } from '@/lib/extensions/icon-resolver'
|
||||
import { sectorNameKey, sectorDescriptionKey } from '@/lib/extensions/i18n'
|
||||
import type { SectorSlug } from '@/lib/extensions/types'
|
||||
import ExtensionCard from '@/components/extensions/ExtensionCard'
|
||||
import Link from 'next/link'
|
||||
@@ -15,7 +17,14 @@ export default async function SectorExtensionsPage({
|
||||
|
||||
if (!sector) notFound()
|
||||
|
||||
|
||||
const t = await getTranslations('extensions')
|
||||
|
||||
const nameKey = sectorNameKey(sector.slug)
|
||||
const descriptionKey = sectorDescriptionKey(sector.slug)
|
||||
const sectorName = nameKey ? t(nameKey) : sector.name
|
||||
const sectorDescription = descriptionKey ? t(descriptionKey) : sector.description
|
||||
|
||||
|
||||
const Icon = resolveIcon(sector.icon)
|
||||
|
||||
return (
|
||||
@@ -23,10 +32,10 @@ export default async function SectorExtensionsPage({
|
||||
{/* Breadcrumb */}
|
||||
<nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-6">
|
||||
<Link href="/extensions" className="hover:text-foreground transition-colors">
|
||||
Tillägg
|
||||
{t('breadcrumb')}
|
||||
</Link>
|
||||
<span>/</span>
|
||||
<span className="text-foreground">{sector.name}</span>
|
||||
<span className="text-foreground">{sectorName}</span>
|
||||
</nav>
|
||||
|
||||
{/* Header */}
|
||||
@@ -35,8 +44,8 @@ export default async function SectorExtensionsPage({
|
||||
<Icon className="h-6 w-6 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{sector.name}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{sector.description}</p>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{sectorName}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">{sectorDescription}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
import { SECTORS } from '@/lib/extensions/sectors'
|
||||
import { sectorNameKey } from '@/lib/extensions/i18n'
|
||||
import ExtensionCard from '@/components/extensions/ExtensionCard'
|
||||
import SectorCard from '@/components/extensions/SectorCard'
|
||||
|
||||
export default function ExtensionsPage() {
|
||||
export default async function ExtensionsPage() {
|
||||
const t = await getTranslations('extensions')
|
||||
const generalSector = SECTORS.find(s => s.slug === 'general')
|
||||
const industrySectors = SECTORS.filter(s => s.slug !== 'general')
|
||||
|
||||
const generalSectorName = (() => {
|
||||
if (!generalSector) return ''
|
||||
const key = sectorNameKey(generalSector.slug)
|
||||
return key ? t(key) : generalSector.name
|
||||
})()
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-8">
|
||||
<h1 className="text-xl font-semibold tracking-tight">Tillägg</h1>
|
||||
<h1 className="text-xl font-semibold tracking-tight">{t('page_title')}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Utöka ditt bokföringssystem med verktyg och branschspecifika funktioner.
|
||||
{t('page_description')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -19,7 +28,7 @@ export default function ExtensionsPage() {
|
||||
{generalSector && (
|
||||
<section className="mb-8">
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4">
|
||||
{generalSector.name}
|
||||
{generalSectorName}
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{generalSector.extensions.map(ext => (
|
||||
@@ -32,7 +41,7 @@ export default function ExtensionsPage() {
|
||||
{/* Industry sectors */}
|
||||
<section>
|
||||
<h2 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider mb-4">
|
||||
Branschverktyg
|
||||
{t('industry_tools')}
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
|
||||
{industrySectors.map(sector => (
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useMemo } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -209,15 +210,16 @@ const glossaryTerms: GlossaryTerm[] = [
|
||||
]
|
||||
|
||||
const categoryConfig = {
|
||||
skatt: { label: 'Skatt', icon: Calculator, color: 'bg-orange-500/10 text-orange-600' },
|
||||
moms: { label: 'Moms', icon: Receipt, color: 'bg-blue-500/10 text-blue-600' },
|
||||
faktura: { label: 'Faktura', icon: FileText, color: 'bg-success/10 text-success' },
|
||||
bokföring: { label: 'Bokföring', icon: BookOpen, color: 'bg-purple-500/10 text-purple-600' },
|
||||
bank: { label: 'Bank', icon: Building2, color: 'bg-pink-500/10 text-pink-600' },
|
||||
företag: { label: 'Företag', icon: Building2, color: 'bg-cyan-500/10 text-cyan-600' },
|
||||
skatt: { labelKey: 'category_skatt', icon: Calculator, color: 'bg-orange-500/10 text-orange-600' },
|
||||
moms: { labelKey: 'category_moms', icon: Receipt, color: 'bg-blue-500/10 text-blue-600' },
|
||||
faktura: { labelKey: 'category_faktura', icon: FileText, color: 'bg-success/10 text-success' },
|
||||
bokföring: { labelKey: 'category_bokforing', icon: BookOpen, color: 'bg-purple-500/10 text-purple-600' },
|
||||
bank: { labelKey: 'category_bank', icon: Building2, color: 'bg-pink-500/10 text-pink-600' },
|
||||
företag: { labelKey: 'category_foretag', icon: Building2, color: 'bg-cyan-500/10 text-cyan-600' },
|
||||
}
|
||||
|
||||
function TermCard({ term, isExpanded, onToggle }: { term: GlossaryTerm; isExpanded: boolean; onToggle: () => void }) {
|
||||
const t = useTranslations('help')
|
||||
const config = categoryConfig[term.category]
|
||||
const CategoryIcon = config.icon
|
||||
|
||||
@@ -265,7 +267,7 @@ function TermCard({ term, isExpanded, onToggle }: { term: GlossaryTerm; isExpand
|
||||
|
||||
{term.relatedTerms && term.relatedTerms.length > 0 && (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-xs text-muted-foreground">Relaterat:</span>
|
||||
<span className="text-xs text-muted-foreground">{t('related_label')}</span>
|
||||
{term.relatedTerms.map((related) => (
|
||||
<Badge key={related} variant="outline" className="text-xs">
|
||||
{related}
|
||||
@@ -276,7 +278,7 @@ function TermCard({ term, isExpanded, onToggle }: { term: GlossaryTerm; isExpand
|
||||
|
||||
{term.skatteverketUrl && (
|
||||
<HelpLink href={term.skatteverketUrl}>
|
||||
Läs mer på Skatteverket
|
||||
{t('read_more_skv')}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</HelpLink>
|
||||
)}
|
||||
@@ -288,6 +290,7 @@ function TermCard({ term, isExpanded, onToggle }: { term: GlossaryTerm; isExpand
|
||||
}
|
||||
|
||||
export default function HelpPage() {
|
||||
const t = useTranslations('help')
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [selectedCategory, setSelectedCategory] = useState<string | null>(null)
|
||||
const [expandedTerms, setExpandedTerms] = useState<Set<string>>(new Set())
|
||||
@@ -329,8 +332,8 @@ export default function HelpPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Hjälp & Ordlista"
|
||||
description="Förklaringar av skatte- och bokföringstermer på ren svenska."
|
||||
title={t('title')}
|
||||
description={t('subtitle')}
|
||||
/>
|
||||
|
||||
{/* Search */}
|
||||
@@ -338,7 +341,7 @@ export default function HelpPage() {
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
type="search"
|
||||
placeholder="Sök efter term..."
|
||||
placeholder={t('search_placeholder')}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-9"
|
||||
@@ -356,7 +359,7 @@ export default function HelpPage() {
|
||||
: 'bg-secondary text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
Alla
|
||||
{t('filter_all')}
|
||||
</button>
|
||||
{Object.entries(categoryConfig).map(([key, config]) => (
|
||||
<button
|
||||
@@ -369,7 +372,7 @@ export default function HelpPage() {
|
||||
: 'bg-secondary text-muted-foreground hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
{config.label}
|
||||
{t(config.labelKey)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -381,7 +384,7 @@ export default function HelpPage() {
|
||||
<CardContent className="py-12 text-center">
|
||||
<Search className="h-8 w-8 text-muted-foreground mx-auto mb-3" />
|
||||
<p className="text-muted-foreground">
|
||||
Inga termer hittades för "{searchQuery}"
|
||||
{t('no_results', { query: searchQuery })}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -400,8 +403,8 @@ export default function HelpPage() {
|
||||
{/* Document templates */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Dokument & Mallar</CardTitle>
|
||||
<CardDescription>Lagstadgade mallar för din bokföring — ladda ner, fyll i och spara</CardDescription>
|
||||
<CardTitle className="text-lg">{t('templates_title')}</CardTitle>
|
||||
<CardDescription>{t('templates_subtitle')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
@@ -438,7 +441,7 @@ export default function HelpPage() {
|
||||
{/* External resources */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Externa resurser</CardTitle>
|
||||
<CardTitle className="text-lg">{t('external_resources_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
@@ -475,10 +478,10 @@ export default function HelpPage() {
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5 text-muted-foreground" />
|
||||
<CardTitle>Behöver du mer hjälp?</CardTitle>
|
||||
<CardTitle>{t('support_title')}</CardTitle>
|
||||
</div>
|
||||
<CardDescription>
|
||||
Hittar du inte svaret? Kontakta oss så hjälper vi dig.
|
||||
{t('support_subtitle')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import { useSearchParams } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -1729,6 +1730,7 @@ export default function ImportPage() {
|
||||
const [mode, setMode] = useState<ImportMode>(null)
|
||||
const [userId, setUserId] = useState('')
|
||||
const [isSandbox, setIsSandbox] = useState(false)
|
||||
const t = useTranslations('import')
|
||||
|
||||
// Fetch authenticated user ID and sandbox status
|
||||
useEffect(() => {
|
||||
@@ -1769,9 +1771,9 @@ export default function ImportPage() {
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Importera</h1>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{t('title')}</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Importera banktransaktioner eller bokföringsdata till ditt företag
|
||||
{t('subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -1781,7 +1783,7 @@ export default function ImportPage() {
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/50 px-4 py-3">
|
||||
<Info className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Import är inte tillgängligt i sandlådemiljön. Skapa ett konto för att importera data.
|
||||
{t('sandbox_disabled')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -1807,13 +1809,13 @@ export default function ImportPage() {
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<h3 className="text-[15px] font-semibold leading-tight">Koppla bank</h3>
|
||||
<h3 className="text-[15px] font-semibold leading-tight">{t('psd2_title')}</h3>
|
||||
<span className="text-[11px] font-medium text-success bg-success/10 px-2 py-0.5 rounded-full leading-none">
|
||||
Rekommenderat
|
||||
{t('psd2_recommended')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
|
||||
Anslut ditt bankkonto direkt och synka transaktioner automatiskt via PSD2.
|
||||
{t('psd2_description')}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground/40 shrink-0 mt-2.5 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-muted-foreground" />
|
||||
@@ -1840,9 +1842,9 @@ export default function ImportPage() {
|
||||
<ArrowRightLeft className="h-[18px] w-[18px] text-foreground/60" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-[15px] font-semibold leading-tight">Hämta från annat system</h3>
|
||||
<h3 className="text-[15px] font-semibold leading-tight">{t('migration_title')}</h3>
|
||||
<p className="text-sm mt-1.5 leading-relaxed max-w-lg underline decoration-foreground/20 underline-offset-2 text-muted-foreground">
|
||||
Inget ändras i ditt befintliga system.
|
||||
{t('migration_description')}
|
||||
</p>
|
||||
</div>
|
||||
<ChevronRight className="h-4 w-4 text-muted-foreground/40 shrink-0 mt-2.5 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-muted-foreground" />
|
||||
@@ -1882,9 +1884,9 @@ export default function ImportPage() {
|
||||
<ArrowLeftRight className="h-[18px] w-[18px] text-foreground/60" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-[15px] font-semibold leading-tight">Banktransaktioner</h3>
|
||||
<h3 className="text-[15px] font-semibold leading-tight">{t('bankfile_title')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
|
||||
Importera kontoutdrag från din bank. Stöder de flesta svenska banker.
|
||||
{t('bankfile_description')}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5 mt-2.5">
|
||||
{['CSV', 'OFX', 'SEB', 'Swedbank', 'Nordea'].map(fmt => (
|
||||
@@ -1915,14 +1917,20 @@ export default function ImportPage() {
|
||||
<FileSpreadsheet className="h-[18px] w-[18px] text-foreground/60" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-[15px] font-semibold leading-tight">Importera CSV/Excel-data</h3>
|
||||
<h3 className="text-[15px] font-semibold leading-tight">{t('csv_data_title')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
|
||||
Importera ingående balanser, kunder eller leverantörer.
|
||||
{t('csv_data_description')}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5 mt-2.5">
|
||||
{['XLSX', 'CSV', 'Ingående balanser', 'Kunder', 'Leverantörer'].map(fmt => (
|
||||
<span key={fmt} className="text-[11px] text-muted-foreground/80 bg-muted/80 px-1.5 py-0.5 rounded leading-none">
|
||||
{fmt}
|
||||
{[
|
||||
{ key: 'XLSX', label: 'XLSX' },
|
||||
{ key: 'CSV', label: 'CSV' },
|
||||
{ key: 'opening_balances', label: t('csv_chip_opening_balances') },
|
||||
{ key: 'customers', label: t('csv_chip_customers') },
|
||||
{ key: 'suppliers', label: t('csv_chip_suppliers') },
|
||||
].map(chip => (
|
||||
<span key={chip.key} className="text-[11px] text-muted-foreground/80 bg-muted/80 px-1.5 py-0.5 rounded leading-none">
|
||||
{chip.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
@@ -1948,9 +1956,9 @@ export default function ImportPage() {
|
||||
<FileText className="h-[18px] w-[18px] text-foreground/60" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="text-[15px] font-semibold leading-tight">Bokföringsdata (SIE)</h3>
|
||||
<h3 className="text-[15px] font-semibold leading-tight">{t('sie_title')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
|
||||
Importera verifikationer och kontoplan från ett annat bokföringsprogram.
|
||||
{t('sie_description')}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5 mt-2.5">
|
||||
{['SIE4', '.se', '.si'].map(fmt => (
|
||||
@@ -1969,7 +1977,7 @@ export default function ImportPage() {
|
||||
{mode !== null && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setMode(null)}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka till val
|
||||
{t('back_to_choices')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect, use } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -27,6 +28,7 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
const t = useTranslations('invoice_credit')
|
||||
|
||||
const [invoice, setInvoice] = useState<InvoiceWithRelations | null>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
@@ -53,8 +55,8 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
|
||||
if (error || !data) {
|
||||
toast({
|
||||
title: 'Kunde inte ladda faktura',
|
||||
description: 'Fakturan hittades inte.',
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
router.push('/invoices')
|
||||
@@ -64,8 +66,8 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
// Check if invoice can be credited
|
||||
if (!['sent', 'paid', 'overdue'].includes(data.status)) {
|
||||
toast({
|
||||
title: 'Kan inte krediteras',
|
||||
description: 'Endast skickade, betalda eller förfallna fakturor kan krediteras',
|
||||
title: t('cannot_credit_title'),
|
||||
description: t('cannot_credit_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
router.push(`/invoices/${id}`)
|
||||
@@ -74,8 +76,8 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
|
||||
if (data.status === 'credited') {
|
||||
toast({
|
||||
title: 'Redan krediterad',
|
||||
description: 'Denna faktura har redan krediterats',
|
||||
title: t('already_credited_title'),
|
||||
description: t('already_credited_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
router.push(`/invoices/${id}`)
|
||||
@@ -88,7 +90,7 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
}
|
||||
|
||||
setInvoice(data as InvoiceWithRelations)
|
||||
setReason(`Krediterar faktura ${data.invoice_number}`)
|
||||
setReason(t('reason_default', { number: data.invoice_number ?? '' }))
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
@@ -109,21 +111,21 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json()
|
||||
throw new Error(data.error || 'Failed to create credit note')
|
||||
throw new Error(data.error || t('create_failed_fallback'))
|
||||
}
|
||||
|
||||
const { data: creditNote } = await response.json()
|
||||
|
||||
toast({
|
||||
title: 'Kreditfaktura skapad',
|
||||
description: `Kreditfaktura ${creditNote.invoice_number} har skapats`,
|
||||
title: t('created_toast_title'),
|
||||
description: t('created_toast_description', { number: creditNote.invoice_number }),
|
||||
})
|
||||
|
||||
router.push(`/invoices/${creditNote.id}`)
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Kunde inte skapa kreditfaktura',
|
||||
description: error instanceof Error ? error.message : 'Försök igen.',
|
||||
title: t('create_failed_title'),
|
||||
description: error instanceof Error ? error.message : t('try_again'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -149,13 +151,13 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
<div className="space-y-6 max-w-3xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="icon" onClick={() => router.back()} aria-label="Tillbaka">
|
||||
<Button variant="ghost" size="icon" onClick={() => router.back()} aria-label={t('back')}>
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Skapa kreditfaktura</h1>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{t('title')}</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Krediterar faktura {invoice.invoice_number}
|
||||
{t('subtitle', { number: invoice.invoice_number ?? '' })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -165,11 +167,9 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
<CardContent className="flex items-start gap-4 pt-6">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-destructive">Oåterkallelig åtgärd</p>
|
||||
<p className="font-medium text-destructive">{t('warning_title')}</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
En kreditfaktura makulerar den ursprungliga fakturan helt.
|
||||
Alla belopp blir negativa, en bokföringsverifikation skapas, och den ursprungliga fakturan markeras som krediterad.
|
||||
Denna åtgärd kan inte ångras.
|
||||
{t('warning_description')}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -178,27 +178,27 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
{/* Original invoice info */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ursprunglig faktura</CardTitle>
|
||||
<CardTitle>{t('original_card_title')}</CardTitle>
|
||||
<CardDescription>
|
||||
Kreditfakturan baseras på denna faktura
|
||||
{t('original_card_description')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">Fakturanummer:</span>
|
||||
<span className="text-muted-foreground">{t('invoice_number_label')}</span>
|
||||
<span className="ml-2 font-medium">{invoice.invoice_number}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Datum:</span>
|
||||
<span className="text-muted-foreground">{t('date_label')}</span>
|
||||
<span className="ml-2">{formatDate(invoice.invoice_date)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Kund:</span>
|
||||
<span className="text-muted-foreground">{t('customer_label')}</span>
|
||||
<span className="ml-2">{customer.name}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">Momsbehandling:</span>
|
||||
<span className="text-muted-foreground">{t('vat_treatment_label')}</span>
|
||||
<span className="ml-2">{getVatTreatmentLabel(invoice.vat_treatment)}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -208,20 +208,20 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
{/* Credit note preview */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Kreditfaktura förhandsgranskning</CardTitle>
|
||||
<CardTitle>{t('preview_card_title')}</CardTitle>
|
||||
<CardDescription>
|
||||
Kreditfakturanummer: KR-{invoice.invoice_number}
|
||||
{t('preview_card_description', { number: invoice.invoice_number ?? '' })}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{/* Header */}
|
||||
<div className="grid grid-cols-12 gap-4 text-sm font-medium text-muted-foreground border-b pb-2">
|
||||
<div className="col-span-5">Beskrivning</div>
|
||||
<div className="col-span-2 text-right">Antal</div>
|
||||
<div className="col-span-1 text-center">Enhet</div>
|
||||
<div className="col-span-2 text-right">à-pris</div>
|
||||
<div className="col-span-2 text-right">Summa</div>
|
||||
<div className="col-span-5">{t('th_description')}</div>
|
||||
<div className="col-span-2 text-right">{t('th_quantity')}</div>
|
||||
<div className="col-span-1 text-center">{t('th_unit')}</div>
|
||||
<div className="col-span-2 text-right">{t('th_unit_price')}</div>
|
||||
<div className="col-span-2 text-right">{t('th_amount')}</div>
|
||||
</div>
|
||||
|
||||
{/* Items (negated) */}
|
||||
@@ -246,27 +246,27 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
{/* Totals (negated) */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Delsumma</span>
|
||||
<span className="text-muted-foreground">{t('subtotal')}</span>
|
||||
<span className="text-destructive">
|
||||
{formatCurrency(-Math.abs(invoice.subtotal), invoice.currency)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between">
|
||||
<span className="text-muted-foreground">Moms ({invoice.vat_rate}%)</span>
|
||||
<span className="text-muted-foreground">{t('vat_at_rate', { rate: invoice.vat_rate })}</span>
|
||||
<span className="text-destructive">
|
||||
{formatCurrency(-Math.abs(invoice.vat_amount), invoice.currency)}
|
||||
</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between font-bold text-lg">
|
||||
<span>Totalt</span>
|
||||
<span>{t('total')}</span>
|
||||
<span className="text-destructive">
|
||||
{formatCurrency(-Math.abs(invoice.total), invoice.currency)}
|
||||
</span>
|
||||
</div>
|
||||
{invoice.currency !== 'SEK' && invoice.total_sek && (
|
||||
<div className="flex justify-between text-sm text-muted-foreground">
|
||||
<span>I SEK (kurs {invoice.exchange_rate})</span>
|
||||
<span>{t('in_sek', { rate: invoice.exchange_rate ?? 1 })}</span>
|
||||
<span className="text-destructive">
|
||||
{formatCurrency(-Math.abs(invoice.total_sek))}
|
||||
</span>
|
||||
@@ -280,19 +280,19 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
{/* Reason */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Anledning</CardTitle>
|
||||
<CardTitle>{t('reason_card_title')}</CardTitle>
|
||||
<CardDescription>
|
||||
Ange anledning till kreditering (visas på kreditfakturan)
|
||||
{t('reason_card_description')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="reason">Anledning</Label>
|
||||
<Label htmlFor="reason">{t('reason_label')}</Label>
|
||||
<Textarea
|
||||
id="reason"
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
placeholder="T.ex. Felaktig fakturering, returnerade varor..."
|
||||
placeholder={t('reason_placeholder')}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
@@ -302,9 +302,11 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
{/* Confirmation */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Bekräfta</CardTitle>
|
||||
<CardTitle>{t('confirm_card_title')}</CardTitle>
|
||||
<CardDescription>
|
||||
Skriv fakturanumret <span className="font-mono font-semibold text-foreground">{invoice.invoice_number}</span> för att bekräfta
|
||||
{t('confirm_card_description_1')}
|
||||
<span className="font-mono font-semibold text-foreground">{invoice.invoice_number}</span>
|
||||
{t('confirm_card_description_2')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -323,7 +325,7 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
{/* Actions */}
|
||||
<div className="flex justify-end gap-4">
|
||||
<Button variant="outline" onClick={() => router.back()}>
|
||||
Avbryt
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
@@ -334,20 +336,20 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
confirmText !== invoice.invoice_number ||
|
||||
!canWrite
|
||||
}
|
||||
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Skapar...
|
||||
{t('creating')}
|
||||
</>
|
||||
) : !canWrite ? (
|
||||
<>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Skapa kreditfaktura
|
||||
{t('create_credit_note')}
|
||||
</>
|
||||
) : (
|
||||
'Skapa kreditfaktura'
|
||||
t('create_credit_note')
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
@@ -21,35 +22,40 @@ import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import type { Invoice, InvoiceStatus } from '@/types'
|
||||
|
||||
const statusConfig: Record<InvoiceStatus, { label: string; variant: 'default' | 'secondary' | 'success' | 'warning' | 'destructive' }> = {
|
||||
draft: { label: 'Utkast', variant: 'secondary' },
|
||||
sent: { label: 'Skickad', variant: 'default' },
|
||||
paid: { label: 'Betald', variant: 'success' },
|
||||
partially_paid: { label: 'Delbetalad', variant: 'warning' },
|
||||
overdue: { label: 'Förfallen', variant: 'destructive' },
|
||||
cancelled: { label: 'Makulerad', variant: 'secondary' },
|
||||
credited: { label: 'Krediterad', variant: 'secondary' },
|
||||
type InvoiceStatusVariant = 'default' | 'secondary' | 'success' | 'warning' | 'destructive'
|
||||
|
||||
const STATUS_CONFIG: Record<InvoiceStatus, { labelKey: string; variant: InvoiceStatusVariant }> = {
|
||||
draft: { labelKey: 'status_draft', variant: 'secondary' },
|
||||
sent: { labelKey: 'status_sent', variant: 'default' },
|
||||
paid: { labelKey: 'status_paid', variant: 'success' },
|
||||
partially_paid: { labelKey: 'status_partially_paid', variant: 'warning' },
|
||||
overdue: { labelKey: 'status_overdue', variant: 'destructive' },
|
||||
cancelled: { labelKey: 'status_cancelled', variant: 'secondary' },
|
||||
credited: { labelKey: 'status_credited', variant: 'secondary' },
|
||||
}
|
||||
|
||||
function getRelativeTimeLabel(dueDateStr: string, status: InvoiceStatus): { text: string; color: string } | null {
|
||||
if (status === 'paid' || status === 'cancelled' || status === 'credited' || status === 'draft') return null
|
||||
function useRelativeTimeLabel() {
|
||||
const t = useTranslations('invoices')
|
||||
return function getRelativeTimeLabel(dueDateStr: string, status: InvoiceStatus): { text: string; color: string } | null {
|
||||
if (status === 'paid' || status === 'cancelled' || status === 'credited' || status === 'draft') return null
|
||||
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const dueDate = new Date(dueDateStr)
|
||||
dueDate.setHours(0, 0, 0, 0)
|
||||
const diffDays = Math.round((dueDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const dueDate = new Date(dueDateStr)
|
||||
dueDate.setHours(0, 0, 0, 0)
|
||||
const diffDays = Math.round((dueDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
||||
|
||||
if (diffDays < 0) {
|
||||
return { text: `${Math.abs(diffDays)} dagar försenad`, color: 'text-destructive' }
|
||||
} else if (diffDays === 0) {
|
||||
return { text: 'Förfaller idag', color: 'text-warning-foreground' }
|
||||
} else if (diffDays <= 3) {
|
||||
return { text: `${diffDays} dagar kvar`, color: 'text-warning-foreground' }
|
||||
} else if (diffDays <= 7) {
|
||||
return { text: `${diffDays} dagar kvar`, color: 'text-muted-foreground' }
|
||||
if (diffDays < 0) {
|
||||
return { text: t('due_days_overdue', { days: Math.abs(diffDays) }), color: 'text-destructive' }
|
||||
} else if (diffDays === 0) {
|
||||
return { text: t('due_today'), color: 'text-warning-foreground' }
|
||||
} else if (diffDays <= 3) {
|
||||
return { text: t('due_days_left', { days: diffDays }), color: 'text-warning-foreground' }
|
||||
} else if (diffDays <= 7) {
|
||||
return { text: t('due_days_left', { days: diffDays }), color: 'text-muted-foreground' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export default function InvoicesPage() {
|
||||
@@ -62,6 +68,8 @@ export default function InvoicesPage() {
|
||||
const [activeTab, setActiveTab] = useState('all')
|
||||
const { toast } = useToast()
|
||||
const supabase = createClient()
|
||||
const t = useTranslations('invoices')
|
||||
const getRelativeTimeLabel = useRelativeTimeLabel()
|
||||
|
||||
async function fetchInvoices() {
|
||||
if (!company) return
|
||||
@@ -81,8 +89,8 @@ export default function InvoicesPage() {
|
||||
|
||||
if (invoicesResult.error) {
|
||||
toast({
|
||||
title: 'Kunde inte ladda fakturor',
|
||||
description: 'Kontrollera din anslutning och försök igen.',
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} else {
|
||||
@@ -103,9 +111,6 @@ export default function InvoicesPage() {
|
||||
|
||||
const isCreditNote = !!invoice.credited_invoice_id
|
||||
const docType = (invoice as Invoice & { document_type?: string }).document_type || 'invoice'
|
||||
// Cancelled invoices are kept in the table for compliance but hidden from
|
||||
// the default 'Alla' view; they only show up when the user explicitly picks
|
||||
// the 'Makulerade' tab.
|
||||
const matchesTab =
|
||||
(activeTab === 'all' && invoice.status !== 'cancelled') ||
|
||||
(activeTab === 'unpaid' && ['sent', 'overdue'].includes(invoice.status) && !isCreditNote && docType === 'invoice') ||
|
||||
@@ -136,29 +141,29 @@ export default function InvoicesPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Fakturor"
|
||||
title={t('title')}
|
||||
action={
|
||||
<div className="flex gap-2">
|
||||
<Link href="/invoices/recurring">
|
||||
<Button variant="secondary">
|
||||
<Repeat className="mr-2 h-4 w-4" />
|
||||
Återkommande
|
||||
{t('recurring')}
|
||||
</Button>
|
||||
</Link>
|
||||
{canWrite ? (
|
||||
<Link href="/invoices/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Ny faktura
|
||||
{t('new_invoice')}
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<Button
|
||||
disabled
|
||||
title="Du har endast läsbehörighet i detta företag"
|
||||
title={t('viewer_disabled_tooltip')}
|
||||
>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Ny faktura
|
||||
{t('new_invoice')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -168,17 +173,17 @@ export default function InvoicesPage() {
|
||||
{/* Inline summary */}
|
||||
{!isLoading && invoices.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground tabular-nums">
|
||||
{invoices.length} {invoices.length === 1 ? 'faktura' : 'fakturor'}
|
||||
{invoices.length === 1 ? t('summary_one', { count: invoices.length }) : t('summary_other', { count: invoices.length })}
|
||||
{stats.unpaid > 0 && (
|
||||
<>
|
||||
{' · '}
|
||||
<span className="text-foreground">{stats.unpaid} obetalda</span>
|
||||
<span className="text-foreground">{t('summary_unpaid', { count: stats.unpaid })}</span>
|
||||
{' · '}
|
||||
{formatCurrency(stats.unpaidAmount)} att få in
|
||||
{t('summary_to_collect', { amount: formatCurrency(stats.unpaidAmount) })}
|
||||
{stats.overdue > 0 && (
|
||||
<>
|
||||
{' · '}
|
||||
<span className="text-destructive">{stats.overdue} förfallna</span>
|
||||
<span className="text-destructive">{t('summary_overdue', { count: stats.overdue })}</span>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
@@ -191,7 +196,7 @@ export default function InvoicesPage() {
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Sök fakturor"
|
||||
placeholder={t('search_placeholder')}
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
className="pl-10"
|
||||
@@ -203,27 +208,27 @@ export default function InvoicesPage() {
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Alla</SelectItem>
|
||||
<SelectItem value="unpaid">Obetalda</SelectItem>
|
||||
<SelectItem value="paid">Betalda</SelectItem>
|
||||
<SelectItem value="draft">Utkast</SelectItem>
|
||||
<SelectItem value="proforma">Proforma</SelectItem>
|
||||
<SelectItem value="delivery_note">Följesedel</SelectItem>
|
||||
<SelectItem value="credit">Kredit</SelectItem>
|
||||
<SelectItem value="cancelled">Makulerade</SelectItem>
|
||||
<SelectItem value="all">{t('tab_all')}</SelectItem>
|
||||
<SelectItem value="unpaid">{t('tab_unpaid')}</SelectItem>
|
||||
<SelectItem value="paid">{t('tab_paid')}</SelectItem>
|
||||
<SelectItem value="draft">{t('tab_draft')}</SelectItem>
|
||||
<SelectItem value="proforma">{t('tab_proforma')}</SelectItem>
|
||||
<SelectItem value="delivery_note">{t('tab_delivery_note')}</SelectItem>
|
||||
<SelectItem value="credit">{t('tab_credit')}</SelectItem>
|
||||
<SelectItem value="cancelled">{t('tab_cancelled')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{/* Desktop: tab bar */}
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="hidden sm:block">
|
||||
<TabsList>
|
||||
<TabsTrigger value="all">Alla</TabsTrigger>
|
||||
<TabsTrigger value="unpaid">Obetalda</TabsTrigger>
|
||||
<TabsTrigger value="paid">Betalda</TabsTrigger>
|
||||
<TabsTrigger value="draft">Utkast</TabsTrigger>
|
||||
<TabsTrigger value="proforma">Proforma</TabsTrigger>
|
||||
<TabsTrigger value="delivery_note">Följesedel</TabsTrigger>
|
||||
<TabsTrigger value="credit">Kredit</TabsTrigger>
|
||||
<TabsTrigger value="cancelled">Makulerade</TabsTrigger>
|
||||
<TabsTrigger value="all">{t('tab_all')}</TabsTrigger>
|
||||
<TabsTrigger value="unpaid">{t('tab_unpaid')}</TabsTrigger>
|
||||
<TabsTrigger value="paid">{t('tab_paid')}</TabsTrigger>
|
||||
<TabsTrigger value="draft">{t('tab_draft')}</TabsTrigger>
|
||||
<TabsTrigger value="proforma">{t('tab_proforma')}</TabsTrigger>
|
||||
<TabsTrigger value="delivery_note">{t('tab_delivery_note')}</TabsTrigger>
|
||||
<TabsTrigger value="credit">{t('tab_credit')}</TabsTrigger>
|
||||
<TabsTrigger value="cancelled">{t('tab_cancelled')}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
</div>
|
||||
@@ -251,16 +256,16 @@ export default function InvoicesPage() {
|
||||
{searchTerm ? (
|
||||
<EmptyState
|
||||
icon={Receipt}
|
||||
title="Inga träffar"
|
||||
description={`Inga fakturor matchar "${searchTerm}".`}
|
||||
title={t('no_search_results_title')}
|
||||
description={t('no_search_results_description', { term: searchTerm })}
|
||||
/>
|
||||
) : invoices.length === 0 ? (
|
||||
<EmptyInvoices />
|
||||
) : (
|
||||
<EmptyState
|
||||
icon={Receipt}
|
||||
title="Inga fakturor i denna kategori"
|
||||
description="Prova att byta flik för att se fler fakturor."
|
||||
title={t('no_category_title')}
|
||||
description={t('no_category_description')}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -268,7 +273,7 @@ export default function InvoicesPage() {
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{filteredInvoices.map((invoice) => {
|
||||
const status = statusConfig[invoice.status]
|
||||
const status = STATUS_CONFIG[invoice.status]
|
||||
const isCreditNote = !!invoice.credited_invoice_id
|
||||
const docType = (invoice as Invoice & { document_type?: string }).document_type || 'invoice'
|
||||
const isProforma = docType === 'proforma'
|
||||
@@ -296,21 +301,21 @@ export default function InvoicesPage() {
|
||||
<div className="flex flex-wrap items-center gap-1.5 mt-1.5">
|
||||
{isCreditNote && (
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
Kredit
|
||||
{t('badge_credit')}
|
||||
</Badge>
|
||||
)}
|
||||
{isProforma && (
|
||||
<Badge variant="secondary" className="text-xs bg-primary/10 text-primary">
|
||||
Proforma
|
||||
{t('badge_proforma')}
|
||||
</Badge>
|
||||
)}
|
||||
{isDeliveryNote && (
|
||||
<Badge variant="secondary" className="text-xs bg-success/10 text-success">
|
||||
Följesedel
|
||||
{t('badge_delivery_note')}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge variant={status.variant as 'default' | 'secondary' | 'destructive'}>
|
||||
{status.label}
|
||||
{t(status.labelKey)}
|
||||
</Badge>
|
||||
{relativeTime && (
|
||||
<span className={`text-xs font-medium ${relativeTime.color}`}>
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { useForm, useFieldArray, Controller } from 'react-hook-form'
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
@@ -26,32 +27,6 @@ import { ArrowLeft, Plus, Trash2 } from 'lucide-react'
|
||||
import type { Customer, Currency } from '@/types'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
|
||||
const itemSchema = z.object({
|
||||
description: z.string().min(1, 'Beskrivning krävs'),
|
||||
quantity: z.number().min(0.01, 'Minst 0.01'),
|
||||
unit: z.string().min(1, 'Enhet krävs'),
|
||||
unit_price: z.number(),
|
||||
vat_rate: z
|
||||
.union([z.literal(0), z.literal(6), z.literal(12), z.literal(25)])
|
||||
.nullable()
|
||||
.optional(),
|
||||
})
|
||||
|
||||
const schema = z.object({
|
||||
customer_id: z.string().uuid('Välj en kund'),
|
||||
name: z.string().min(1, 'Namn krävs'),
|
||||
day_of_month: z.number().int().min(1).max(31),
|
||||
payment_terms_days: z.number().int().min(0).max(90),
|
||||
currency: z.enum(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']),
|
||||
auto_send: z.boolean(),
|
||||
your_reference: z.string().optional(),
|
||||
our_reference: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
items: z.array(itemSchema).min(1, 'Minst en rad krävs'),
|
||||
})
|
||||
|
||||
type FormData = z.infer<typeof schema>
|
||||
|
||||
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
|
||||
const units = ['st', 'tim', 'dag', 'månad', 'km', 'kg']
|
||||
|
||||
@@ -60,9 +35,37 @@ export default function NewRecurringSchedulePage() {
|
||||
const { toast } = useToast()
|
||||
const { company } = useCompany()
|
||||
const supabase = createClient()
|
||||
const t = useTranslations('invoice_recurring_new')
|
||||
const [customers, setCustomers] = useState<Customer[]>([])
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
|
||||
const schema = useMemo(() => {
|
||||
const itemSchema = z.object({
|
||||
description: z.string().min(1, t('validation_description_required')),
|
||||
quantity: z.number().min(0.01, t('validation_quantity_min')),
|
||||
unit: z.string().min(1, t('validation_unit_required')),
|
||||
unit_price: z.number(),
|
||||
vat_rate: z
|
||||
.union([z.literal(0), z.literal(6), z.literal(12), z.literal(25)])
|
||||
.nullable()
|
||||
.optional(),
|
||||
})
|
||||
return z.object({
|
||||
customer_id: z.string().uuid(t('validation_customer_required')),
|
||||
name: z.string().min(1, t('validation_name_required')),
|
||||
day_of_month: z.number().int().min(1).max(31),
|
||||
payment_terms_days: z.number().int().min(0).max(90),
|
||||
currency: z.enum(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']),
|
||||
auto_send: z.boolean(),
|
||||
your_reference: z.string().optional(),
|
||||
our_reference: z.string().optional(),
|
||||
notes: z.string().optional(),
|
||||
items: z.array(itemSchema).min(1, t('validation_min_one_row')),
|
||||
})
|
||||
}, [t])
|
||||
|
||||
type FormData = z.infer<typeof schema>
|
||||
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
@@ -104,13 +107,13 @@ export default function NewRecurringSchedulePage() {
|
||||
})
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(body.error || 'Kunde inte skapa schema')
|
||||
throw new Error(body.error || t('create_failed_fallback'))
|
||||
}
|
||||
toast({ title: 'Schema skapat' })
|
||||
toast({ title: t('created_title') })
|
||||
router.push('/invoices/recurring')
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: 'Kunde inte skapa schema',
|
||||
title: t('create_failed_title'),
|
||||
description: err instanceof Error ? err.message : undefined,
|
||||
variant: 'destructive',
|
||||
})
|
||||
@@ -135,22 +138,22 @@ export default function NewRecurringSchedulePage() {
|
||||
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-1" />
|
||||
Tillbaka
|
||||
{t('back')}
|
||||
</Link>
|
||||
|
||||
<PageHeader title="Nytt återkommande schema" />
|
||||
<PageHeader title={t('title')} />
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Schema</CardTitle>
|
||||
<CardTitle className="text-base">{t('schedule_card_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div>
|
||||
<Label htmlFor="name">Namn</Label>
|
||||
<Label htmlFor="name">{t('name_label')}</Label>
|
||||
<Input
|
||||
id="name"
|
||||
placeholder="t.ex. Månadsretainer Acme AB"
|
||||
placeholder={t('name_placeholder')}
|
||||
{...register('name')}
|
||||
/>
|
||||
{errors.name && (
|
||||
@@ -159,14 +162,14 @@ export default function NewRecurringSchedulePage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="customer_id">Kund</Label>
|
||||
<Label htmlFor="customer_id">{t('customer_label')}</Label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="customer_id"
|
||||
render={({ field }) => (
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<SelectTrigger id="customer_id">
|
||||
<SelectValue placeholder="Välj kund" />
|
||||
<SelectValue placeholder={t('customer_placeholder')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{customers.map((c) => (
|
||||
@@ -185,7 +188,7 @@ export default function NewRecurringSchedulePage() {
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="day_of_month">Dag i månaden</Label>
|
||||
<Label htmlFor="day_of_month">{t('day_label')}</Label>
|
||||
<Input
|
||||
id="day_of_month"
|
||||
type="number"
|
||||
@@ -195,11 +198,11 @@ export default function NewRecurringSchedulePage() {
|
||||
{...register('day_of_month', { valueAsNumber: true })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
29-31 körs sista dagen i kortare månader.
|
||||
{t('day_hint')}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="payment_terms_days">Betalningsvillkor (dagar)</Label>
|
||||
<Label htmlFor="payment_terms_days">{t('payment_terms_label')}</Label>
|
||||
<Input
|
||||
id="payment_terms_days"
|
||||
type="number"
|
||||
@@ -210,7 +213,7 @@ export default function NewRecurringSchedulePage() {
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="currency">Valuta</Label>
|
||||
<Label htmlFor="currency">{t('currency_label')}</Label>
|
||||
<Controller
|
||||
control={control}
|
||||
name="currency"
|
||||
@@ -249,11 +252,10 @@ export default function NewRecurringSchedulePage() {
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="auto_send" className="font-medium">
|
||||
Skapa och skicka automatiskt
|
||||
{t('auto_send_label')}
|
||||
</Label>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
När markerad: fakturan skickas med e-post till kunden direkt vid
|
||||
skapande. Annars skapas den som utkast för manuell granskning.
|
||||
{t('auto_send_description')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -263,7 +265,7 @@ export default function NewRecurringSchedulePage() {
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Rader</CardTitle>
|
||||
<CardTitle className="text-base">{t('items_card_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{fields.map((field, index) => (
|
||||
@@ -273,7 +275,7 @@ export default function NewRecurringSchedulePage() {
|
||||
>
|
||||
<div className="col-span-12 sm:col-span-5">
|
||||
<Input
|
||||
placeholder="Beskrivning"
|
||||
placeholder={t('description_placeholder')}
|
||||
{...register(`items.${index}.description`)}
|
||||
/>
|
||||
</div>
|
||||
@@ -281,7 +283,7 @@ export default function NewRecurringSchedulePage() {
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
placeholder="Antal"
|
||||
placeholder={t('quantity_placeholder')}
|
||||
className="tabular-nums"
|
||||
{...register(`items.${index}.quantity`, { valueAsNumber: true })}
|
||||
/>
|
||||
@@ -310,7 +312,7 @@ export default function NewRecurringSchedulePage() {
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
placeholder="à-pris"
|
||||
placeholder={t('unit_price_placeholder')}
|
||||
className="tabular-nums"
|
||||
{...register(`items.${index}.unit_price`, { valueAsNumber: true })}
|
||||
/>
|
||||
@@ -321,7 +323,7 @@ export default function NewRecurringSchedulePage() {
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => fields.length > 1 && remove(index)}
|
||||
aria-label="Ta bort rad"
|
||||
aria-label={t('remove_row')}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -337,31 +339,31 @@ export default function NewRecurringSchedulePage() {
|
||||
}
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Lägg till rad
|
||||
{t('add_row')}
|
||||
</Button>
|
||||
<div className="pt-2 text-sm text-muted-foreground tabular-nums">
|
||||
Delsumma exkl. moms: {formatCurrency(subtotal, watchCurrency)}
|
||||
{t('subtotal_ex_vat', { amount: formatCurrency(subtotal, watchCurrency) })}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Övrigt</CardTitle>
|
||||
<CardTitle className="text-base">{t('other_card_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label htmlFor="your_reference">Er referens</Label>
|
||||
<Label htmlFor="your_reference">{t('your_reference_label')}</Label>
|
||||
<Input id="your_reference" {...register('your_reference')} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="our_reference">Vår referens</Label>
|
||||
<Label htmlFor="our_reference">{t('our_reference_label')}</Label>
|
||||
<Input id="our_reference" {...register('our_reference')} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="notes">Anteckningar (skrivs på varje faktura)</Label>
|
||||
<Label htmlFor="notes">{t('notes_label')}</Label>
|
||||
<Textarea id="notes" rows={3} {...register('notes')} />
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -370,11 +372,11 @@ export default function NewRecurringSchedulePage() {
|
||||
<div className="flex justify-end gap-2">
|
||||
<Link href="/invoices/recurring">
|
||||
<Button type="button" variant="secondary">
|
||||
Avbryt
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
</Link>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? 'Skapar...' : 'Skapa schema'}
|
||||
{isSubmitting ? t('creating') : t('create_schedule')}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -32,6 +33,7 @@ export default function RecurringInvoicesPage() {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { toast } = useToast()
|
||||
const router = useRouter()
|
||||
const t = useTranslations('invoice_recurring')
|
||||
|
||||
async function fetchSchedules() {
|
||||
setIsLoading(true)
|
||||
@@ -42,8 +44,8 @@ export default function RecurringInvoicesPage() {
|
||||
setSchedules(json.data ?? [])
|
||||
} catch {
|
||||
toast({
|
||||
title: 'Kunde inte ladda återkommande fakturor',
|
||||
description: 'Kontrollera din anslutning och försök igen.',
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -63,46 +65,46 @@ export default function RecurringInvoicesPage() {
|
||||
})
|
||||
if (res.ok) {
|
||||
toast({
|
||||
title: next === 'paused' ? 'Schema pausat' : 'Schema återaktiverat',
|
||||
title: next === 'paused' ? t('schedule_paused_title') : t('schedule_resumed_title'),
|
||||
})
|
||||
fetchSchedules()
|
||||
} else {
|
||||
toast({
|
||||
title: 'Kunde inte uppdatera schema',
|
||||
title: t('schedule_update_failed_title'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSchedule(s: ScheduleRow) {
|
||||
if (!confirm(`Ta bort schemat "${s.name}"? Redan skapade fakturor påverkas inte.`)) {
|
||||
if (!confirm(t('delete_confirm', { name: s.name }))) {
|
||||
return
|
||||
}
|
||||
const res = await fetch(`/api/invoices/recurring/${s.id}`, { method: 'DELETE' })
|
||||
if (res.ok) {
|
||||
toast({ title: 'Schema borttaget' })
|
||||
toast({ title: t('schedule_deleted_title') })
|
||||
fetchSchedules()
|
||||
} else {
|
||||
toast({ title: 'Kunde inte ta bort schema', variant: 'destructive' })
|
||||
toast({ title: t('schedule_delete_failed_title'), variant: 'destructive' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Återkommande fakturor"
|
||||
title={t('title')}
|
||||
action={
|
||||
canWrite ? (
|
||||
<Link href="/invoices/recurring/new">
|
||||
<Button>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Nytt schema
|
||||
{t('new_schedule')}
|
||||
</Button>
|
||||
</Link>
|
||||
) : (
|
||||
<Button disabled title="Du har endast läsbehörighet i detta företag">
|
||||
<Button disabled title={t('viewer_disabled_tooltip')}>
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
Nytt schema
|
||||
{t('new_schedule')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -111,7 +113,7 @@ export default function RecurringInvoicesPage() {
|
||||
{isLoading ? (
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center text-sm text-muted-foreground">
|
||||
Laddar...
|
||||
{t('loading')}
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : schedules.length === 0 ? (
|
||||
@@ -119,9 +121,9 @@ export default function RecurringInvoicesPage() {
|
||||
<CardContent className="p-0">
|
||||
<EmptyState
|
||||
icon={Repeat}
|
||||
title="Inga återkommande fakturor"
|
||||
description="Skapa ett schema för att automatiskt fakturera kunder på en bestämd dag varje månad."
|
||||
actionLabel={canWrite ? 'Nytt schema' : undefined}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
actionLabel={canWrite ? t('new_schedule') : undefined}
|
||||
actionHref={canWrite ? '/invoices/recurring/new' : undefined}
|
||||
/>
|
||||
</CardContent>
|
||||
@@ -132,13 +134,13 @@ export default function RecurringInvoicesPage() {
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Namn</TableHead>
|
||||
<TableHead>Kund</TableHead>
|
||||
<TableHead className="tabular-nums">Dag</TableHead>
|
||||
<TableHead className="tabular-nums">Nästa körning</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="tabular-nums text-right">Skapade</TableHead>
|
||||
<TableHead className="text-right">Åtgärder</TableHead>
|
||||
<TableHead>{t('th_name')}</TableHead>
|
||||
<TableHead>{t('th_customer')}</TableHead>
|
||||
<TableHead className="tabular-nums">{t('th_day')}</TableHead>
|
||||
<TableHead className="tabular-nums">{t('th_next_run')}</TableHead>
|
||||
<TableHead>{t('th_status')}</TableHead>
|
||||
<TableHead className="tabular-nums text-right">{t('th_generated')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_actions')}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -166,9 +168,9 @@ export default function RecurringInvoicesPage() {
|
||||
<TableCell className="tabular-nums">{formatDate(s.next_run_date)}</TableCell>
|
||||
<TableCell>
|
||||
{s.status === 'active' ? (
|
||||
<Badge variant="success">Aktiv</Badge>
|
||||
<Badge variant="success">{t('status_active')}</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">Pausad</Badge>
|
||||
<Badge variant="secondary">{t('status_paused')}</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="tabular-nums text-right">
|
||||
@@ -186,14 +188,14 @@ export default function RecurringInvoicesPage() {
|
||||
size="sm"
|
||||
onClick={() => togglePause(s)}
|
||||
>
|
||||
{s.status === 'active' ? 'Pausa' : 'Aktivera'}
|
||||
{s.status === 'active' ? t('pause') : t('resume')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => deleteSchedule(s)}
|
||||
>
|
||||
Ta bort
|
||||
{t('delete')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
|
||||
@@ -13,6 +14,7 @@ import { getDefaultPreferences } from '@/lib/reports/kpi-definitions'
|
||||
import type { KPIReport, KPIPreferences } from '@/types'
|
||||
|
||||
export default function KpiPage() {
|
||||
const t = useTranslations('kpi')
|
||||
const [selectedPeriod, setSelectedPeriod] = useState<string>('')
|
||||
const [report, setReport] = useState<KPIReport | null>(null)
|
||||
const [preferences, setPreferences] = useState<KPIPreferences>(getDefaultPreferences())
|
||||
@@ -39,15 +41,15 @@ export default function KpiPage() {
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/reports/kpi?period_id=${periodId}`)
|
||||
if (!res.ok) throw new Error('Kunde inte hämta nyckeltal')
|
||||
if (!res.ok) throw new Error(t('fetch_failed'))
|
||||
const { data } = await res.json()
|
||||
setReport(data)
|
||||
} catch {
|
||||
setError('Kunde inte hämta nyckeltal')
|
||||
setError(t('fetch_failed'))
|
||||
} finally {
|
||||
setIsLoadingReport(false)
|
||||
}
|
||||
}, [])
|
||||
}, [t])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedPeriod) return
|
||||
@@ -80,7 +82,7 @@ export default function KpiPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Nyckeltal</h1>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{t('title')}</h1>
|
||||
<KPISettingsDialog
|
||||
preferences={preferences}
|
||||
onSave={handleSavePreferences}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useMemo, Fragment } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -26,18 +27,18 @@ import type { PendingOperation, PendingOperationStatus } from '@/types'
|
||||
import { AttachDocumentPreview } from '@/components/bookkeeping/AttachDocumentPreview'
|
||||
import { MatchTransactionInvoicePreview } from '@/components/bookkeeping/MatchTransactionInvoicePreview'
|
||||
|
||||
const operationLabels: Record<string, { label: string; icon: typeof ArrowLeftRight; variant: 'default' | 'secondary' | 'outline' }> = {
|
||||
categorize_transaction: { label: 'Kategorisering', icon: ArrowLeftRight, variant: 'default' },
|
||||
create_customer: { label: 'Ny kund', icon: Users, variant: 'secondary' },
|
||||
create_invoice: { label: 'Ny faktura', icon: Receipt, variant: 'outline' },
|
||||
create_transaction: { label: 'Ny transaktion', icon: ArrowLeftRight, variant: 'secondary' },
|
||||
create_voucher: { label: 'Ny verifikation', icon: BookOpen, variant: 'outline' },
|
||||
correct_entry: { label: 'Rättelse', icon: BookOpen, variant: 'outline' },
|
||||
reverse_entry: { label: 'Makulering', icon: BookOpen, variant: 'outline' },
|
||||
mark_invoice_paid: { label: 'Betald faktura', icon: Receipt, variant: 'default' },
|
||||
send_invoice: { label: 'Skicka faktura', icon: Receipt, variant: 'outline' },
|
||||
mark_invoice_sent: { label: 'Markera skickad', icon: Receipt, variant: 'outline' },
|
||||
match_transaction_invoice: { label: 'Fakturamatchning', icon: ArrowLeftRight, variant: 'secondary' },
|
||||
const OPERATION_LABEL_KEYS: Record<string, { labelKey: string; icon: typeof ArrowLeftRight; variant: 'default' | 'secondary' | 'outline' }> = {
|
||||
categorize_transaction: { labelKey: 'type_categorize_transaction', icon: ArrowLeftRight, variant: 'default' },
|
||||
create_customer: { labelKey: 'type_create_customer', icon: Users, variant: 'secondary' },
|
||||
create_invoice: { labelKey: 'type_create_invoice', icon: Receipt, variant: 'outline' },
|
||||
create_transaction: { labelKey: 'type_create_transaction', icon: ArrowLeftRight, variant: 'secondary' },
|
||||
create_voucher: { labelKey: 'type_create_voucher', icon: BookOpen, variant: 'outline' },
|
||||
correct_entry: { labelKey: 'type_correct_entry', icon: BookOpen, variant: 'outline' },
|
||||
reverse_entry: { labelKey: 'type_reverse_entry', icon: BookOpen, variant: 'outline' },
|
||||
mark_invoice_paid: { labelKey: 'type_mark_invoice_paid', icon: Receipt, variant: 'default' },
|
||||
send_invoice: { labelKey: 'type_send_invoice', icon: Receipt, variant: 'outline' },
|
||||
mark_invoice_sent: { labelKey: 'type_mark_invoice_sent', icon: Receipt, variant: 'outline' },
|
||||
match_transaction_invoice: { labelKey: 'type_match_transaction_invoice', icon: ArrowLeftRight, variant: 'secondary' },
|
||||
}
|
||||
|
||||
// Terse per-type labels used in the bulk confirmation dialog list. Phrased so
|
||||
@@ -58,10 +59,11 @@ const bulkActionDescriptions: Record<string, (count: number) => string> = {
|
||||
n === 1 ? 'En kategorisering tas bort.' : `${n} kategoriseringar tas bort.`,
|
||||
}
|
||||
|
||||
function bulkActionLabel(operationType: string, count: number): string {
|
||||
function bulkActionLabel(operationType: string, count: number, t: (key: string) => string): string {
|
||||
const fn = bulkActionDescriptions[operationType]
|
||||
if (fn) return fn(count)
|
||||
const fallback = operationLabels[operationType]?.label ?? operationType
|
||||
const entry = OPERATION_LABEL_KEYS[operationType]
|
||||
const fallback = entry ? t(entry.labelKey) : operationType
|
||||
return `${count} × ${fallback}`
|
||||
}
|
||||
|
||||
@@ -389,6 +391,7 @@ function OperationPreview({ op }: { op: PendingOperation }) {
|
||||
type SourceFilter = 'all' | 'agent' | 'high_risk'
|
||||
|
||||
export default function PendingOperationsPage() {
|
||||
const t = useTranslations('pending')
|
||||
const [operations, setOperations] = useState<PendingOperation[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [activeTab, setActiveTab] = useState<PendingOperationStatus>('pending')
|
||||
@@ -580,23 +583,23 @@ export default function PendingOperationsPage() {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="Granskning"
|
||||
description="Operationer som väntar på godkännande"
|
||||
title={t('title')}
|
||||
description={t('subtitle')}
|
||||
/>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as PendingOperationStatus)}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="pending">Väntande</TabsTrigger>
|
||||
<TabsTrigger value="committed">Godkända</TabsTrigger>
|
||||
<TabsTrigger value="rejected">Avvisade</TabsTrigger>
|
||||
<TabsTrigger value="pending">{t('tab_pending')}</TabsTrigger>
|
||||
<TabsTrigger value="committed">{t('tab_committed')}</TabsTrigger>
|
||||
<TabsTrigger value="rejected">{t('tab_rejected')}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
<Tabs value={sourceFilter} onValueChange={(v) => setSourceFilter(v as SourceFilter)}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="all">Alla</TabsTrigger>
|
||||
<TabsTrigger value="agent">Från agent</TabsTrigger>
|
||||
<TabsTrigger value="high_risk">Hög risk</TabsTrigger>
|
||||
<TabsTrigger value="all">{t('tab_all')}</TabsTrigger>
|
||||
<TabsTrigger value="agent">{t('tab_agent')}</TabsTrigger>
|
||||
<TabsTrigger value="high_risk">{t('tab_high_risk')}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
|
||||
@@ -607,20 +610,21 @@ export default function PendingOperationsPage() {
|
||||
id="select-all"
|
||||
checked={allSelected ? true : someSelected ? 'indeterminate' : false}
|
||||
onCheckedChange={() => toggleSelectAll()}
|
||||
aria-label="Markera alla"
|
||||
aria-label={t('select_all_aria')}
|
||||
/>
|
||||
<label htmlFor="select-all" className="text-sm cursor-pointer">
|
||||
{selectedCount > 0
|
||||
? `${selectedCount} valda`
|
||||
: `Markera alla (${bulkEligible.length})`}
|
||||
? t('selected_count', { count: selectedCount })
|
||||
: t('select_all_count', { count: bulkEligible.length })}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{typeCounts.length > 0 && selectedCount === 0 && (
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<span className="text-xs text-muted-foreground">Snabbval:</span>
|
||||
<span className="text-xs text-muted-foreground">{t('quick_pick')}</span>
|
||||
{typeCounts.map(([type, count]) => {
|
||||
const config = operationLabels[type] || { label: type }
|
||||
const entry = OPERATION_LABEL_KEYS[type]
|
||||
const label = entry ? t(entry.labelKey) : type
|
||||
return (
|
||||
<Button
|
||||
key={type}
|
||||
@@ -629,7 +633,7 @@ export default function PendingOperationsPage() {
|
||||
className="h-7 px-2 text-xs"
|
||||
onClick={() => selectAllOfType(type)}
|
||||
>
|
||||
{config.label} ({count})
|
||||
{label} ({count})
|
||||
</Button>
|
||||
)
|
||||
})}
|
||||
@@ -644,7 +648,7 @@ export default function PendingOperationsPage() {
|
||||
className="h-8 px-3 text-xs"
|
||||
onClick={() => setSelectedIds(new Set())}
|
||||
>
|
||||
Avmarkera
|
||||
{t('deselect')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
@@ -653,7 +657,7 @@ export default function PendingOperationsPage() {
|
||||
disabled={selectedCount === 0 || isBulkCommitting}
|
||||
onClick={() => setShowBulkDialog(true)}
|
||||
>
|
||||
Godkänn valda ({selectedCount})
|
||||
{t('approve_selected', { count: selectedCount })}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -673,22 +677,25 @@ export default function PendingOperationsPage() {
|
||||
</div>
|
||||
<p className="font-medium">
|
||||
{activeTab === 'pending'
|
||||
? 'Inga väntande operationer'
|
||||
? t('empty_pending_title')
|
||||
: activeTab === 'committed'
|
||||
? 'Inga godkända operationer'
|
||||
: 'Inga avvisade operationer'}
|
||||
? t('empty_committed_title')
|
||||
: t('empty_rejected_title')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{activeTab === 'pending'
|
||||
? 'När en operation kräver godkännande visas den här för granskning.'
|
||||
: 'Operationer du har godkänt eller avvisat visas här.'}
|
||||
? t('empty_pending_description')
|
||||
: t('empty_finished_description')}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{filteredOperations.map((op) => {
|
||||
const config = operationLabels[op.operation_type] || { label: op.operation_type, icon: ClipboardCheck, variant: 'default' as const }
|
||||
const entry = OPERATION_LABEL_KEYS[op.operation_type]
|
||||
const config = entry
|
||||
? { label: t(entry.labelKey), icon: entry.icon, variant: entry.variant }
|
||||
: { label: op.operation_type, icon: ClipboardCheck, variant: 'default' as const }
|
||||
const isExpanded = expandedId === op.id
|
||||
const canBulkSelect = showBulkControls && op.status === 'pending' && op.risk_level !== 'high'
|
||||
const isSelected = selectedIds.has(op.id)
|
||||
@@ -711,7 +718,7 @@ export default function PendingOperationsPage() {
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={() => toggleSelected(op.id)}
|
||||
aria-label="Välj operation"
|
||||
aria-label={t('select_operation_aria')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -720,7 +727,7 @@ export default function PendingOperationsPage() {
|
||||
<Badge variant={config.variant}>{config.label}</Badge>
|
||||
{op.risk_level === 'high' && (
|
||||
<Badge variant="outline" className="border-terracotta/40 text-terracotta">
|
||||
Hög risk
|
||||
{t('badge_high_risk')}
|
||||
</Badge>
|
||||
)}
|
||||
{op.actor_type && op.actor_type !== 'user' && (
|
||||
@@ -732,13 +739,13 @@ export default function PendingOperationsPage() {
|
||||
{op.status === 'committed' && (
|
||||
<Badge variant="success">
|
||||
<CheckCircle2 className="h-3 w-3 mr-1" />
|
||||
Godkänd
|
||||
{t('badge_approved')}
|
||||
</Badge>
|
||||
)}
|
||||
{op.status === 'rejected' && (
|
||||
<Badge variant="destructive">
|
||||
<XCircle className="h-3 w-3 mr-1" />
|
||||
Avvisad
|
||||
{t('badge_rejected')}
|
||||
</Badge>
|
||||
)}
|
||||
<span className="text-xs text-muted-foreground">
|
||||
@@ -759,7 +766,7 @@ export default function PendingOperationsPage() {
|
||||
setShowCommitDialog(true)
|
||||
}}
|
||||
>
|
||||
Godkänn
|
||||
{t('approve')}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
@@ -770,7 +777,7 @@ export default function PendingOperationsPage() {
|
||||
handleReject(op)
|
||||
}}
|
||||
>
|
||||
Avvisa
|
||||
{t('reject')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
@@ -795,9 +802,9 @@ export default function PendingOperationsPage() {
|
||||
<ConfirmationDialog
|
||||
open={showCommitDialog}
|
||||
onOpenChange={setShowCommitDialog}
|
||||
title={selectedOp?.title || 'Godkänn operation'}
|
||||
title={selectedOp?.title || t('approve_operation_title')}
|
||||
warningText={selectedOp ? singleActionWarning(selectedOp.operation_type) : ''}
|
||||
confirmLabel="Godkänn"
|
||||
confirmLabel={t('approve')}
|
||||
isSubmitting={isCommitting}
|
||||
onConfirm={handleCommit}
|
||||
>
|
||||
@@ -808,24 +815,24 @@ export default function PendingOperationsPage() {
|
||||
<ConfirmationDialog
|
||||
open={showBulkDialog}
|
||||
onOpenChange={setShowBulkDialog}
|
||||
title={`Godkänn ${selectedCount} operationer?`}
|
||||
title={t('approve_bulk_title', { count: selectedCount })}
|
||||
warningText=""
|
||||
confirmLabel={`Godkänn ${selectedCount}`}
|
||||
confirmLabel={t('approve_count', { count: selectedCount })}
|
||||
isSubmitting={isBulkCommitting}
|
||||
onConfirm={() => handleBulkCommit(Array.from(selectedIds))}
|
||||
>
|
||||
<div className="space-y-3 text-sm">
|
||||
<p>Genom att bekräfta utförs följande:</p>
|
||||
<p>{t('bulk_confirm_intro')}</p>
|
||||
<ul className="space-y-1 rounded-md border bg-muted/30 px-3 py-2">
|
||||
{selectedBreakdown.map(({ type, count }) => (
|
||||
<li key={type} className="flex justify-between font-mono tabular-nums">
|
||||
<span className="font-sans">{bulkActionLabel(type, count)}</span>
|
||||
<span className="font-sans">{bulkActionLabel(type, count, t)}</span>
|
||||
<span className="text-muted-foreground">{count}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Operationerna körs i ordning. Misslyckade hoppas över och rapporteras efteråt.
|
||||
{t('bulk_confirm_footer')}
|
||||
</p>
|
||||
</div>
|
||||
</ConfirmationDialog>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import React, { useState, useEffect, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -43,13 +44,13 @@ interface DrillDownStep {
|
||||
accountNumber?: string
|
||||
}
|
||||
|
||||
const TAB_LABELS: Record<string, string> = {
|
||||
'resultatrapport': 'Resultatrapport',
|
||||
'balansrapport': 'Balansrapport',
|
||||
'trial-balance': 'Saldobalans',
|
||||
'income-statement': 'Resultaträkning',
|
||||
'balance-sheet': 'Balansräkning',
|
||||
'huvudbok': 'Huvudbok',
|
||||
const TAB_LABEL_KEYS: Record<string, string> = {
|
||||
'resultatrapport': 'name_resultatrapport',
|
||||
'balansrapport': 'name_balansrapport',
|
||||
'trial-balance': 'name_trial_balance',
|
||||
'income-statement': 'name_income_statement',
|
||||
'balance-sheet': 'name_balance_sheet',
|
||||
'huvudbok': 'name_huvudbok',
|
||||
}
|
||||
|
||||
export default function ReportsPage() {
|
||||
@@ -57,6 +58,7 @@ export default function ReportsPage() {
|
||||
const [activeTab, setActiveTab] = useState('resultatrapport')
|
||||
const [isLoadingInit, setIsLoadingInit] = useState(true)
|
||||
const { company } = useCompany()
|
||||
const t = useTranslations('reports')
|
||||
|
||||
// Drill-down state: when navigating from a report to the GL for a specific account
|
||||
const [glAccountFilter, setGlAccountFilter] = useState<string | null>(null)
|
||||
@@ -65,11 +67,11 @@ export default function ReportsPage() {
|
||||
const navigateToAccount = useCallback((accountNumber: string) => {
|
||||
setDrillDownTrail((prev) => [
|
||||
...prev,
|
||||
{ tab: activeTab, label: TAB_LABELS[activeTab] || activeTab },
|
||||
{ tab: activeTab, label: TAB_LABEL_KEYS[activeTab] ? t(TAB_LABEL_KEYS[activeTab]) : activeTab },
|
||||
])
|
||||
setGlAccountFilter(accountNumber)
|
||||
setActiveTab('huvudbok')
|
||||
}, [activeTab])
|
||||
}, [activeTab, t])
|
||||
|
||||
const handleTabChange = useCallback((tab: string) => {
|
||||
// Manual tab change clears drill-down state
|
||||
@@ -94,7 +96,7 @@ export default function ReportsPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Rapporter</h1>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{t('title')}</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row sm:items-end gap-4">
|
||||
@@ -113,7 +115,7 @@ export default function ReportsPage() {
|
||||
}}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Ladda ner SIE-fil
|
||||
{t('download_sie')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
@@ -159,7 +161,7 @@ export default function ReportsPage() {
|
||||
</React.Fragment>
|
||||
))}
|
||||
<span className="font-medium">
|
||||
Huvudbok {glAccountFilter && `— ${glAccountFilter}`}
|
||||
{t('name_huvudbok')} {glAccountFilter && `— ${glAccountFilter}`}
|
||||
</span>
|
||||
</nav>
|
||||
)}
|
||||
@@ -444,6 +446,7 @@ function TrialBalanceView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
)
|
||||
}
|
||||
function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: string; onNavigateToAccount: (account: string) => void }) {
|
||||
const t = useTranslations('reports')
|
||||
const [data, setData] = useState<IncomeStatementReport | null>(null)
|
||||
const [monthlyData, setMonthlyData] = useState<MonthlyDataPoint[]>([])
|
||||
const [monthlyLoading, setMonthlyLoading] = useState(false)
|
||||
@@ -523,7 +526,7 @@ function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
onClick={() => window.open(`/api/reports/income-statement/pdf?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Ladda ner PDF
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -603,6 +606,7 @@ function IncomeStatementView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
}
|
||||
|
||||
function BalanceSheetView({ periodId, onNavigateToAccount }: { periodId: string; onNavigateToAccount: (account: string) => void }) {
|
||||
const t = useTranslations('reports')
|
||||
const [data, setData] = useState<BalanceSheetReport | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -668,7 +672,7 @@ function BalanceSheetView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
onClick={() => window.open(`/api/reports/balance-sheet/pdf?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Ladda ner PDF
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -727,6 +731,7 @@ function BalanceSheetView({ periodId, onNavigateToAccount }: { periodId: string;
|
||||
}
|
||||
|
||||
function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: string; onNavigateToAccount: (account: string) => void }) {
|
||||
const t = useTranslations('reports')
|
||||
const [data, setData] = useState<ResultatrapportReport | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -792,7 +797,7 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
onClick={() => window.open(`/api/reports/resultatrapport/pdf?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Ladda ner PDF
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -867,6 +872,7 @@ function ResultatrapportView({ periodId, onNavigateToAccount }: { periodId: stri
|
||||
}
|
||||
|
||||
function BalansrapportView({ periodId, onNavigateToAccount }: { periodId: string; onNavigateToAccount: (account: string) => void }) {
|
||||
const t = useTranslations('reports')
|
||||
const [data, setData] = useState<BalansrapportReport | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
@@ -930,7 +936,7 @@ function BalansrapportView({ periodId, onNavigateToAccount }: { periodId: string
|
||||
onClick={() => window.open(`/api/reports/balansrapport/pdf?period_id=${periodId}`, '_blank')}
|
||||
>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
Ladda ner PDF
|
||||
{t('download_pdf')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -12,13 +13,14 @@ import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { Employee } from '@/types'
|
||||
|
||||
const EMPLOYMENT_LABELS: Record<string, string> = {
|
||||
employee: 'Anställd',
|
||||
company_owner: 'Företagsledare',
|
||||
board_member: 'Styrelseledamot',
|
||||
const EMPLOYMENT_LABEL_KEYS: Record<string, string> = {
|
||||
employee: 'employment_employee',
|
||||
company_owner: 'employment_company_owner',
|
||||
board_member: 'employment_board_member',
|
||||
}
|
||||
|
||||
export default function EmployeesPage() {
|
||||
const t = useTranslations('employees')
|
||||
const [employees, setEmployees] = useState<Employee[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const { canWrite } = useCanWrite()
|
||||
@@ -40,18 +42,18 @@ export default function EmployeesPage() {
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="icon" asChild>
|
||||
<Link href="/salary" aria-label="Tillbaka till löner"><ArrowLeft className="h-4 w-4" /></Link>
|
||||
<Link href="/salary" aria-label={t('back_to_payroll')}><ArrowLeft className="h-4 w-4" /></Link>
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Anställda</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">{employees.length} registrerade</p>
|
||||
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">{t('title')}</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">{t('registered_count', { count: employees.length })}</p>
|
||||
</div>
|
||||
</div>
|
||||
{canWrite && (
|
||||
<Button asChild>
|
||||
<Link href="/salary/employees/new">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Ny anställd
|
||||
{t('new_employee')}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
@@ -68,9 +70,9 @@ export default function EmployeesPage() {
|
||||
<CardContent className="p-0">
|
||||
<EmptyState
|
||||
icon={UserCircle}
|
||||
title="Inga anställda"
|
||||
description="Lägg till anställda för att kunna skapa lönekörningar och AGI-deklarationer."
|
||||
actionLabel={canWrite ? 'Lägg till anställd' : undefined}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_description')}
|
||||
actionLabel={canWrite ? t('add_employee') : undefined}
|
||||
actionHref={canWrite ? '/salary/employees/new' : undefined}
|
||||
/>
|
||||
</CardContent>
|
||||
@@ -81,12 +83,12 @@ export default function EmployeesPage() {
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Namn</TableHead>
|
||||
<TableHead>Personnummer</TableHead>
|
||||
<TableHead>Typ</TableHead>
|
||||
<TableHead className="text-right">Lön</TableHead>
|
||||
<TableHead className="text-right">Sysselsättningsgrad</TableHead>
|
||||
<TableHead>Skattetabell</TableHead>
|
||||
<TableHead>{t('th_name')}</TableHead>
|
||||
<TableHead>{t('th_personnummer')}</TableHead>
|
||||
<TableHead>{t('th_type')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_salary')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_employment_degree')}</TableHead>
|
||||
<TableHead>{t('th_tax_table')}</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
@@ -101,18 +103,20 @@ export default function EmployeesPage() {
|
||||
{emp.personnummer}
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground">
|
||||
{EMPLOYMENT_LABELS[emp.employment_type] || emp.employment_type}
|
||||
{EMPLOYMENT_LABEL_KEYS[emp.employment_type]
|
||||
? t(EMPLOYMENT_LABEL_KEYS[emp.employment_type])
|
||||
: emp.employment_type}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{emp.salary_type === 'hourly'
|
||||
? emp.hourly_rate ? `${formatCurrency(emp.hourly_rate)}/tim` : '—'
|
||||
? emp.hourly_rate ? `${formatCurrency(emp.hourly_rate)}${t('hourly_suffix')}` : '—'
|
||||
: emp.monthly_salary ? formatCurrency(emp.monthly_salary) : '—'}
|
||||
</TableCell>
|
||||
<TableCell className="text-right tabular-nums">
|
||||
{emp.employment_degree}%
|
||||
</TableCell>
|
||||
<TableCell className="text-muted-foreground tabular-nums">
|
||||
{emp.tax_table_number ? `Tabell ${emp.tax_table_number}, kol ${emp.tax_column}` : '—'}
|
||||
{emp.tax_table_number ? t('tax_table_format', { table: emp.tax_table_number, column: emp.tax_column ?? '' }) : '—'}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -14,12 +15,12 @@ import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import type { SalaryRun } from '@/types'
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
draft: 'Utkast',
|
||||
review: 'Granskning',
|
||||
approved: 'Godkänd',
|
||||
paid: 'Betald',
|
||||
booked: 'Bokförd',
|
||||
const STATUS_LABEL_KEYS: Record<string, string> = {
|
||||
draft: 'status_draft',
|
||||
review: 'status_review',
|
||||
approved: 'status_approved',
|
||||
paid: 'status_paid',
|
||||
booked: 'status_booked',
|
||||
}
|
||||
|
||||
const STATUS_VARIANTS: Record<string, 'default' | 'secondary' | 'success' | 'warning' | 'destructive'> = {
|
||||
@@ -35,6 +36,7 @@ export default function SalaryPage() {
|
||||
const [employeeCount, setEmployeeCount] = useState(0)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const { canWrite } = useCanWrite()
|
||||
const t = useTranslations('salary')
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
@@ -81,20 +83,20 @@ export default function SalaryPage() {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title="Löner"
|
||||
title={t('title')}
|
||||
action={
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/salary/employees">
|
||||
<Users className="mr-2 h-4 w-4" />
|
||||
Anställda
|
||||
{t('employees')}
|
||||
</Link>
|
||||
</Button>
|
||||
{canWrite && (
|
||||
<Button asChild>
|
||||
<Link href="/salary/runs/new">
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Ny lönekörning
|
||||
{t('new_run')}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
@@ -109,7 +111,7 @@ export default function SalaryPage() {
|
||||
<div className="flex items-center gap-3">
|
||||
<Users className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Anställda</p>
|
||||
<p className="text-sm text-muted-foreground">{t('employees')}</p>
|
||||
<p className="text-2xl font-semibold tabular-nums">{employeeCount}</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -120,7 +122,7 @@ export default function SalaryPage() {
|
||||
<div className="flex items-center gap-3">
|
||||
<HandCoins className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Bruttolöner {currentYear}</p>
|
||||
<p className="text-sm text-muted-foreground">{t('gross_year', { year: currentYear })}</p>
|
||||
<p className="text-2xl font-semibold tabular-nums">{formatCurrency(totalGrossYTD)}</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -131,7 +133,7 @@ export default function SalaryPage() {
|
||||
<div className="flex items-center gap-3">
|
||||
<CalendarDays className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Avgifter {currentYear}</p>
|
||||
<p className="text-sm text-muted-foreground">{t('contributions_year', { year: currentYear })}</p>
|
||||
<p className="text-2xl font-semibold tabular-nums">{formatCurrency(totalAvgifterYTD)}</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -142,27 +144,27 @@ export default function SalaryPage() {
|
||||
{/* Recent runs */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Lönekörningar</CardTitle>
|
||||
<CardTitle className="text-base">{t('runs_title')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="p-0">
|
||||
{runs.length === 0 ? (
|
||||
<EmptyState
|
||||
icon={HandCoins}
|
||||
title="Inga lönekörningar ännu"
|
||||
description="Skapa en lönekörning för att räkna ut löner, skatt och arbetsgivaravgifter."
|
||||
actionLabel={canWrite ? 'Skapa lönekörning' : undefined}
|
||||
title={t('empty_runs_title')}
|
||||
description={t('empty_runs_description')}
|
||||
actionLabel={canWrite ? t('create_run') : undefined}
|
||||
actionHref={canWrite ? '/salary/runs/new' : undefined}
|
||||
/>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Period</TableHead>
|
||||
<TableHead>Utbetalningsdag</TableHead>
|
||||
<TableHead className="text-right">Brutto</TableHead>
|
||||
<TableHead className="text-right">Netto</TableHead>
|
||||
<TableHead className="text-right">Avgifter</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>{t('th_period')}</TableHead>
|
||||
<TableHead>{t('th_payday')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_gross')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_net')}</TableHead>
|
||||
<TableHead className="text-right">{t('th_contributions')}</TableHead>
|
||||
<TableHead>{t('th_status')}</TableHead>
|
||||
<TableHead></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
@@ -186,7 +188,7 @@ export default function SalaryPage() {
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={STATUS_VARIANTS[run.status] || 'secondary'}>
|
||||
{STATUS_LABELS[run.status]}
|
||||
{STATUS_LABEL_KEYS[run.status] ? t(STATUS_LABEL_KEYS[run.status]) : run.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Sun, Moon, Monitor, LogOut } from 'lucide-react'
|
||||
import { Sun, Moon, Monitor, LogOut, Languages } from 'lucide-react'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { createClient } from '@/lib/supabase/client'
|
||||
import { SecuritySettings } from '@/components/settings/SecuritySettings'
|
||||
@@ -13,6 +14,8 @@ import { AccountDangerZone } from '@/components/settings/AccountDangerZone'
|
||||
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
||||
import { useSettings } from '@/components/settings/useSettings'
|
||||
import { clearRecaptIdentity } from '@/lib/recapt'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SUPPORTED_LOCALES, type Locale } from '@/i18n/config'
|
||||
|
||||
export default function AccountSettingsPage() {
|
||||
const router = useRouter()
|
||||
@@ -21,6 +24,11 @@ export default function AccountSettingsPage() {
|
||||
const [mounted, setMounted] = useState(false)
|
||||
const hasCalendarExtension = ENABLED_EXTENSION_IDS.has('calendar')
|
||||
const { settings } = useSettings()
|
||||
const { toast } = useToast()
|
||||
const activeLocale = useLocale() as Locale
|
||||
const tCommon = useTranslations('common')
|
||||
const tSettings = useTranslations('settings')
|
||||
const [savingLocale, setSavingLocale] = useState(false)
|
||||
|
||||
useEffect(() => { setMounted(true) }, [])
|
||||
|
||||
@@ -30,20 +38,47 @@ export default function AccountSettingsPage() {
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
async function handleLocaleChange(next: Locale) {
|
||||
if (next === activeLocale || savingLocale) return
|
||||
setSavingLocale(true)
|
||||
try {
|
||||
const res = await fetch('/api/user/locale', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ locale: next }),
|
||||
})
|
||||
if (!res.ok) throw new Error('Could not save')
|
||||
toast({ title: tSettings('language_saved') })
|
||||
router.refresh()
|
||||
} catch {
|
||||
toast({
|
||||
title: tSettings('language_save_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setSavingLocale(false)
|
||||
}
|
||||
}
|
||||
|
||||
const localeLabels: Record<Locale, string> = {
|
||||
sv: tCommon('language_swedish'),
|
||||
en: tCommon('language_english'),
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{/* Appearance */}
|
||||
<section className="space-y-4">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Utseende
|
||||
{tSettings('section_appearance')}
|
||||
</h2>
|
||||
{mounted && (
|
||||
<div className="flex gap-3">
|
||||
{([
|
||||
{ value: 'light', label: 'Ljust', icon: Sun },
|
||||
{ value: 'dark', label: 'Mörkt', icon: Moon },
|
||||
{ value: 'system', label: 'System', icon: Monitor },
|
||||
] as const).map(({ value, label, icon: Icon }) => (
|
||||
{ value: 'light', labelKey: 'theme_light', icon: Sun },
|
||||
{ value: 'dark', labelKey: 'theme_dark', icon: Moon },
|
||||
{ value: 'system', labelKey: 'theme_system', icon: Monitor },
|
||||
] as const).map(({ value, labelKey, icon: Icon }) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
@@ -55,13 +90,41 @@ export default function AccountSettingsPage() {
|
||||
}`}
|
||||
>
|
||||
<Icon className="h-4 w-4 text-muted-foreground" />
|
||||
{label}
|
||||
{tCommon(labelKey)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Language */}
|
||||
<section className="space-y-4 border-t border-border/8 pt-8">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{tSettings('section_language')}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground max-w-md">
|
||||
{tSettings('language_description')}
|
||||
</p>
|
||||
<div className="flex gap-3">
|
||||
{SUPPORTED_LOCALES.map((value) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
onClick={() => handleLocaleChange(value)}
|
||||
disabled={savingLocale}
|
||||
className={`flex items-center gap-2 rounded-lg border-2 px-4 py-2.5 text-sm font-medium transition-colors disabled:opacity-50 ${
|
||||
activeLocale === value
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-border hover:border-primary/40'
|
||||
}`}
|
||||
>
|
||||
<Languages className="h-4 w-4 text-muted-foreground" />
|
||||
{localeLabels[value]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Security */}
|
||||
<div className="border-t border-border/8 pt-8">
|
||||
<SecuritySettings />
|
||||
@@ -78,17 +141,17 @@ export default function AccountSettingsPage() {
|
||||
<section className="border-t border-border/8 pt-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Kontoinställningar</CardTitle>
|
||||
<CardTitle>{tCommon('account_settings')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-between p-4 border rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium">Logga ut</p>
|
||||
<p className="text-sm text-muted-foreground">Logga ut från ditt konto</p>
|
||||
<p className="font-medium">{tCommon('logout')}</p>
|
||||
<p className="text-sm text-muted-foreground">{tCommon('logout_description')}</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={handleLogout}>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Logga ut
|
||||
{tCommon('logout')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -1,20 +1,18 @@
|
||||
import { getTranslations } from 'next-intl/server'
|
||||
import { BackupDownloadForm } from '@/components/settings/BackupDownloadForm'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
|
||||
export default function BackupSettingsPage() {
|
||||
export default async function BackupSettingsPage() {
|
||||
const t = await getTranslations('settings_backup')
|
||||
const { appName } = getBranding()
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<section className="space-y-2">
|
||||
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
|
||||
Säkerhetsbackup
|
||||
{t('heading')}
|
||||
</h2>
|
||||
<p className="text-sm text-muted-foreground max-w-prose">
|
||||
Ladda ner en egen kopia av all räkenskapsinformation — SIE-filer, kvitton,
|
||||
underlag och behandlingshistorik — i en enda ZIP-fil. Säkerhetsbackupen är din
|
||||
egen kopia för trygghet och portabilitet. {appName.toLowerCase()} arkiverar all
|
||||
räkenskapsinformation i minst 7 år enligt BFL 7 kap. 2 §, så din backup ersätter
|
||||
inte vårt lagkrav — den kompletterar det.
|
||||
{t('intro', { appName: appName.toLowerCase() })}
|
||||
</p>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useSearchParams, useRouter } from 'next/navigation'
|
||||
import Link from 'next/link'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
@@ -13,6 +14,7 @@ import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-exten
|
||||
const BankingPanel = getSettingsPanel('enable-banking')
|
||||
|
||||
export default function BankingSettingsPage() {
|
||||
const t = useTranslations('settings_banking')
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
@@ -42,8 +44,8 @@ export default function BankingSettingsPage() {
|
||||
|
||||
if (connectionId) {
|
||||
toast({
|
||||
title: 'Synkroniserar transaktioner...',
|
||||
description: 'Hämtar transaktioner från din bank i bakgrunden.',
|
||||
title: t('sync_start_title'),
|
||||
description: t('sync_start_description'),
|
||||
})
|
||||
const controller = new AbortController()
|
||||
abortControllerRef.current = controller
|
||||
@@ -62,8 +64,8 @@ export default function BankingSettingsPage() {
|
||||
if (res.ok) {
|
||||
if (!unmountedRef.current) {
|
||||
toast({
|
||||
title: 'Bank ansluten!',
|
||||
description: `${data.imported ?? 0} transaktioner importerade`,
|
||||
title: t('sync_success_title'),
|
||||
description: t('sync_success_description', { count: data.imported ?? 0 }),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
@@ -74,13 +76,13 @@ export default function BankingSettingsPage() {
|
||||
if (unmountedRef.current) return
|
||||
if (controller.signal.aborted) {
|
||||
toast({
|
||||
title: 'Synkronisering tog för lång tid',
|
||||
description: 'Transaktionerna hämtas i bakgrunden. Ladda om sidan om en stund.',
|
||||
title: t('sync_timeout_title'),
|
||||
description: t('sync_timeout_description'),
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: 'Synkronisering misslyckades',
|
||||
description: err instanceof Error ? err.message : 'Kunde inte hämta transaktioner',
|
||||
title: t('sync_failed_title'),
|
||||
description: err instanceof Error ? err.message : t('sync_failed_default'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
@@ -88,8 +90,8 @@ export default function BankingSettingsPage() {
|
||||
})()
|
||||
} else {
|
||||
toast({
|
||||
title: 'Bank ansluten!',
|
||||
description: 'Din bank är nu kopplad.',
|
||||
title: t('sync_success_title'),
|
||||
description: t('sync_success_no_id_description'),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -100,7 +102,7 @@ export default function BankingSettingsPage() {
|
||||
const bankName = searchParams.get('bank_name')
|
||||
const errorCode = searchParams.get('bank_error_code')
|
||||
toast({
|
||||
title: 'Anslutning misslyckades',
|
||||
title: t('connect_failed_title'),
|
||||
description: errorMsg,
|
||||
variant: 'destructive',
|
||||
})
|
||||
@@ -109,7 +111,7 @@ export default function BankingSettingsPage() {
|
||||
if (errorCode === 'access_denied') setIsAccessDenied(true)
|
||||
router.replace('/settings/banking')
|
||||
}
|
||||
}, [searchParams, router, toast])
|
||||
}, [searchParams, router, toast, t])
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
@@ -120,11 +122,11 @@ export default function BankingSettingsPage() {
|
||||
<p className="text-sm font-medium text-destructive">{bankConnectionError}</p>
|
||||
{isAccessDenied && failedBankName && (
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
{failedBankName} nekade åtkomst. Om du använder ett privatkonto kan du prova att ansluta med kontotypen "Privatkonto" i bankväljaren nedan.
|
||||
{t('access_denied_hint', { bankName: failedBankName })}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Du kan också <Link href="/import?mode=bank" className="underline hover:text-foreground">importera transaktioner via bankfil</Link> istället.
|
||||
{t('import_fallback_text')}<Link href="/import?mode=bank" className="underline hover:text-foreground">{t('import_fallback_link')}</Link>{t('import_fallback_suffix')}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
@@ -134,7 +136,7 @@ export default function BankingSettingsPage() {
|
||||
setIsAccessDenied(false)
|
||||
}}
|
||||
className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground"
|
||||
aria-label="Stäng"
|
||||
aria-label={t('dismiss_aria')}
|
||||
>
|
||||
<span className="text-lg leading-none">×</span>
|
||||
</button>
|
||||
@@ -147,14 +149,14 @@ export default function BankingSettingsPage() {
|
||||
<Card>
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<CreditCard className="h-10 w-10 text-muted-foreground/40 mb-4" />
|
||||
<p className="font-medium mb-1">Bankintegration (PSD2) är inte aktiverad</p>
|
||||
<p className="font-medium mb-1">{t('not_enabled_title')}</p>
|
||||
<p className="text-sm text-muted-foreground mb-4 max-w-md">
|
||||
Aktivera tillägget Enable Banking för att koppla ditt bankkonto och automatiskt hämta transaktioner.
|
||||
{t('not_enabled_description')}
|
||||
</p>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/extensions">
|
||||
<ExternalLink className="mr-2 h-4 w-4" />
|
||||
Gå till Tillägg
|
||||
{t('go_to_extensions')}
|
||||
</Link>
|
||||
</Button>
|
||||
</CardContent>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user