Bug/resend and invoices (#1192)

* fix(invoices): anchor the PDF logo to the top-left of its header cell

The logo box is always the full 240x80pt reserved area (any larger logo is
clamped to exactly that), so objectFit: 'contain' placed the image inside it
with the default 50% 50% centering. A wide banner logo fills the width and
lands on the left margin, but a near-square logo scaled down to the 80pt
height cap is only ~117pt wide and got pushed ~60pt in from the margin, which
reads as a misaligned logo and forced companies to reshape their artwork.

Anchor the image top-left so every aspect ratio starts at the margin.

Covered by a test that renders the real PDF and reads the image placement
matrix out of the content stream, for both a wide and a near-square logo.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(invoices): show the real delivery outcome in the send history

"Skickad" only meant the email provider accepted the message, so a bounced
invoice looked identical to one that arrived. Resend reports the outcome
asynchronously; that report now lands on the delivery row and drives the
history: green is reserved for a confirmed delivery, bounce/blocked reads
red, delayed and spam-marked read amber, and an accepted-but-unconfirmed
send is neutral instead of falsely green.

The report arrives on a signed webhook and may only touch the three new
provider status columns of an already sent, unredacted row: the WORM trigger
proves nothing else changed, and a lower ranked or older report can never
downgrade an observed failure. The provider reason text can quote the failing
address, so it is masked on read and cleared by the daily PII redaction job.

Timestamps also formatted in Europe/Stockholm instead of falling back to the
runtime zone, which rendered a 14:05 send as 12:05 on Vercel.

Delivery reports are per message, never per recipient: Resend sends one event
for the whole message, so splitting a send per recipient would be the only way
to get finer granularity, at the cost of CC.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(stripe): make the integration feed-only

Stripe sync now only imports balance transactions into the transactions
inbox, like any bank feed; nothing auto-books. The event/settlement sync
(lib/sync.ts, lib/payouts.ts) stays in the repo but is no longer wired to
any route or cron: the 15-min sync cron is removed from vercel.json.
Payment links on invoice send are unchanged; their payments arrive as
feed rows and are matched manually.

- /sync runs only syncStripeBalanceTransactions; response is { success,
  transactions }
- connecting via OAuth enables the nightly feed by default (toggle stays
  as opt-out)
- panel: needs-review section and plumbing removed, copy rewritten to
  transactions-first (sv + en), toast reports fetched/imported/linked
  and calls out an empty result instead of silent all-zeros

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(api): return the article currency from the v1 article list

The dashboard, importer, export and MCP article surfaces all learned to
carry a non-SEK article price (#1166, #1183, #1184), but the v1
projection still omitted currency. An API or agent caller therefore read
price_excl_vat with nothing marking it as EUR and would copy the number
straight onto a SEK invoice line, at a nine-to-one error.

Adds currency to the projection, the response shape and the example, plus
a pitfall stating the price is not always SEK and that this endpoint does
no FX conversion.

Additive field only; no migration (articles.currency already exists).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat(settings): replace the settings modal with a routed panel sheet

Settings now renders as a sheet that fills the main panel, sliding up over the
page the user came from and back down on close, with the sidebar and frame left
visible and usable. Behind it sits one shared master-detail surface: underline
search across every section and subsection, the grouped section rail, and the
active section as a direct-editing accordion. All 11 sections are decomposed
into subsections, and the legacy *SettingsContent components compose the same
pieces so the stacked and accordion layouts cannot drift.

The sheet is the only presentation, on every entry path. The intercepting route
handles in-app navigation and closes by popping the history entry, landing back
on the page underneath. @settingsModal/default.tsx handles cold loads (refresh,
deep link, new tab), where interception never fires; nothing is mounted
underneath there, so it closes to the dashboard. Both branch on one shared
predicate, isSheetSection, together with the settings layout, which must render
nothing for those sections or the surface would stack twice behind the sheet
and run every section's fetches twice.

Closing is deliberate rather than incidental: the X, Esc, or navigating away.
The dialog is non-modal so the sidebar's account popover and company switcher
keep working with settings up, and an outside click no longer dismisses it.
Sections land fully collapsed, and the scroll position of the page behind
survives opening and closing the sheet.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* feat: enhance article management and settings UI

- Add PATCH test for toggling article active state without other fields.
- Remove unused MessageCircle icon from DashboardContent.
- Refactor AccountingFrameworkForm to use SettingsFieldRow for better help text display.
- Update CompanyInfoForm, DimensionsToggle, and various settings forms to replace description with help text.
- Remove redundant headings and intros in several settings components to streamline UI.
- Improve help text for various settings in English and Swedish translations.
- Update structured error messages for better clarity on article deletion.

* refactor(ArticleDetailPage): remove unused imports and duplicate state variable

* fix(settings): own deep-linked settings routes by route list, not nav visibility

Review fixes from the settings panel sheet work:
* isSheetSection reads the full settings route list so a hidden-but-deep-linked
  section (assistant before BankID, banking in sandbox, api without MCP) is
  claimed by the sheet instead of rendering the legacy shell around an empty panel
* keep 503 on the Resend delivery webhook when the signing secret is unset, with
  a test pinning the behaviour
* stripe callback route test coverage

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* refactor: update salary, tax, and templates settings components

- Refactored SalarySettingsContent to use a form wrapper and improved payment settings UI.
- Enhanced TaxSettingsContent with new signals for EU sales, KU obligations, and ROT/RUT deductions.
- Updated TemplatesSettingsContent to remove legacy comments and improve readability.
- Simplified navigation items by removing unnecessary constants and directly using hrefs.
- Cleaned up translation files by removing deprecated keys and adding new descriptions for clarity.

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Mattsson
2026-07-25 22:56:17 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent f07a34c51b
commit d54b43f80f
89 changed files with 6399 additions and 4682 deletions
+21 -5
View File
@@ -3,6 +3,7 @@
Classification: Confidential
Date: 2026-07-22
Updated: 2026-07-24 (provider delivery outcome)
Owner: Accounted controller
Status: Screening completed
@@ -19,9 +20,19 @@ and legal obligations under Article 6(1)(c) and BFL 7 kap.
The exact payload is needed server-side to resolve delivery disputes and retain
the sent accounting document. It is not necessary in the routine browser list.
The list therefore exposes only status, timestamps, masked recipient domains,
provider name, error code, and an active-company-scoped link to the archived
PDF. Subjects, bodies, full addresses, reply-to addresses, provider message IDs,
BCC recipients, filenames, and checksums are excluded.
provider name, the provider delivery outcome with its masked reason text, error
code, and an active-company-scoped link to the archived PDF. Subjects, bodies,
full addresses, reply-to addresses, provider message IDs, BCC recipients,
filenames, and checksums are excluded.
The provider delivery outcome (`provider_status`, `provider_status_at`,
`provider_status_detail`) is received from the email provider over a signed
webhook after the send. The outcome and its timestamp are delivery metadata.
The reason text is provider-authored and routinely quotes the recipient address
that failed, so it is treated as recipient personal data: local parts are masked
before it leaves the server, the stored text is capped at 500 characters, and it
is cleared by the same daily redaction job as the rest of the delivery PII. No
open or click tracking is enabled, so no recipient behaviour is recorded.
The owner/admin full statutory archive has a different legal and operational
purpose from the routine list, so it intentionally does not apply the list's
@@ -49,8 +60,13 @@ server-generated export.
statutory exports are owner/admin-only server operations. Their exact payload
exception is limited to the downloadable statutory archive purpose described
above and is not reused by the routine history endpoint.
The summary function is defined in migration `20260723003000` and the route
applies domain masking again before returning its allow-listed fields.
The summary function is defined in migration `20260724160000` and the route
applies domain masking again before returning its allow-listed fields,
including inside the provider reason text.
- Forged delivery outcome: the provider webhook is Svix-signature verified
before anything is written, and the applying function is service-role only.
It matches on the provider's own message identifier, may only touch an
already sent, unredacted row, and can never downgrade an observed failure.
- Forged delivery evidence: authenticated PostgREST INSERT and UPDATE access is
removed. Server-only functions bind reservations and state transitions to a
verified writable company member. Payload-free crashed reservations may be
+2
View File
@@ -52,6 +52,8 @@ processing_activities:
- exact_sent_pdf_worm_protection
- metadata_only_immutable_audit_log
- daily_post_retention_pii_redaction
- signed_provider_delivery_webhook_only
- masked_recipient_addresses_in_provider_reason_text
- id: customer.private_identity
name: Personnummer för privatkund
+8
View File
File diff suppressed because one or more lines are too long
+17 -11
View File
@@ -57,8 +57,8 @@ export default function ArticleDetailPage({
const [isLoading, setIsLoading] = useState(true)
const [isEditOpen, setIsEditOpen] = useState(false)
const [isUpdating, setIsUpdating] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [isTogglingActive, setIsTogglingActive] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const { dialogProps: confirmDialogProps, confirm: confirmAction } = useDestructiveConfirm()
useEffect(() => {
@@ -131,17 +131,21 @@ export default function ArticleDetailPage({
}
}
// Soft retire/restore: the only path for articles already used on invoices,
// where hard delete is refused (ARTICLE_IN_USE) to keep invoice history.
// Soft deactivation is the answer for an article that has already been used
// on an invoice: the delete path refuses those (ARTICLE_IN_USE), while
// active=false hides it from the invoice picker, the export and the MCP
// listing without touching invoice history. Reactivation is not destructive,
// so only the deactivate direction confirms.
async function handleToggleActive() {
if (!article) return
const deactivating = article.active
if (deactivating) {
const nextActive = !article.active
if (!nextActive) {
const ok = await confirmAction({
title: t('deactivate_confirm_title', { name: article.name }),
description: t('deactivate_confirm_description'),
confirmLabel: t('deactivate_confirm_label'),
variant: 'destructive',
variant: 'warning',
})
if (!ok) return
}
@@ -151,18 +155,19 @@ export default function ArticleDetailPage({
const response = await fetch(`/api/articles/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ active: !article.active }),
body: JSON.stringify({ active: nextActive }),
})
await throwOnStructuredError(response)
const { data } = (await throwOnStructuredError(response)) as { data: Article }
setArticle(data)
toast({
title: deactivating ? t('deactivated_title') : t('activated_title'),
title: nextActive ? t('activated_title') : t('deactivated_title'),
description: article.name,
})
fetchArticle()
} catch (err) {
const body = (err as { body?: unknown }).body
toast({
title: deactivating ? t('deactivate_failed_title') : t('activate_failed_title'),
title: nextActive ? t('activate_failed_title') : t('deactivate_failed_title'),
description: getErrorMessage(body ?? err, { context: 'article', locale: errorLocale }),
variant: 'destructive',
})
@@ -264,6 +269,7 @@ export default function ArticleDetailPage({
variant="outline"
size="sm"
onClick={handleToggleActive}
className="min-h-10"
disabled={isTogglingActive || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
+21
View File
@@ -63,6 +63,27 @@ describe('GET/PATCH/DELETE /api/articles/[id]', () => {
expect(body.data.price_excl_vat).toBe(1500)
})
// The article detail page's Inaktivera/Aktivera button sends nothing but the
// flag, so an active-only body must be a valid sparse update on its own.
it('PATCH toggles active on its own without any other field', async () => {
enqueue({ data: { id: 'a1', name: 'Konsulttimme', active: false } })
const request = createMockRequest('/api/articles/a1', {
method: 'PATCH',
body: { active: false },
})
const response = await PATCH(request, createMockRouteParams({ id: 'a1' }))
const { status, body } = await parseJsonResponse<{ data: { active: boolean } }>(response)
expect(status).toBe(200)
expect(body.data.active).toBe(false)
// Only the articles update: no revenue-account lookup is triggered by a
// body that carries nothing but the flag.
expect(supabase.from).toHaveBeenCalledTimes(1)
expect(supabase.from).toHaveBeenCalledWith('articles')
})
it('PATCH answers ACCOUNTS_NOT_IN_CHART for a BAS class-3 account missing from the chart', async () => {
// chart_of_accounts lookup: no row, but 3999 is a known BAS class-3
// account → activatable via the activate-and-retry dialog flow.
@@ -0,0 +1,149 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { eventBus } from '@/lib/events/bus'
// Mock dependencies: factory must not reference outer variables
const mockExchangeCodeForAccount = vi.fn()
const mockFetchAccountDisplayName = vi.fn()
vi.mock('@/extensions/general/stripe/lib/connect', () => ({
exchangeCodeForAccount: (...args: unknown[]) => mockExchangeCodeForAccount(...args),
fetchAccountDisplayName: (...args: unknown[]) => mockFetchAccountDisplayName(...args),
}))
const { mockFrom } = vi.hoisted(() => ({ mockFrom: vi.fn() }))
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: vi.fn().mockResolvedValue({ from: mockFrom }),
}))
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'http://localhost:3000')
import { GET } from '../route'
const CONNECTION_ID = 'connection-1'
const OAUTH_STATE = 'state-token-1'
function makeRequest(params: Record<string, string>) {
const url = new URL('http://localhost:3000/api/extensions/stripe/callback')
for (const [k, v] of Object.entries(params)) {
url.searchParams.set(k, v)
}
return new Request(url.toString())
}
function mockChain(result: { data?: unknown; error?: unknown }) {
const chain: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'update', 'insert']) {
chain[m] = vi.fn().mockReturnValue(chain)
}
chain.single = vi
.fn()
.mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
// For chains ending without .single() (the insert and the error-path updates)
chain.then = (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
return chain
}
describe('GET /api/extensions/stripe/callback', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
mockExchangeCodeForAccount.mockResolvedValue({
stripeAccountId: 'acct_123',
livemode: false,
})
mockFetchAccountDisplayName.mockResolvedValue('Test Shop')
})
it('activates the connection and turns the transaction feed on by default', async () => {
const findChain = mockChain({
data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' },
})
const replayChain = mockChain({ error: null })
const activateChain = mockChain({
data: {
id: CONNECTION_ID,
company_id: 'company-1',
user_id: 'user-1',
stripe_account_id: 'acct_123',
livemode: false,
},
})
mockFrom
.mockReturnValueOnce(findChain)
.mockReturnValueOnce(replayChain)
.mockReturnValueOnce(activateChain)
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.status).toBe(307)
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_connected=true',
)
// Feed-only product: a completed OAuth must leave the nightly sync armed,
// otherwise a connected account silently ingests nothing.
const activatePayload = (activateChain.update as ReturnType<typeof vi.fn>).mock.calls[0][0]
expect(activatePayload).toMatchObject({
stripe_account_id: 'acct_123',
livemode: false,
display_name: 'Test Shop',
status: 'active',
oauth_state: null,
transaction_sync_enabled: true,
})
})
it('redirects with an error and never activates when the state is unknown', async () => {
mockFrom.mockReturnValueOnce(mockChain({ data: null, error: { code: 'PGRST116' } }))
const response = await GET(makeRequest({ code: 'ac_123', state: 'unknown-state' }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=invalid_state',
)
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
})
it('redirects with an error when the authorization code was already used', async () => {
mockFrom
.mockReturnValueOnce(
mockChain({ data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' } }),
)
.mockReturnValueOnce(mockChain({ error: { code: '23505' } }))
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=invalid_state',
)
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
})
it('reports the conflict when the Stripe account is already connected', async () => {
mockFrom
.mockReturnValueOnce(
mockChain({ data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' } }),
)
.mockReturnValueOnce(mockChain({ error: null }))
.mockReturnValueOnce(mockChain({ data: null, error: { code: '23505', message: 'dup' } }))
.mockReturnValueOnce(mockChain({ error: null }))
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=account_already_connected',
)
})
it('redirects without touching Stripe when parameters are missing', async () => {
const response = await GET(makeRequest({ state: OAUTH_STATE }))
expect(response.headers.get('location')).toBe(
'http://localhost:3000/import?mode=stripe&stripe_error=missing_parameters',
)
expect(mockFrom).not.toHaveBeenCalled()
})
})
@@ -118,6 +118,10 @@ export async function GET(request: Request) {
connected_at: new Date().toISOString(),
error_message: null,
oauth_state: null, // Clear to prevent replay
// Feed-only product: connecting Stripe means fetching its
// transactions, so the nightly feed starts on by default. The panel
// toggle remains as the opt-out.
transaction_sync_enabled: true,
})
.eq('id', pendingConnection.id)
.select('id, company_id, user_id, stripe_account_id, livemode')
@@ -79,6 +79,9 @@ describe('GET /api/invoices/[id]/deliveries', () => {
body_text: 'Hej! Här kommer fakturan.',
provider: 'resend',
provider_message_id: 'provider-1',
provider_status: 'delivered',
provider_status_at: '2026-07-22T10:30:04.000Z',
provider_status_detail: null,
error_code: null,
document_attachment_id: 'document-1',
attachment_filename: 'faktura-f-1001.pdf',
@@ -105,6 +108,9 @@ describe('GET /api/invoices/[id]/deliveries', () => {
to_addresses: ['***@example.com'],
cc_addresses: ['***@example.com'],
provider: 'resend',
provider_status: 'delivered',
provider_status_at: '2026-07-22T10:30:04.000Z',
provider_status_detail: null,
error_code: null,
document_attachment_id: 'document-1',
attachment_filename: 'faktura-f-1001.pdf',
@@ -127,4 +133,85 @@ describe('GET /api/invoices/[id]/deliveries', () => {
p_invoice_id: INVOICE_ID,
})
})
it('masks recipient addresses quoted inside the provider reason text', async () => {
enqueue({ data: { id: INVOICE_ID }, error: null })
enqueue({
data: [{
id: 'delivery-2',
channel: 'email',
status: 'sent',
to_addresses: ['[email protected]'],
cc_addresses: [],
provider: 'resend',
provider_status: 'bounced',
provider_status_at: '2026-07-22T10:31:00.000Z',
provider_status_detail:
'550 5.1.1 <[email protected]>: Recipient address rejected Permanent/General',
error_code: null,
document_attachment_id: 'document-1',
attachment_filename: 'faktura-f-1001.pdf',
sent_at: '2026-07-22T10:30:00.000Z',
failed_at: null,
created_at: '2026-07-22T10:29:59.000Z',
}],
error: null,
})
const response = await GET(
createMockRequest(`/api/invoices/${INVOICE_ID}/deliveries`),
createMockRouteParams({ id: INVOICE_ID }),
)
const { body } = await parseJsonResponse<{ data: Array<Record<string, unknown>> }>(response)
expect(body.data[0].provider_status).toBe('bounced')
expect(body.data[0].provider_status_detail).toBe(
'550 5.1.1 <***@example.com>: Recipient address rejected Permanent/General',
)
})
// An ASCII allow-list stops at the first character it cannot spell and leaks
// the head of the address ("anna.bergstr" out of anna.bergström@). Each of
// these forms is a real local part a provider can quote back at us.
it.each([
['non-ASCII local part', 'anna.bergströ[email protected] avvisad', '***@example.se avvisad'],
['quoted local part', '"anna berg"@example.com bounced', '***@example.com bounced'],
['apostrophe in local part', "o'[email protected] hard bounce", '***@example.se hard bounce'],
[
'several addresses in one reason',
'delivered to [email protected] but not [email protected]',
'delivered to ***@example.se but not ***@example.com',
],
])('masks the %s in the provider reason text', async (_label, detail, expected) => {
enqueue({ data: { id: INVOICE_ID }, error: null })
enqueue({
data: [{
id: 'delivery-3',
channel: 'email',
status: 'sent',
to_addresses: ['[email protected]'],
cc_addresses: [],
provider: 'resend',
provider_status: 'bounced',
provider_status_at: '2026-07-22T10:31:00.000Z',
provider_status_detail: detail,
error_code: null,
document_attachment_id: null,
attachment_filename: null,
sent_at: '2026-07-22T10:30:00.000Z',
failed_at: null,
created_at: '2026-07-22T10:29:59.000Z',
}],
error: null,
})
const response = await GET(
createMockRequest(`/api/invoices/${INVOICE_ID}/deliveries`),
createMockRouteParams({ id: INVOICE_ID }),
)
const { body } = await parseJsonResponse<{ data: Array<Record<string, unknown>> }>(response)
expect(body.data[0].provider_status_detail).toBe(expected)
expect(body.data[0].provider_status_detail).not.toContain('anna')
})
})
+37 -2
View File
@@ -2,7 +2,11 @@ import { NextResponse } from 'next/server'
import { z } from 'zod'
import { withRouteContext } from '@/lib/api/with-route-context'
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
import type { InvoiceDeliveryChannel, InvoiceDeliveryStatus } from '@/types'
import type {
InvoiceDeliveryChannel,
InvoiceDeliveryProviderStatus,
InvoiceDeliveryStatus,
} from '@/types'
interface InvoiceDeliverySummaryRow {
id: string
@@ -11,6 +15,9 @@ interface InvoiceDeliverySummaryRow {
to_addresses: string[]
cc_addresses: string[]
provider: string | null
provider_status: InvoiceDeliveryProviderStatus | null
provider_status_at: string | null
provider_status_detail: string | null
error_code: string | null
document_attachment_id: string | null
attachment_filename: string | null
@@ -35,8 +42,12 @@ interface MaskedInvoiceDeliverySummaryRow
* addresses stay server-side. The attachment filename passes through: it is
* derived from data the invoice already exposes to every company member. The
* database allow-list and masking boundary is defined by
* list_invoice_delivery_summaries in migration 20260723150000; this route
* list_invoice_delivery_summaries in migration 20260724160000; this route
* masks returned addresses again as defense in depth.
*
* The provider delivery outcome is message-level, never per recipient: the
* provider reports one result for the whole send, and its reason text can
* quote the failing address, so that text is masked the same way.
*/
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
'invoice.deliveries.list',
@@ -79,6 +90,9 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
to_addresses: delivery.to_addresses.map(maskRecipientDomain),
cc_addresses: delivery.cc_addresses.map(maskRecipientDomain),
provider: delivery.provider,
provider_status: delivery.provider_status,
provider_status_at: delivery.provider_status_at,
provider_status_detail: maskAddressesInText(delivery.provider_status_detail),
error_code: delivery.error_code,
document_attachment_id: delivery.document_attachment_id,
attachment_filename: delivery.attachment_filename,
@@ -94,6 +108,27 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
},
)
/**
* Provider reason texts routinely quote the address that failed
* ("550 5.1.1 <[email protected]>: user unknown"). Keep the diagnostic value,
* drop the local part, matching how the recipient list itself is masked.
*
* The local part is matched by exclusion, not by an allow-list of ASCII mail
* characters: an allow-list stops at the first character it does not know, so
* it leaks the head of every address it cannot spell. `anna.bergström@` would
* mask only the `m`, and a quoted local part ("anna berg"@example.com) would
* not match at all. Anything up to the delimiters that genuinely cannot sit
* inside an address (whitespace, the angle brackets and punctuation providers
* wrap addresses in) is treated as local part, so over-masking is the failure
* mode rather than a partial disclosure.
*/
const ADDRESS_LOCAL_PART = /"[^"]*"@|[^\s<>()[\],;:"@]+@/gu
function maskAddressesInText(text: string | null): string | null {
if (!text) return null
return text.replace(ADDRESS_LOCAL_PART, '***@')
}
function maskRecipientDomain(address: string): MaskedRecipientAddress {
const separator = address.lastIndexOf('@')
if (separator <= 0 || separator === address.length - 1) {
@@ -34,6 +34,7 @@ const SAMPLE_ARTICLE = {
type: 'tjanst',
unit: 'tim',
price_excl_vat: 850,
currency: 'SEK',
vat_rate: 25,
revenue_account: null,
cost_price: null,
@@ -111,6 +112,26 @@ describe('GET /api/v1/companies/:companyId/articles', () => {
expect(client.eqCalls).toContainEqual(['articles', 'active', true])
})
it('exposes the article currency so a caller can tell a non-SEK price apart', async () => {
// price_excl_vat alone is ambiguous: without currency an agent copies a EUR
// price onto a SEK invoice line with no FX conversion.
const client = makeSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
articles: { data: [{ ...SAMPLE_ARTICLE, price_excl_vat: 95, currency: 'EUR' }], error: null },
})
mockServiceClient.mockReturnValue(client)
const res = await listArticles(
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/articles`),
routeParams,
)
expect(res.status).toBe(200)
const body = await res.json()
expect(body.data.articles[0].currency).toBe('EUR')
expect(body.data.articles[0].price_excl_vat).toBe(95)
})
it('includes inactive articles with ?include_inactive=true', async () => {
const client = makeSupabase({
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
@@ -23,6 +23,7 @@ const ArticleShape = z.object({
type: z.enum(['vara', 'tjanst']),
unit: z.string(),
price_excl_vat: z.number(),
currency: z.string(),
vat_rate: z.number(),
revenue_account: z.string().nullable(),
cost_price: z.number().nullable(),
@@ -36,7 +37,7 @@ const ArticleShape = z.object({
// Explicit projection: excludes user_id, company_id (internal scoping).
const ARTICLE_COLUMNS =
'id, article_number, name, name_en, type, unit, price_excl_vat, vat_rate, revenue_account, cost_price, ean, housework_type, notes, active, created_at, updated_at'
'id, article_number, name, name_en, type, unit, price_excl_vat, currency, vat_rate, revenue_account, cost_price, ean, housework_type, notes, active, created_at, updated_at'
registerEndpoint({
operation: 'articles.list',
@@ -52,6 +53,7 @@ registerEndpoint({
pitfalls: [
'Linking article_id does NOT auto-fill the invoice line: send description, unit_price, vat_rate etc. explicitly on the item (copy them from this response).',
'price_excl_vat always excludes VAT.',
'price_excl_vat is denominated in the article\'s own currency, which is NOT always SEK. Check currency before copying the price onto an invoice line: the invoice carries a single currency for all its lines and there is no FX conversion here.',
'housework_type is an arbetstypskod hint (e.g. BYGG, STAD); the invoice line still needs deduction_type + labor_hours + work_type set explicitly for ROT/RUT.',
'Inactive articles (active=false) are hidden by default but remain linkable for historical reads.',
],
@@ -67,6 +69,7 @@ registerEndpoint({
type: 'tjanst',
unit: 'tim',
price_excl_vat: 850,
currency: 'SEK',
vat_rate: 25,
revenue_account: null,
cost_price: null,
+4 -1
View File
@@ -14,6 +14,7 @@ import { RecaptHideWidget } from "@/components/RecaptHideWidget";
import { ScrollbarReveal } from "@/components/ScrollbarReveal";
import { ensureInitialized } from "@/lib/init";
import { getBranding } from "@/lib/branding/service";
import { APP_TIME_ZONE } from "@/i18n/config";
import "./globals.css";
// Load extensions before metadata/viewport functions read the branding service.
@@ -81,7 +82,9 @@ export default async function RootLayout({
<body
className="antialiased"
>
<NextIntlClientProvider locale={locale} messages={messages}>
{/* timeZone is passed explicitly: client components must format in the
same zone the server rendered with, or timestamps shift on hydration. */}
<NextIntlClientProvider locale={locale} messages={messages} timeZone={APP_TIME_ZONE}>
<ThemeProvider
attribute="class"
defaultTheme="light"
+1 -4
View File
@@ -12,7 +12,7 @@ import AttGoraSection from '@/components/dashboard/AttGoraSection'
import ResumePane from '@/components/dashboard/ResumePane'
import BackupHealthBanner from '@/components/dashboard/BackupHealthBanner'
import { SkatteverketPromoCard } from '@/components/dashboard/SkatteverketPromoCard'
import { ArrowRight, MessageCircle } from 'lucide-react'
import { ArrowRight } from 'lucide-react'
import type { InitialSetupState, OnboardingProgress } from '@/types'
import type { SuggestedMatch, WorklistCounts } from '@/lib/worklist/types'
import type { ResumeItem } from '@/lib/worklist/resume'
@@ -111,9 +111,6 @@ export default function DashboardContent({
<Link href={hasAi ? '/onboarding/agent' : '/settings/billing'} className="block group">
<Card className="transition-colors hover:border-primary/50">
<CardContent className="p-6 flex items-center gap-4">
<div className="flex-shrink-0 h-10 w-10 rounded-lg flex items-center justify-center bg-foreground text-background">
<MessageCircle className="h-5 w-5" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<p className="font-display text-xl leading-tight">Bygg din bokföringsassistent</p>
+67 -6
View File
@@ -6,7 +6,7 @@ import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import type { InvoiceDelivery } from '@/types'
import type { InvoiceDelivery, InvoiceDeliveryProviderStatus } from '@/types'
export type InvoiceDeliveryView = Pick<
InvoiceDelivery,
@@ -15,6 +15,9 @@ export type InvoiceDeliveryView = Pick<
| 'to_addresses'
| 'cc_addresses'
| 'provider'
| 'provider_status'
| 'provider_status_at'
| 'provider_status_detail'
| 'error_code'
| 'document_attachment_id'
| 'attachment_filename'
@@ -30,12 +33,37 @@ interface InvoiceDeliveryHistoryProps {
showLegacyEmptyState: boolean
}
const statusVariant = {
/**
* What the row actually says happened. The send status alone stops at
* "handed to the provider", which is why an accepted-but-bounced invoice used
* to read as a plain success. When the provider has reported back, its
* outcome is what the row shows.
*/
type DeliveryOutcome =
| 'pending'
| 'sent'
| 'failed'
| 'marked_sent'
| InvoiceDeliveryProviderStatus
function outcomeOf(delivery: InvoiceDeliveryView): DeliveryOutcome {
if (delivery.status === 'sent' && delivery.provider_status) return delivery.provider_status
return delivery.status
}
// Green is reserved for a confirmed arrival. "Skickad" without a delivery
// report is a neutral, honest in-between state.
const outcomeVariant: Record<DeliveryOutcome, 'secondary' | 'success' | 'warning' | 'destructive' | 'outline'> = {
pending: 'secondary',
sent: 'success',
sent: 'secondary',
delivered: 'success',
delayed: 'warning',
complained: 'warning',
bounced: 'destructive',
failed: 'destructive',
suppressed: 'destructive',
marked_sent: 'outline',
} as const
}
export function InvoiceDeliveryHistory({
deliveries,
@@ -76,6 +104,10 @@ export function InvoiceDeliveryHistory({
{deliveries.map((delivery) => {
const occurredAt = delivery.sent_at || delivery.failed_at || delivery.created_at
const isManual = delivery.channel === 'manual'
const outcome = outcomeOf(delivery)
const isEmailSend = !isManual && delivery.status === 'sent'
const recipientCount =
delivery.to_addresses.length + delivery.cc_addresses.length
return (
<details key={delivery.id} className="group rounded-lg border bg-card">
@@ -91,8 +123,8 @@ export function InvoiceDeliveryHistory({
{formatTimestamp(occurredAt)}
</span>
</span>
<Badge variant={statusVariant[delivery.status]}>
{t(`delivery_status_${delivery.status}`)}
<Badge variant={outcomeVariant[outcome]}>
{t(`delivery_status_${outcome}`)}
</Badge>
</summary>
@@ -115,6 +147,35 @@ export function InvoiceDeliveryHistory({
)}
</dl>
{isEmailSend && (
<div className="rounded-lg border bg-muted/30 p-3">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">
{t('delivery_provider_status_label')}
</span>
<span>{t(`delivery_status_${outcome}`)}</span>
{delivery.provider_status_at && (
<span className="text-xs text-muted-foreground tabular-nums">
{formatTimestamp(delivery.provider_status_at)}
</span>
)}
</div>
<p className="mt-1 text-xs text-muted-foreground">
{t(`delivery_status_explanation_${outcome}`)}
</p>
{delivery.provider_status_detail && (
<p className="mt-2 break-words text-xs text-muted-foreground">
{t('delivery_provider_reason_label')}: {delivery.provider_status_detail}
</p>
)}
{recipientCount > 1 && delivery.provider_status && (
<p className="mt-2 text-xs text-muted-foreground">
{t('delivery_status_whole_send_note')}
</p>
)}
</div>
)}
{delivery.document_attachment_id && (
<Button asChild variant="outline" size="sm" className="max-w-full">
<a
+14 -6
View File
@@ -74,13 +74,21 @@ export function TaxTableStatus({ year, compact = false }: Props) {
)
}
// Flat row presentation (Fönster settings language): muted status line
// with a quiet right-aligned recheck, no box.
return (
<div className="flex items-center justify-between gap-3 rounded-md border bg-muted/30 px-3 py-2">
<div className="flex items-center gap-2 text-sm">
<Icon className={`h-4 w-4 ${iconColor}`} />
<span>{label}</span>
</div>
<Button variant="ghost" size="sm" onClick={check} disabled={loading} aria-label={t('recheck')}>
<div className="flex w-full min-w-0 items-center gap-2">
<Icon className={`h-3.5 w-3.5 shrink-0 ${iconColor}`} />
<span className="min-w-0 text-xs text-muted-foreground">{label}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={check}
disabled={loading}
aria-label={t('recheck')}
className="ml-auto shrink-0"
>
{loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCcw className="h-3.5 w-3.5" />}
</Button>
</div>
+58 -50
View File
@@ -20,6 +20,12 @@ import { RetentionNotice } from '@/components/ui/retention-notice'
import { ExternalLink, Loader2 } from 'lucide-react'
import { SupportLink } from '@/components/ui/support-link'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import {
SettingsDangerZone,
SettingsRow,
SettingsRowEnd,
SettingsRowNote,
} from '@/components/settings/SettingsRows'
interface Blocker {
id: string
@@ -28,6 +34,7 @@ interface Blocker {
export function AccountDangerZone() {
const t = useTranslations('settings_account_danger')
const tRetention = useTranslations('retention_notice')
const router = useRouter()
const [email, setEmail] = useState<string | null>(null)
const [blockers, setBlockers] = useState<Blocker[]>([])
@@ -103,61 +110,62 @@ export function AccountDangerZone() {
return (
<>
<section className="space-y-4 border-t border-border pt-8">
<h2 className="text-sm font-medium uppercase tracking-wider text-destructive">
{t('heading')}
</h2>
<SettingsDangerZone label={t('heading')}>
{/* Owned companies block deletion: functional state, kept visible as
rows (only the first row carries the label and the why-help). */}
{hasBlockers &&
blockers.map((b, i) => (
<SettingsRow
key={b.id}
label={i === 0 ? t('blockers_title') : ''}
help={i === 0 ? t('blockers_description') : undefined}
>
<span className="text-sm">{b.name}</span>
<SettingsRowEnd>
<Button variant="ghost" size="sm" asChild>
<Link href="/settings/company">{t('blockers_manage')}</Link>
</Button>
</SettingsRowEnd>
</SettingsRow>
))}
{hasBlockers && (
<div className="rounded-lg border border-border bg-muted/30 p-4 space-y-3">
<p className="text-sm font-medium">{t('blockers_title')}</p>
<p className="text-sm text-muted-foreground">
{t('blockers_description')}
</p>
<ul className="space-y-2">
{blockers.map((b) => (
<li
key={b.id}
className="flex items-center justify-between rounded-md border border-border bg-background px-3 py-2"
>
<span className="text-sm font-medium">{b.name}</span>
<Button variant="ghost" size="sm" asChild>
<Link href="/settings/company">{t('blockers_manage')}</Link>
</Button>
</li>
))}
</ul>
</div>
)}
<RetentionNotice variant="account" />
<p className="text-sm text-muted-foreground">
{t('support_question')}{' '}
<SupportLink variant="inline" subject={t('support_subject')} />
</p>
<SettingsRow
label={t('delete_button')}
borderless
// The full anonymization/BFL retention copy (incl. the backup link)
// lives behind the "?": the visible row stays one quiet line.
help={<RetentionNotice variant="account" className="border-0 bg-transparent p-0" />}
>
<SettingsRowNote>{tRetention('account_title')}</SettingsRowNote>
<SettingsRowEnd>
<Button variant="ghost" size="sm" asChild>
<Link href="/reports?type=sie">
<ExternalLink className="mr-2 h-3.5 w-3.5" />
{t('export_sie')}
</Link>
</Button>
<button
type="button"
onClick={() => setShowDialog(true)}
disabled={!canDelete}
className="text-sm font-medium text-destructive underline underline-offset-2 transition-colors duration-150 hover:text-destructive/80 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('delete_button')}
</button>
</SettingsRowEnd>
</SettingsRow>
{error && !showDialog && (
<p className="text-sm text-destructive">{error}</p>
<p className="px-1 text-sm text-destructive">{error}</p>
)}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<Button variant="outline" className="w-full sm:w-auto" asChild>
<Link href="/reports?type=sie">
<ExternalLink className="mr-2 h-4 w-4" />
{t('export_sie')}
</Link>
</Button>
<Button
variant="destructive"
className="w-full sm:w-auto"
onClick={() => setShowDialog(true)}
disabled={!canDelete}
>
{t('delete_button')}
</Button>
</div>
</section>
<p className="px-1 pt-3">
<SettingsRowNote>
{t('support_question')}{' '}
<SupportLink variant="inline" subject={t('support_subject')} />
</SettingsRowNote>
</p>
</SettingsDangerZone>
<Dialog
open={showDialog}
+36 -35
View File
@@ -1,15 +1,7 @@
'use client'
import { useState } from 'react'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Dialog,
DialogContent,
@@ -19,6 +11,11 @@ import {
DialogTitle,
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import {
SettingsRow,
SettingsRowNote,
SettingsSelect,
} from '@/components/settings/SettingsRows'
import type { AccountingFramework } from '@/types'
import { Loader2 } from 'lucide-react'
@@ -30,8 +27,9 @@ interface AccountingFrameworkFormProps {
}
/**
* K2/K3 selector for AB. Lives on the bookkeeping settings page. Renders nothing
* for non-AB entities: the parent gates this component by entity_type.
* K2/K3 selector row for AB. Lives in the Grunder group on the bookkeeping
* settings page. Renders nothing for non-AB entities: the parent gates this
* component by entity_type.
*
* UX rules (regulatory area: kept in Swedish):
* - Default is K2 (matches the column default and BFNAR 2016:10 baseline).
@@ -100,33 +98,36 @@ export function AccountingFrameworkForm({ current, onSaved }: AccountingFramewor
}
return (
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Redovisningsregelverk
</h2>
<div className="space-y-2">
<Label htmlFor="accounting_framework">Regelverk</Label>
<Select
<>
<SettingsRow
label="Regelverk"
htmlFor="accounting_framework"
help={
<>
K2 är standard för mindre bolag och innebär förenklade regler. K3 krävs när
bolaget når två av tre tröskelvärden (nettoomsättning &gt; 80 MSEK, tillgångar
&gt; 40 MSEK, eller fler än 50 anställda). K3 ställer högre krav: kassaflödesanalys,
komponentavskrivning på materiella anläggningstillgångar och redovisning av
uppskjuten skatt på obeskattade reserver (79,4 % eget kapital / 20,6 % skuld).
</>
}
>
<SettingsSelect
id="accounting_framework"
value={selected}
onValueChange={handleChange}
onChange={(e) => handleChange(e.target.value)}
// Saves via its own PATCH; the row sits inside the page's
// SettingsFormWrapper form, so keep the wrapper's dirty tracking
// (onInput on the form) from reacting to this select. No `name`
// either, so the wrapper's FormData never picks it up.
onInput={(e) => e.stopPropagation()}
disabled={saving}
>
<SelectTrigger id="accounting_framework" className="w-full max-w-sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="k2">K2 (BFNAR 2016:10): mindre företag</SelectItem>
<SelectItem value="k3">K3 (BFNAR 2012:1): större företag</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
K2 är standard för mindre bolag och innebär förenklade regler. K3 krävs när
bolaget når två av tre tröskelvärden (nettoomsättning &gt; 80 MSEK, tillgångar
&gt; 40 MSEK, eller fler än 50 anställda). K3 ställer högre krav: kassaflödesanalys,
komponentavskrivning på materiella anläggningstillgångar och redovisning av
uppskjuten skatt på obeskattade reserver (79,4 % eget kapital / 20,6 % skuld).
</p>
</div>
<option value="k2">K2 (BFNAR 2016:10): mindre företag</option>
<option value="k3">K3 (BFNAR 2012:1): större företag</option>
</SettingsSelect>
{saving && <SettingsRowNote>Sparar…</SettingsRowNote>}
</SettingsRow>
<Dialog
open={pending !== null}
@@ -174,6 +175,6 @@ export function AccountingFrameworkForm({ current, onSaved }: AccountingFramewor
</DialogFooter>
</DialogContent>
</Dialog>
</section>
</>
)
}
+204 -196
View File
@@ -2,16 +2,24 @@
import { useCallback, useEffect, useMemo, useState } from 'react'
import { Brain, Loader2, Pin, PinOff, Pencil, Plus, RotateCcw, Trash2, X } from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { EmptyState } from '@/components/ui/empty-state'
import { Skeleton } from '@/components/ui/skeleton'
import { useToast } from '@/components/ui/use-toast'
import {
SettingsGroup,
SettingsReveal,
SettingsRow,
SettingsRowEnd,
SettingsRowNote,
SettingsSeg,
SettingsSelect,
SettingsTextarea,
} from '@/components/settings/SettingsRows'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { formatDateLong } from '@/lib/utils'
import { cn, formatDateLong } from '@/lib/utils'
type Kind = 'fact' | 'preference' | 'pattern' | 'correction'
type Source = 'composer' | 'user_taught' | 'agent_learned' | 'derived'
@@ -53,7 +61,7 @@ const KIND_FILTER: { value: 'all' | Kind; label: string }[] = [
]
// The API returns errors either as a plain string (legacy/validation) or as
// the canonical { code, message } envelope — extract something renderable.
// the canonical { code, message } envelope; extract something renderable.
function apiErrorText(error: unknown): string | undefined {
if (typeof error === 'string') return error
if (error && typeof error === 'object' && 'message' in error) {
@@ -159,19 +167,31 @@ export function AgentMemoryPanel() {
setEditingId(null)
}
// The view wrapper in AssistantSettingsContent already provides the gap
// under the segmented control, so the group starts flush (pt-0).
return (
<Card>
<CardHeader className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
<div>
<CardTitle className="text-base">Vad min assistent kommer ihåg</CardTitle>
<CardDescription>
Bokföringsassistenten använder dessa anteckningar för att ge dig rätt råd. Fäst det som
alltid ska vara med, redigera fel, eller dölj det som inte längre stämmer.
</CardDescription>
</div>
<SettingsGroup
label="Vad min assistent kommer ihåg"
help={
<>
Bokföringsassistenten använder dessa anteckningar för att ge dig rätt råd. Fäst det som
alltid ska vara med, redigera fel, eller dölj det som inte längre stämmer. Upp till 30
minnen ingår i samtal per tur.
</>
}
className="pt-0 first:pt-0"
>
{/* Toolbar row: kind filter + the add-memory entry point. */}
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-1 py-3">
<SettingsSeg
value={kindFilter}
onChange={setKindFilter}
options={KIND_FILTER}
aria-label="Filtrera minnen"
/>
{canWrite && (
<Button
variant="outline"
variant="ghost"
size="sm"
onClick={() => setShowAdd((v) => !v)}
disabled={adding}
@@ -180,31 +200,32 @@ export function AgentMemoryPanel() {
Lägg till minne
</Button>
)}
</CardHeader>
</div>
<CardContent className="space-y-6">
{showAdd && canWrite && (
<div className="rounded-lg border border-border p-4 space-y-3">
<Textarea
{canWrite && (
<SettingsReveal open={showAdd}>
<div className="space-y-3 py-3">
<SettingsTextarea
value={newContent}
onChange={(e) => setNewContent(e.target.value)}
placeholder="T.ex. Vi använder Stripe för B2C-betalningar; utbetalningar landar på 1930 var måndag."
rows={3}
maxLength={2000}
aria-label="Nytt minne"
className="w-full border-border"
/>
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">Typ</span>
<Select value={newKind} onValueChange={(v) => setNewKind(v as Kind)}>
<SelectTrigger className="h-8 w-[160px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{(Object.keys(KIND_LABEL) as Kind[]).map((k) => (
<SelectItem key={k} value={k}>{KIND_LABEL[k]}</SelectItem>
))}
</SelectContent>
</Select>
<SettingsSelect
value={newKind}
onChange={(e) => setNewKind(e.target.value as Kind)}
aria-label="Typ"
>
{(Object.keys(KIND_LABEL) as Kind[]).map((k) => (
<option key={k} value={k}>{KIND_LABEL[k]}</option>
))}
</SettingsSelect>
</div>
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" onClick={() => { setShowAdd(false); setNewContent('') }}>
@@ -217,194 +238,181 @@ export function AgentMemoryPanel() {
</div>
</div>
</div>
)}
</SettingsReveal>
)}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-wrap gap-1">
{KIND_FILTER.map((f) => {
const active = kindFilter === f.value
return (
<button
key={f.value}
onClick={() => setKindFilter(f.value)}
className={`rounded-md px-3 py-1.5 text-xs transition-colors ${
active
? 'bg-secondary text-foreground'
: 'text-muted-foreground hover:bg-secondary/60 hover:text-foreground'
}`}
>
{f.label}
</button>
)
})}
</div>
<label className="inline-flex items-center gap-2 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
checked={includeDismissed}
onChange={(e) => setIncludeDismissed(e.target.checked)}
className="h-3.5 w-3.5"
/>
Visa dolda
</label>
</div>
<SettingsRow label="Visa dolda">
<SettingsRowEnd>
<Switch
checked={includeDismissed}
onCheckedChange={setIncludeDismissed}
aria-label="Visa dolda"
/>
</SettingsRowEnd>
</SettingsRow>
{rows && (
<div className="text-xs text-muted-foreground tabular-nums">
{/* Dynamic status stays visible; the static "how it's used" copy lives
in the group help above. */}
{rows && (
<p className="px-1 pt-3">
<SettingsRowNote className="tabular-nums">
{counts.active} aktiva · {counts.pinned} fästa
{includeDismissed && counts.dismissed > 0 ? ` · ${counts.dismissed} dolda` : ''}
<span className="ml-1">(upp till 30 ingår i samtal per tur)</span>
</div>
)}
</SettingsRowNote>
</p>
)}
{rows === null && (
<div className="space-y-3">
{[0, 1, 2].map((i) => (
<Skeleton key={i} className="h-20 w-full rounded-lg" />
))}
</div>
)}
{rows === null && (
<div className="space-y-3 pt-3">
{[0, 1, 2].map((i) => (
<Skeleton key={i} className="h-16 w-full" />
))}
</div>
)}
{rows && rows.length === 0 && (
<EmptyState
icon={Brain}
title="Inga minnen ännu"
description="När du lär assistenten saker (eller när den noterar saker själv med ditt godkännande) dyker de upp här."
/>
)}
{rows && rows.length === 0 && (
<EmptyState
icon={Brain}
title="Inga minnen ännu"
description="När du lär assistenten saker (eller när den noterar saker själv med ditt godkännande) dyker de upp här."
/>
)}
{rows && rows.length > 0 && (
<ul className="space-y-3">
{rows.map((row) => {
const isEditing = editingId === row.id
const isBusy = busyId === row.id
const dimmed = !row.is_active
return (
<li
key={row.id}
className={`rounded-lg border border-border p-4 transition-colors ${
dimmed ? 'bg-muted/30 opacity-70' : 'bg-card'
}`}
>
<div className="flex items-start gap-3">
{canWrite && row.is_active ? (
<button
onClick={() => patch(row.id, { is_pinned: !row.is_pinned })}
disabled={isBusy}
className={`mt-0.5 shrink-0 rounded-md p-1.5 transition-colors ${
row.is_pinned
? 'text-foreground bg-secondary'
: 'text-muted-foreground hover:bg-secondary/60 hover:text-foreground'
}`}
aria-label={row.is_pinned ? 'Lossa' : 'Fäst'}
title={row.is_pinned ? 'Lossa' : 'Fäst: säkerställer att minnet alltid skickas med'}
>
{row.is_pinned ? <Pin className="h-4 w-4 fill-current" /> : <PinOff className="h-4 w-4" />}
</button>
{rows && rows.length > 0 && (
<ul>
{rows.map((row) => {
const isEditing = editingId === row.id
const isBusy = busyId === row.id
const dimmed = !row.is_active
return (
<li
key={row.id}
className={cn(
'border-b border-border px-1 py-3 transition-colors',
dimmed && 'opacity-70',
)}
>
<div className="flex items-start gap-3">
{canWrite && row.is_active ? (
<button
onClick={() => patch(row.id, { is_pinned: !row.is_pinned })}
disabled={isBusy}
className={cn(
'mt-0.5 shrink-0 rounded-md p-1.5 transition-colors duration-150',
row.is_pinned
? 'bg-secondary text-foreground'
: 'text-muted-foreground hover:bg-secondary/60 hover:text-foreground',
)}
aria-label={row.is_pinned ? 'Lossa' : 'Fäst'}
title={row.is_pinned ? 'Lossa' : 'Fäst: säkerställer att minnet alltid skickas med'}
>
{row.is_pinned ? <Pin className="h-4 w-4 fill-current" /> : <PinOff className="h-4 w-4" />}
</button>
) : (
<div className="mt-0.5 shrink-0 p-1.5">
{row.is_pinned && <Pin className="h-4 w-4 fill-current text-foreground" />}
</div>
)}
<div className="min-w-0 flex-1 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<span className="text-[11px] text-muted-foreground">
{KIND_LABEL[row.kind]} · {SOURCE_LABEL[row.source]}
</span>
{dimmed && <Badge variant="secondary">Dold</Badge>}
</div>
{isEditing ? (
<SettingsTextarea
value={editDraft}
onChange={(e) => setEditDraft(e.target.value)}
rows={3}
maxLength={2000}
autoFocus
aria-label="Redigera minne"
className="w-full border-border"
/>
) : (
<div className="mt-0.5 shrink-0 p-1.5">
{row.is_pinned && <Pin className="h-4 w-4 fill-current text-foreground" />}
</div>
<p className="whitespace-pre-wrap break-words text-sm text-foreground">{row.content}</p>
)}
<div className="flex-1 min-w-0 space-y-2">
<div className="flex flex-wrap items-center gap-2">
<span className="text-[11px] text-muted-foreground">
{KIND_LABEL[row.kind]} · {SOURCE_LABEL[row.source]}
</span>
{dimmed && <Badge variant="secondary">Dold</Badge>}
</div>
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
<p className="text-[11px] text-muted-foreground tabular-nums">
Skapad {formatDateLong(row.created_at)}
{row.updated_at !== row.created_at && ` · uppdaterad ${formatDateLong(row.updated_at)}`}
</p>
{isEditing ? (
<Textarea
value={editDraft}
onChange={(e) => setEditDraft(e.target.value)}
rows={3}
maxLength={2000}
autoFocus
/>
) : (
<p className="text-sm text-foreground whitespace-pre-wrap break-words">{row.content}</p>
)}
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
<p className="text-[11px] text-muted-foreground tabular-nums">
Skapad {formatDateLong(row.created_at)}
{row.updated_at !== row.created_at && ` · uppdaterad ${formatDateLong(row.updated_at)}`}
</p>
{canWrite && (
<div className="flex items-center gap-1">
{isEditing ? (
<>
<Button
variant="ghost"
size="sm"
onClick={() => setEditingId(null)}
disabled={isBusy}
>
<X className="h-4 w-4" />
<span className="sr-only">Avbryt</span>
</Button>
<Button
size="sm"
onClick={() => saveEdit(row)}
disabled={isBusy || editDraft.trim().length < 2}
>
{isBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Spara'}
</Button>
</>
) : row.is_active ? (
<>
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(row)}
disabled={isBusy}
>
<Pencil className="mr-1 h-3.5 w-3.5" />
Redigera
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => patch(row.id, { is_active: false })}
disabled={isBusy}
>
{isBusy ? (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="mr-1 h-3.5 w-3.5" />
)}
Dölj
</Button>
</>
) : (
{canWrite && (
<div className="flex items-center gap-1">
{isEditing ? (
<>
<Button
variant="ghost"
size="sm"
onClick={() => patch(row.id, { is_active: true })}
onClick={() => setEditingId(null)}
disabled={isBusy}
>
<X className="h-4 w-4" />
<span className="sr-only">Avbryt</span>
</Button>
<Button
size="sm"
onClick={() => saveEdit(row)}
disabled={isBusy || editDraft.trim().length < 2}
>
{isBusy ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Spara'}
</Button>
</>
) : row.is_active ? (
<>
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(row)}
disabled={isBusy}
>
<Pencil className="mr-1 h-3.5 w-3.5" />
Redigera
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => patch(row.id, { is_active: false })}
disabled={isBusy}
>
{isBusy ? (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
) : (
<RotateCcw className="mr-1 h-3.5 w-3.5" />
<Trash2 className="mr-1 h-3.5 w-3.5" />
)}
Återställ
Dölj
</Button>
)}
</div>
)}
</div>
</>
) : (
<Button
variant="ghost"
size="sm"
onClick={() => patch(row.id, { is_active: true })}
disabled={isBusy}
>
{isBusy ? (
<Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" />
) : (
<RotateCcw className="mr-1 h-3.5 w-3.5" />
)}
Återställ
</Button>
)}
</div>
)}
</div>
</div>
</li>
)
})}
</ul>
)}
</CardContent>
</Card>
</div>
</li>
)
})}
</ul>
)}
</SettingsGroup>
)
}
+98 -101
View File
@@ -4,11 +4,13 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
import { ChevronDown, GraduationCap, Loader2 } from 'lucide-react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { EmptyState } from '@/components/ui/empty-state'
import { HelpPopover } from '@/components/ui/help-popover'
import { Skeleton } from '@/components/ui/skeleton'
import { useToast } from '@/components/ui/use-toast'
import { SettingsGroup, SettingsRowNote } from '@/components/settings/SettingsRows'
import { cn } from '@/lib/utils'
type Tier = 'horizontal' | 'vertical' | 'modifier'
@@ -53,7 +55,7 @@ const PROSE =
'[&_td]:border-b [&_td]:border-border [&_td]:py-1.5 [&_td]:px-2 [&_td]:align-top'
// The API returns errors either as a plain string (legacy/validation) or as
// the canonical { code, message } envelope — extract something renderable.
// the canonical { code, message } envelope; extract something renderable.
function apiErrorText(error: unknown): string | undefined {
if (typeof error === 'string') return error
if (error && typeof error === 'object' && 'message' in error) {
@@ -118,112 +120,107 @@ export function AgentSkillsPanel() {
}
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Vad min assistent kan</CardTitle>
<CardDescription>
Utöver vad den minns om ditt företag bygger assistenten på en uppsättning kunskapsområden
om svensk bokföring och skatt. Kärnkompetensen gäller alla; bransch- och bolagsanpassningen
väljs utifrån ditt företag. Klicka för att läsa hela kunskapen.
</CardDescription>
</CardHeader>
<CardContent className="space-y-8">
{atoms && (
<div className="text-xs text-muted-foreground tabular-nums">
<div>
{/* Dynamic status stays visible; the static "what this is" copy sits
behind the "?" next to it. */}
{atoms && (
<div className="flex items-center gap-2 px-1">
<SettingsRowNote className="tabular-nums">
{counts.total} kunskapsområden · {counts.active} aktiva för ditt företag
</div>
)}
</SettingsRowNote>
<HelpPopover className="shrink-0">
Utöver vad den minns om ditt företag bygger assistenten på en uppsättning
kunskapsområden om svensk bokföring och skatt. Kärnkompetensen gäller alla;
bransch- och bolagsanpassningen väljs utifrån ditt företag. Klicka på ett
område för att läsa hela kunskapen.
</HelpPopover>
</div>
)}
{atoms === null && (
<div className="space-y-3">
{[0, 1, 2, 3].map((i) => (
<Skeleton key={i} className="h-16 w-full rounded-lg" />
))}
</div>
)}
{atoms === null && (
<div className="space-y-3">
{[0, 1, 2, 3].map((i) => (
<Skeleton key={i} className="h-12 w-full" />
))}
</div>
)}
{atoms && atoms.length === 0 && (
<EmptyState
icon={GraduationCap}
title="Inga kunskapsområden ännu"
description="När din assistent har komponerats dyker dess kunskapsområden upp här."
/>
)}
{atoms && atoms.length === 0 && (
<EmptyState
icon={GraduationCap}
title="Inga kunskapsområden ännu"
description="När din assistent har komponerats dyker dess kunskapsområden upp här."
/>
)}
{atoms && atoms.length > 0 &&
TIER_ORDER.filter((tier) => grouped[tier].length > 0).map((tier) => (
<section key={tier} className="space-y-3">
<div className="space-y-1">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{TIER_SECTION[tier].title}
</h2>
<p className="text-xs text-muted-foreground">{TIER_SECTION[tier].blurb}</p>
</div>
<ul className="space-y-2">
{grouped[tier].map((atom) => {
const isOpen = expandedId === atom.id
const isLoading = loadingBody === atom.id
const body = bodies[atom.id]
const dormant = !atom.active
return (
<li
key={atom.id}
className={`rounded-lg border border-border transition-colors ${
dormant ? 'bg-muted/30' : 'bg-card'
}`}
>
<button
onClick={() => toggle(atom)}
aria-expanded={isOpen}
className="flex w-full items-start gap-3 p-4 text-left"
{atoms && atoms.length > 0 &&
TIER_ORDER.filter((tier) => grouped[tier].length > 0).map((tier) => (
<SettingsGroup key={tier} label={TIER_SECTION[tier].title} help={TIER_SECTION[tier].blurb}>
{grouped[tier].map((atom) => {
const isOpen = expandedId === atom.id
const isLoading = loadingBody === atom.id
const body = bodies[atom.id]
const dormant = !atom.active
return (
<div key={atom.id} className="border-b border-border">
<button
onClick={() => toggle(atom)}
aria-expanded={isOpen}
className="flex w-full items-start gap-3 px-1 py-3 text-left"
>
<ChevronDown
className={cn(
'mt-0.5 h-4 w-4 shrink-0 text-muted-foreground transition-transform',
!isOpen && '-rotate-90',
)}
/>
<span className="min-w-0 flex-1">
<span
className={cn(
'block text-sm font-medium',
dormant ? 'text-muted-foreground' : 'text-foreground',
)}
>
<ChevronDown
className={`mt-0.5 h-4 w-4 shrink-0 text-muted-foreground transition-transform ${
isOpen ? '' : '-rotate-90'
}`}
/>
<div className="flex-1 min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-sm font-medium text-foreground">{atom.title}</span>
{tier !== 'horizontal' && (
<Badge variant={atom.active ? 'success' : 'secondary'}>
{atom.active ? 'Aktiv' : 'Vilande'}
</Badge>
)}
</div>
<p className="text-xs text-muted-foreground">{atom.description}</p>
</div>
</button>
{atom.title}
</span>
<span className="block text-xs text-muted-foreground">{atom.description}</span>
</span>
{/* Chips mark exceptions: active is the normal state and
renders as muted text, only dormant gets a Badge. */}
{tier !== 'horizontal' && (
atom.active ? (
<span className="mt-0.5 shrink-0 text-xs text-muted-foreground">Aktiv</span>
) : (
<Badge variant="outline" className="mt-0.5 shrink-0">Vilande</Badge>
)
)}
</button>
{isOpen && (
<div className="border-t border-border px-4 py-4 pl-11">
{isLoading && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Läser in…
</div>
)}
{!isLoading && body !== undefined && body.length > 0 && (
<div className={PROSE}>
<ReactMarkdown remarkPlugins={[remarkGfm]}>{body}</ReactMarkdown>
</div>
)}
{!isLoading && body !== undefined && body.length === 0 && (
<p className="text-xs text-muted-foreground">
Innehållet kunde inte läsas in.
</p>
)}
{isOpen && (
<div className="px-1 pb-4 pl-8">
{isLoading && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Läser in…
</div>
)}
</li>
)
})}
</ul>
</section>
))}
</CardContent>
</Card>
{!isLoading && body !== undefined && body.length > 0 && (
<div className={PROSE}>
<ReactMarkdown remarkPlugins={[remarkGfm]}>{body}</ReactMarkdown>
</div>
)}
{!isLoading && body !== undefined && body.length === 0 && (
<p className="text-xs text-muted-foreground">
Innehållet kunde inte läsas in.
</p>
)}
</div>
)}
</div>
)
})}
</SettingsGroup>
))}
</div>
)
}
+144 -151
View File
@@ -2,7 +2,6 @@
import { useTranslations } from 'next-intl'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
@@ -18,9 +17,16 @@ import {
import { Checkbox } from '@/components/ui/checkbox'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import { EmptyState } from '@/components/ui/empty-state'
import { HelpPopover } from '@/components/ui/help-popover'
import { useToast } from '@/components/ui/use-toast'
import {
SettingsGroup,
SettingsReveal,
SettingsRow,
SettingsRowNote,
} from '@/components/settings/SettingsRows'
import { Loader2, Plus, Copy, Check, Trash2, Key, ChevronDown, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { cn, formatDateLong } from '@/lib/utils'
import { getBranding } from '@/lib/branding/service'
import { STAGING_SCOPES } from '@/lib/auth/api-keys'
import type { ApiKeyScope } from '@/lib/auth/api-keys'
@@ -366,15 +372,6 @@ export function ApiKeysPanel() {
setTimeout(() => setCopied(false), 2000)
}
function formatDate(iso: string | null) {
if (!iso) return '-'
return new Date(iso).toLocaleDateString('sv-SE', {
year: 'numeric',
month: 'short',
day: 'numeric',
})
}
const mcpBase = typeof window !== 'undefined'
? `${window.location.origin}/api/extensions/ext/mcp-server/mcp`
: '/api/extensions/ext/mcp-server/mcp'
@@ -383,140 +380,137 @@ export function ApiKeysPanel() {
const mcpUrl = (client: string) => `${mcpBase}?client=${client}`
return (
<div className="space-y-6">
<Card>
<CardHeader>
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-base">{t('title')}</CardTitle>
<CardDescription>
{t('description')}
</CardDescription>
</div>
<Button
size="sm"
onClick={() => setShowCreateDialog(true)}
disabled={keys.length >= 10}
>
<Plus className="mr-1.5 h-3.5 w-3.5" />
{t('create_key')}
</Button>
</div>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : keys.length === 0 ? (
<EmptyState
icon={Key}
title={t('empty_title')}
description={t('empty_help')}
/>
) : (
<div className="space-y-3">
{keys.map((key) => {
const scopeCount = key.scopes?.length ?? 0
return (
<div
key={key.id}
className="flex items-center justify-between rounded-md border px-4 py-3"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="text-sm font-medium truncate">{key.name}</p>
{key.mode === 'test' && (
<Badge variant="secondary" className="shrink-0 text-[10px] font-normal px-1.5 py-0">
{t('badge_test')}
</Badge>
)}
<span className="text-xs text-muted-foreground">
{scopeCount === ALL_SCOPES.length
? t('all_permissions')
: scopeCount === 0
? t('no_permissions')
: t('permissions_count', { count: scopeCount })}
</span>
</div>
<div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1">
<code className="text-xs text-muted-foreground font-mono">
{key.key_prefix}...
</code>
<span className="text-xs text-muted-foreground">
{t('created')} {formatDate(key.created_at)}
</span>
<span className="text-xs text-muted-foreground">
{key.last_used_at
? t('used_on', { date: formatDate(key.last_used_at) })
: t('never_used')}
</span>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => handleRevoke(key.id, key.name)}
aria-label={t('revoke_aria', { name: key.name })}
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
)
})}
</div>
)}
</CardContent>
</Card>
<>
<SettingsGroup>
{/* Group eyebrow with the group's primary action on the right. Styling
mirrors SettingsGroup's label line; the "?" holds the old panel
description. */}
<div className="flex items-center justify-between gap-4 px-1">
<p className="flex items-center gap-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
<span>{t('title')}</span>
<HelpPopover className="shrink-0">{t('description')}</HelpPopover>
</p>
<Button
size="sm"
onClick={() => setShowCreateDialog(true)}
disabled={keys.length >= 10}
>
<Plus className="mr-1.5 h-3.5 w-3.5" />
{t('create_key')}
</Button>
</div>
<Card>
<CardHeader>
<CardTitle className="text-base">{t('connect_mcp_title')}</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
<div>
<div className="flex items-center gap-2 mb-2">
<p className="text-sm font-medium">Claude.ai</p>
<span className="text-xs text-muted-foreground">{t('recommended_badge')}</span>
</div>
<p className="text-xs text-muted-foreground mb-2">
{t.rich('claude_ai_instructions', {
connectorName,
path: (chunks) => <strong>{chunks}</strong>,
})}
</p>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : keys.length === 0 ? (
<EmptyState
icon={Key}
title={t('empty_title')}
description={t('empty_help')}
/>
) : (
keys.map((key) => {
const scopeCount = key.scopes?.length ?? 0
const permissionSummary =
scopeCount === ALL_SCOPES.length
? t('all_permissions')
: scopeCount === 0
? t('no_permissions')
: t('permissions_count', { count: scopeCount })
return (
<div
key={key.id}
className="flex items-center gap-3 border-b border-border px-1 py-3"
>
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="flex min-w-0 items-center gap-2">
<span className="truncate text-sm">{key.name}</span>
{key.mode === 'test' && (
<Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[10px] font-normal">
{t('badge_test')}
</Badge>
)}
</span>
<span className="min-w-0 truncate text-xs text-muted-foreground">
{permissionSummary}
{' · '}
<span className="font-mono">{key.key_prefix}...</span>
</span>
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
{t('created')} {formatDateLong(key.created_at)}
{' · '}
{key.last_used_at
? t('used_on', { date: formatDateLong(key.last_used_at) })
: t('never_used')}
</span>
</div>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
onClick={() => handleRevoke(key.id, key.name)}
aria-label={t('revoke_aria', { name: key.name })}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
)
})
)}
</SettingsGroup>
<SettingsGroup label={t('connect_mcp_title')}>
<SettingsRow
label="Claude.ai"
align="baseline"
help={t.rich('claude_ai_instructions', {
connectorName,
path: (chunks) => <strong>{chunks}</strong>,
})}
>
<SettingsRowNote>{t('recommended_badge')}</SettingsRowNote>
<div className="w-full min-w-0">
<CopyBlock text={mcpUrl('claude-connector')} copyAriaLabel={t('copy_aria')} />
</div>
</SettingsRow>
<div>
<p className="text-sm font-medium mb-2">{t('claude_code_cursor')}</p>
<p className="text-xs text-muted-foreground mb-2">
{t('terminal_runs_browser_login')}
</p>
{/* URL is quoted: unquoted `?` in the query string trips zsh globbing. */}
<SettingsRow
label={t('claude_code_cursor')}
align="baseline"
help={t('terminal_runs_browser_login')}
>
{/* URL is quoted: unquoted `?` in the query string trips zsh globbing. */}
<div className="w-full min-w-0">
<CopyBlock text={`claude mcp add ${connectorName} --transport http "${mcpUrl('claude-code')}"`} copyAriaLabel={t('copy_aria')} />
</div>
</SettingsRow>
<div className="border-t pt-4">
<button
type="button"
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
onClick={() => setShowApiKeyMethods(!showApiKeyMethods)}
>
<ChevronDown className={`h-3.5 w-3.5 transition-transform ${showApiKeyMethods ? '' : '-rotate-90'}`} />
{t('connect_with_api_key')}
</button>
{showApiKeyMethods && (
<div className="space-y-6 pt-4 animate-in slide-in-from-top-1 duration-150">
<div>
<p className="text-sm font-medium mb-1">Claude Desktop</p>
<p className="text-xs text-muted-foreground mb-2">
{t.rich('claude_desktop_instructions', {
code: (chunks) => <code className="text-xs">{chunks}</code>,
})}
</p>
<CopyBlock text={`{
<button
type="button"
aria-expanded={showApiKeyMethods}
onClick={() => setShowApiKeyMethods(!showApiKeyMethods)}
className="flex items-center gap-2 px-1 py-3 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
>
<ChevronDown
className={cn(
'h-3.5 w-3.5 transition-transform duration-150',
!showApiKeyMethods && '-rotate-90',
)}
/>
{t('connect_with_api_key')}
</button>
<SettingsReveal open={showApiKeyMethods}>
<div className="space-y-6 pb-3 pt-1">
<div>
<p className="mb-1 text-sm">Claude Desktop</p>
<p className="mb-2 text-xs text-muted-foreground">
{t.rich('claude_desktop_instructions', {
code: (chunks) => <code className="text-xs">{chunks}</code>,
})}
</p>
<CopyBlock text={`{
"mcpServers": {
"${connectorName}": {
"command": "npx",
@@ -528,22 +522,20 @@ export function ApiKeysPanel() {
}
}
}`} copyAriaLabel={t('copy_aria')} />
</div>
</div>
<div>
<p className="text-sm font-medium mb-1">{t('claude_code_cursor')}</p>
<p className="text-xs text-muted-foreground mb-2">
{t('terminal_with_api_key')}
</p>
<CopyBlock text={`claude mcp add ${connectorName} --transport http \\
<div>
<p className="mb-1 text-sm">{t('claude_code_cursor')}</p>
<p className="mb-2 text-xs text-muted-foreground">
{t('terminal_with_api_key')}
</p>
<CopyBlock text={`claude mcp add ${connectorName} --transport http \\
--url "${mcpUrl('claude-code')}" \\
--header "Authorization: Bearer gnubok_sk_..."`} copyAriaLabel={t('copy_aria')} />
</div>
</div>
)}
</div>
</div>
</CardContent>
</Card>
</SettingsReveal>
</SettingsGroup>
{/* Create key dialog */}
<Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
@@ -697,6 +689,7 @@ export function ApiKeysPanel() {
size="sm"
className="absolute right-2 top-2"
onClick={handleCopy}
aria-label={t('copy_aria')}
>
{copied ? (
<Check className="h-4 w-4 text-success" />
@@ -716,6 +709,6 @@ export function ApiKeysPanel() {
</DialogFooter>
</DialogContent>
</Dialog>
</div>
</>
)
}
+53 -63
View File
@@ -6,10 +6,14 @@ import { createClient } from '@/lib/supabase/client'
import { BankIdAuth } from '@/components/auth/BankIdAuth'
import type { BankIdResult } from '@/components/auth/BankIdAuth'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Shield, ShieldCheck, Loader2 } from 'lucide-react'
import { Loader2 } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { formatDateLong } from '@/lib/utils'
import {
SettingsRow,
SettingsRowEnd,
SettingsRowNote,
} from '@/components/settings/SettingsRows'
interface BankIdIdentity {
given_name: string | null
@@ -78,73 +82,59 @@ export function BankIdSettings() {
if (isLoading) {
return (
<Card>
<CardContent className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</CardContent>
</Card>
)
}
if (isLinking) {
return (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('link_bankid_title')}</CardTitle>
<CardDescription>{t('link_bankid_description')}</CardDescription>
</CardHeader>
<CardContent className="flex flex-col items-center">
<BankIdAuth mode="link" onComplete={handleLinkComplete} />
</CardContent>
</Card>
<SettingsRow label={t('title')}>
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</SettingsRow>
)
}
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
{identity ? (
<ShieldCheck className="h-4 w-4 text-success" />
) : (
<Shield className="h-4 w-4 text-muted-foreground" />
)}
{t('title')}
</CardTitle>
<CardDescription>
{identity ? t('linked_description') : t('not_linked_description')}
</CardDescription>
</CardHeader>
<CardContent>
<>
<SettingsRow
label={t('title')}
help={identity ? t('linked_description') : t('not_linked_description')}
borderless={isLinking}
>
{identity ? (
<div className="flex items-center justify-between">
<div className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
{identity.given_name} {identity.surname}
</span>
<span className="ml-2">
{t('linked_on', { date: formatDateLong(identity.linked_at) })}
</span>
</div>
<Button
variant="ghost"
size="sm"
onClick={handleUnlink}
disabled={isUnlinking}
className="text-destructive hover:text-destructive"
>
{isUnlinking ? t('unlinking') : t('unlink_button')}
</Button>
</div>
<>
<span className="text-sm font-medium">
{identity.given_name} {identity.surname}
</span>
<SettingsRowNote>
{t('linked_on', { date: formatDateLong(identity.linked_at) })}
</SettingsRowNote>
<SettingsRowEnd>
<Button
variant="ghost"
size="sm"
onClick={handleUnlink}
disabled={isUnlinking}
className="text-destructive hover:text-destructive"
>
{isUnlinking ? t('unlinking') : t('unlink_button')}
</Button>
</SettingsRowEnd>
</>
) : isLinking ? (
// Active flow: the scan instruction is the actionable content and
// stays visible while the QR block below is open.
<SettingsRowNote>{t('link_bankid_description')}</SettingsRowNote>
) : (
<Button
variant="outline"
onClick={() => setIsLinking(true)}
>
{t('link_button')}
</Button>
<SettingsRowEnd>
<Button variant="ghost" size="sm" onClick={() => setIsLinking(true)}>
{t('link_button')}
</Button>
</SettingsRowEnd>
)}
</CardContent>
</Card>
</SettingsRow>
{/* QR flow: an expanding block below the row. Mounted only while
linking so the BankID session starts exactly when requested. */}
{isLinking && (
<div className="flex flex-col items-center border-b border-border px-1 py-4">
<BankIdAuth mode="link" onComplete={handleLinkComplete} />
</div>
)}
</>
)
}
+38 -39
View File
@@ -1,9 +1,10 @@
'use client'
import { useState, type ReactNode } from 'react'
import { useState } from 'react'
import { ChevronRight } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { SettingsSeg } from '@/components/settings/SettingsRows'
import { formatDateLong } from '@/lib/utils'
import type { BillingPlan } from '@/lib/stripe/client'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
@@ -25,8 +26,9 @@ const PRICE: Record<BillingPlan, { amount: string; suffix: string; sub: string;
/**
* Interactive billing CTA. Paying companies get the Stripe Customer Portal
* (manage/cancel); everyone else gets a reactive plan picker + Checkout. Both
* POST to a route that returns a hosted Stripe URL we redirect to.
* (manage/cancel) as a quiet row action; everyone else gets a plan picker
* (SettingsSeg) + Checkout. Both POST to a route that returns a hosted Stripe
* URL we redirect to.
*
* `firstChargeAt`: when the checkout route will defer the first charge to the
* trial's end (see billing/checkout), the date it lands. Shifts the CTA from
@@ -72,7 +74,7 @@ export function BillingActions({
if (isPaying) {
return (
<Button size="lg" onClick={() => go('/api/billing/portal')} disabled={loading} className="w-full sm:w-auto">
<Button variant="outline" size="sm" onClick={() => go('/api/billing/portal')} disabled={loading}>
Hantera abonnemang
</Button>
)
@@ -80,58 +82,55 @@ export function BillingActions({
if (!configured) {
return (
<Button size="lg" disabled className="w-full">
<Button size="lg" disabled className="w-full sm:w-auto">
Uppgradering öppnar snart
</Button>
)
}
const segment = (p: BillingPlan, label: ReactNode) => (
<button
type="button"
onClick={() => setPlan(p)}
className={`flex items-center rounded-md px-3 py-2 transition-colors ${
plan === p ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground'
}`}
>
{label}
</button>
)
return (
<div className="space-y-4">
<div>
<div className="flex items-baseline gap-2">
<span className="font-display text-3xl tracking-tight tabular-nums">{PRICE[plan].amount}</span>
<span className="text-muted-foreground">{PRICE[plan].suffix}</span>
</div>
<p className="text-sm text-muted-foreground mt-1">{PRICE[plan].sub}</p>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
<SettingsSeg
value={plan}
onChange={setPlan}
aria-label="Betalningsintervall"
options={[
{ value: 'monthly', label: 'Månadsvis' },
{
value: 'yearly',
label: (
<>
Årsvis
<span className="ml-2 text-muted-foreground">Spara 2 mån</span>
</>
),
},
]}
/>
<p className="text-sm text-muted-foreground">
<span className="tabular-nums text-foreground">{PRICE[plan].amount}</span> {PRICE[plan].suffix}
</p>
</div>
<p className="text-xs text-muted-foreground tabular-nums">{PRICE[plan].sub}</p>
<div className="inline-flex rounded-lg border border-border p-1 text-sm">
{segment('monthly', 'Månadsvis')}
{segment(
'yearly',
<>
Årsvis
<span className="ml-2 text-xs text-muted-foreground">Spara 2 mån</span>
</>,
)}
</div>
<Button size="lg" onClick={() => go('/api/billing/checkout', { plan })} disabled={loading} className="w-full">
<Button
size="lg"
onClick={() => go('/api/billing/checkout', { plan })}
disabled={loading}
className="w-full sm:w-auto"
>
{loading ? 'Öppnar…' : firstChargeAt ? 'Starta abonnemanget: 0 kr idag' : PRICE[plan].cta}
{!loading && <ChevronRight className="h-4 w-4" />}
</Button>
{firstChargeAt && (
<p className="text-xs text-muted-foreground text-center">
// The one deferred-charge line that stays visible (the rest of the
// legal/marketing copy lives behind the group-level "?").
<p className="text-xs text-muted-foreground">
Första debiteringen sker {formatDateLong(firstChargeAt)}, när provperioden slutar. Avslutar du innan dess
kostar det ingenting.
</p>
)}
<p className="text-xs text-muted-foreground text-center">
Ingen bindningstid · Avsluta när du vill · Säker betalning via Stripe
</p>
</div>
)
}
+175 -164
View File
@@ -2,9 +2,9 @@
import { useTranslations } from 'next-intl'
import { useState, useEffect, useCallback, useRef } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { HelpPopover } from '@/components/ui/help-popover'
import { useToast } from '@/components/ui/use-toast'
import {
Dialog,
@@ -13,10 +13,12 @@ import {
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { Loader2, Trash2, Plus, ChevronDown, Download, Upload, Building2, Users, Globe, Pencil, Copy } from 'lucide-react'
import { SettingsGroup } from '@/components/settings/SettingsRows'
import { Loader2, Trash2, Plus, ChevronDown, Download, Upload, Pencil, Copy } from 'lucide-react'
import { TEMPLATE_CATEGORY_LABELS, convertLibraryToBookingTemplate } from '@/lib/bookkeeping/template-library'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { TemplateForm } from '@/components/settings/TemplateForm'
import { cn } from '@/lib/utils'
import type { BookingTemplateLibrary, BookingTemplateLibraryLine } from '@/types'
export function BookingTemplatesPanel() {
@@ -125,124 +127,131 @@ export function BookingTemplatesPanel() {
return (
<>
<Card>
<CardHeader>
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div>
<CardTitle className="text-base">{t('title')}</CardTitle>
<CardDescription>
{t('description')}
</CardDescription>
</div>
{canWrite && (
<div className="flex gap-2 shrink-0">
<Button variant="outline" size="sm" onClick={handleExport}>
<Download className="h-3.5 w-3.5 mr-1.5" />
{t('export')}
</Button>
<Button variant="outline" size="sm" onClick={() => importRef.current?.click()}>
<Upload className="h-3.5 w-3.5 mr-1.5" />
{t('import')}
</Button>
<input
ref={importRef}
type="file"
accept=".json"
className="hidden"
onChange={handleImport}
/>
<Dialog open={showCreate} onOpenChange={setShowCreate}>
<DialogTrigger asChild>
<Button size="sm">
<Plus className="h-3.5 w-3.5 mr-1.5" />
{t('new_template')}
</Button>
</DialogTrigger>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{t('create_dialog_title')}</DialogTitle>
</DialogHeader>
<TemplateForm
mode="create"
entityLabels={ENTITY_LABELS}
duplicateNamePool={companyTemplateNames}
onSaved={() => {
setShowCreate(false)
fetchTemplates()
}}
/>
</DialogContent>
</Dialog>
</div>
)}
</div>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : templates.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-12">
{t('empty_state')}
</p>
) : (
<div className="space-y-6">
{/* System templates */}
{systemTemplates.length > 0 && (
<TemplateSection
title={t('section_system')}
icon={Globe}
templates={systemTemplates}
expandedId={expandedId}
onToggle={setExpandedId}
deletingId={deletingId}
onDelete={handleDelete}
canDelete={false}
canEdit={false}
canCustomize={canWrite}
onCustomize={setActiveTemplate}
entityLabels={ENTITY_LABELS}
/>
)}
{/* Team templates */}
{teamTemplates.length > 0 && (
<TemplateSection
title={t('section_team')}
icon={Users}
templates={teamTemplates}
expandedId={expandedId}
onToggle={setExpandedId}
deletingId={deletingId}
onDelete={handleDelete}
canDelete={canWrite}
canEdit={canWrite}
onEdit={setActiveTemplate}
entityLabels={ENTITY_LABELS}
/>
)}
{/* Company templates */}
{companyTemplates.length > 0 && (
<TemplateSection
title={t('section_company')}
icon={Building2}
templates={companyTemplates}
expandedId={expandedId}
onToggle={setExpandedId}
deletingId={deletingId}
onDelete={handleDelete}
canDelete={canWrite}
canEdit={canWrite}
onEdit={setActiveTemplate}
entityLabels={ENTITY_LABELS}
/>
)}
<SettingsGroup>
{/* Group eyebrow with the panel's actions on the right: export/import as
quiet buttons, "Ny mall" as the one pill. The old card description
lives behind the "?". */}
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 px-1">
<p className="flex items-center gap-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
<span>{t('title')}</span>
<HelpPopover className="shrink-0">{t('description')}</HelpPopover>
</p>
{canWrite && (
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={handleExport}
className="text-muted-foreground hover:text-foreground"
>
<Download className="mr-1.5 h-3.5 w-3.5" />
{t('export')}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => importRef.current?.click()}
className="text-muted-foreground hover:text-foreground"
>
<Upload className="mr-1.5 h-3.5 w-3.5" />
{t('import')}
</Button>
<input
ref={importRef}
type="file"
accept=".json"
className="hidden"
onChange={handleImport}
/>
<Dialog open={showCreate} onOpenChange={setShowCreate}>
<DialogTrigger asChild>
<Button size="sm">
<Plus className="mr-1.5 h-3.5 w-3.5" />
{t('new_template')}
</Button>
</DialogTrigger>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{t('create_dialog_title')}</DialogTitle>
</DialogHeader>
<TemplateForm
mode="create"
entityLabels={ENTITY_LABELS}
duplicateNamePool={companyTemplateNames}
onSaved={() => {
setShowCreate(false)
fetchTemplates()
}}
/>
</DialogContent>
</Dialog>
</div>
)}
</CardContent>
</Card>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : templates.length === 0 ? (
<p className="py-12 text-center text-sm text-muted-foreground">
{t('empty_state')}
</p>
) : null}
</SettingsGroup>
{!isLoading && templates.length > 0 && (
<>
{/* System templates */}
{systemTemplates.length > 0 && (
<TemplateSection
title={t('section_system')}
templates={systemTemplates}
expandedId={expandedId}
onToggle={setExpandedId}
deletingId={deletingId}
onDelete={handleDelete}
canDelete={false}
canEdit={false}
canCustomize={canWrite}
onCustomize={setActiveTemplate}
entityLabels={ENTITY_LABELS}
/>
)}
{/* Team templates */}
{teamTemplates.length > 0 && (
<TemplateSection
title={t('section_team')}
templates={teamTemplates}
expandedId={expandedId}
onToggle={setExpandedId}
deletingId={deletingId}
onDelete={handleDelete}
canDelete={canWrite}
canEdit={canWrite}
onEdit={setActiveTemplate}
entityLabels={ENTITY_LABELS}
/>
)}
{/* Company templates */}
{companyTemplates.length > 0 && (
<TemplateSection
title={t('section_company')}
templates={companyTemplates}
expandedId={expandedId}
onToggle={setExpandedId}
deletingId={deletingId}
onDelete={handleDelete}
canDelete={canWrite}
canEdit={canWrite}
onEdit={setActiveTemplate}
entityLabels={ENTITY_LABELS}
/>
)}
</>
)}
{/* Shared edit / customize dialog. Editing a company or team template uses
PUT; customizing a read-only system template creates a company-scoped
@@ -276,7 +285,6 @@ export function BookingTemplatesPanel() {
function TemplateSection({
title,
icon: Icon,
templates,
expandedId,
onToggle,
@@ -290,7 +298,6 @@ function TemplateSection({
entityLabels,
}: {
title: string
icon: React.ComponentType<{ className?: string }>
templates: BookingTemplateLibrary[]
expandedId: string | null
onToggle: (id: string | null) => void
@@ -304,52 +311,54 @@ function TemplateSection({
entityLabels: Record<string, string>
}) {
const t = useTranslations('settings_booking_templates')
const tCommon = useTranslations('common')
return (
<div>
<div className="flex items-center gap-2 mb-2">
<Icon className="h-4 w-4 text-muted-foreground" />
<h3 className="text-sm font-medium">{title}</h3>
<span className="text-xs text-muted-foreground tabular-nums">{templates.length}</span>
</div>
<div className="space-y-1">
<SettingsGroup>
{/* Origin eyebrow with count; mirrors SettingsGroup's label line. */}
<p className="flex items-center gap-2 px-1 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
<span>{title}</span>
<span className="tabular-nums">{templates.length}</span>
</p>
<div>
{templates.map((tt) => {
const isExpanded = expandedId === tt.id
const isConvertible = convertLibraryToBookingTemplate(tt) !== null
return (
<div
key={tt.id}
className="rounded-lg border"
>
<div className="flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors">
<div key={tt.id} className="border-b border-border">
<div className="flex items-center gap-3 px-1 py-3 transition-colors duration-150 hover:bg-secondary/60">
<button
type="button"
onClick={() => onToggle(isExpanded ? null : tt.id)}
className="flex items-center gap-3 flex-1 min-w-0 text-left"
aria-expanded={isExpanded}
className="flex min-w-0 flex-1 items-center gap-3 text-left"
>
<ChevronDown className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isExpanded ? 'rotate-0' : '-rotate-90'}`} />
<div className="flex-1 min-w-0">
<span className="text-sm font-medium">{tt.name}</span>
<div className="flex items-center gap-1.5 mt-0.5 flex-wrap">
<span className="text-xs text-muted-foreground">
{TEMPLATE_CATEGORY_LABELS[tt.category]}
{tt.entity_type !== 'all' && ` · ${entityLabels[tt.entity_type]}`}
</span>
{!isConvertible && (
<Badge variant="warning" className="text-[10px] px-1.5 py-0">
{t('unconvertible_badge')}
</Badge>
)}
</div>
</div>
<ChevronDown
className={cn(
'h-4 w-4 shrink-0 text-muted-foreground transition-transform',
!isExpanded && '-rotate-90',
)}
/>
<span className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="truncate text-sm">{tt.name}</span>
<span className="text-xs text-muted-foreground">
{TEMPLATE_CATEGORY_LABELS[tt.category]}
{tt.entity_type !== 'all' && ` · ${entityLabels[tt.entity_type]}`}
</span>
{!isConvertible && (
<Badge variant="warning" className="px-1.5 py-0 text-[10px]">
{t('unconvertible_badge')}
</Badge>
)}
</span>
</button>
{canCustomize && onCustomize && (
<Button
variant="ghost"
size="sm"
size="icon"
onClick={() => onCustomize(tt)}
aria-label={t('customize')}
title={t('customize')}
className="h-8 w-8 p-0 shrink-0"
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
>
<Copy className="h-3.5 w-3.5" />
</Button>
@@ -357,11 +366,11 @@ function TemplateSection({
{canEdit && onEdit && (
<Button
variant="ghost"
size="sm"
size="icon"
onClick={() => onEdit(tt)}
aria-label={t('edit')}
title={t('edit')}
className="h-8 w-8 p-0 shrink-0"
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-foreground"
>
<Pencil className="h-3.5 w-3.5" />
</Button>
@@ -369,10 +378,12 @@ function TemplateSection({
{canDelete && (
<Button
variant="ghost"
size="sm"
size="icon"
onClick={() => onDelete(tt.id)}
disabled={deletingId === tt.id}
className="h-8 w-8 p-0 shrink-0"
aria-label={tCommon('delete')}
title={tCommon('delete')}
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
>
{deletingId === tt.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
@@ -383,23 +394,23 @@ function TemplateSection({
)}
</div>
{isExpanded && (
<div className="px-3 pb-3 pt-0">
<div className="px-1 pb-3">
{tt.description && (
<p className="text-xs text-muted-foreground mb-2">{tt.description}</p>
<p className="mb-2 text-xs text-muted-foreground">{tt.description}</p>
)}
<table className="w-full text-xs">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b">
<th className="text-left py-1 w-14">{t('th_account')}</th>
<th className="text-left py-1">{t('th_description')}</th>
<th className="text-center py-1 w-16">{t('th_type')}</th>
<th className="text-right py-1 w-12">{t('th_debit')}</th>
<th className="text-right py-1 w-12">{t('th_credit')}</th>
<tr className="border-b border-border">
<th className="w-14 py-1 text-left">{t('th_account')}</th>
<th className="py-1 text-left">{t('th_description')}</th>
<th className="w-16 py-1 text-center">{t('th_type')}</th>
<th className="w-12 py-1 text-right">{t('th_debit')}</th>
<th className="w-12 py-1 text-right">{t('th_credit')}</th>
</tr>
</thead>
<tbody>
{tt.lines.map((line: BookingTemplateLibraryLine, i: number) => (
<tr key={i} className="border-b last:border-0">
<tr key={i} className="border-b border-border last:border-0">
<td className="py-1 font-mono">{line.account}</td>
<td className="py-1">{line.label}</td>
<td className="py-1 text-center">
@@ -419,6 +430,6 @@ function TemplateSection({
)
})}
</div>
</div>
</SettingsGroup>
)
}
+97 -138
View File
@@ -2,14 +2,18 @@
import { useTranslations } from 'next-intl'
import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'
import { Calendar, Copy, RefreshCw, Loader2, ExternalLink, Check } from 'lucide-react'
import { Calendar, Copy, RefreshCw, Loader2, Check } from 'lucide-react'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import {
SettingsGroup,
SettingsInput,
SettingsRow,
SettingsRowEnd,
SettingsRowNote,
} from '@/components/settings/SettingsRows'
import type { CalendarFeed } from '@/types'
interface CalendarFeedWithUrls extends CalendarFeed {
@@ -30,7 +34,6 @@ export function CalendarFeedSettings() {
useEffect(() => {
fetchFeed()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const fetchFeed = async () => {
@@ -162,7 +165,7 @@ export function CalendarFeedSettings() {
if (isLoading) {
return (
<div className="flex items-center justify-center h-32">
<div className="flex h-32 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)
@@ -170,177 +173,133 @@ export function CalendarFeedSettings() {
if (!feed) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Calendar className="h-5 w-5" />
{t('title')}
</CardTitle>
<CardDescription>
{t('description')}
</CardDescription>
</CardHeader>
<CardContent>
<div className="text-center space-y-4 py-4">
<p className="text-muted-foreground">
{t('empty_intro')}
</p>
<Button onClick={createFeed} disabled={isSaving}>
<SettingsGroup label={t('title')} help={t('description')}>
<SettingsRow label={t('activate_sync')} help={t('empty_intro')}>
<SettingsRowEnd>
<Button variant="ghost" size="sm" onClick={createFeed} disabled={isSaving}>
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
{t('creating')}
</>
) : (
<>
<Calendar className="mr-2 h-4 w-4" />
<Calendar className="mr-2 h-3.5 w-3.5" />
{t('activate_sync')}
</>
)}
</Button>
</div>
</CardContent>
</Card>
</SettingsRowEnd>
</SettingsRow>
</SettingsGroup>
)
}
return (
<div className="space-y-6">
<>
{/* Feed URL */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Calendar className="h-5 w-5" />
{t('title')}
</CardTitle>
<CardDescription>
{t('subscribe_description')}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{/* Quick add for Apple Calendar */}
<div className="flex gap-2">
<Button onClick={openWebcal} className="flex-1">
<Calendar className="mr-2 h-4 w-4" />
<SettingsGroup label={t('title')} help={t('subscribe_description')}>
<SettingsRow
label={t('calendar_link_label')}
htmlFor="calendar-feed-url"
help={t('calendar_link_help')}
align="baseline"
>
<SettingsInput
id="calendar-feed-url"
value={feed.httpsUrl}
readOnly
className="font-mono text-xs"
/>
<Button
variant="ghost"
size="icon"
onClick={() => copyToClipboard(feed.httpsUrl)}
aria-label={t('calendar_link_help')}
className="shrink-0 text-muted-foreground hover:text-foreground"
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
<SettingsRowEnd>
<Button variant="ghost" size="sm" onClick={openWebcal}>
<Calendar className="mr-2 h-3.5 w-3.5" />
{t('add_to_apple_calendar')}
</Button>
<Button variant="outline" onClick={() => copyToClipboard(feed.httpsUrl)}>
{copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</SettingsRowEnd>
</SettingsRow>
{/* URL display */}
<div className="space-y-2">
<Label>{t('calendar_link_label')}</Label>
<div className="flex gap-2">
<Input
value={feed.httpsUrl}
readOnly
className="font-mono text-xs"
/>
</div>
<p className="text-xs text-muted-foreground">
{t('calendar_link_help')}
</p>
</div>
{/* Stats */}
<SettingsRow label={t('create_new_link')} help={t('regen_help')}>
{/* Live feed stats stay visible: they are state, not instructions */}
{feed.last_accessed_at && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span>{t('last_fetched')}</span>
<span>
{new Date(feed.last_accessed_at).toLocaleDateString('sv-SE', {
day: 'numeric',
month: 'short',
hour: '2-digit',
minute: '2-digit',
})}
</span>
<span className="text-muted-foreground/30">·</span>
<span className="tabular-nums">
{t('times_count', { count: feed.access_count })}
</span>
</div>
<SettingsRowNote className="tabular-nums">
{t('last_fetched')}{' '}
{new Date(feed.last_accessed_at).toLocaleDateString('sv-SE', {
day: 'numeric',
month: 'short',
hour: '2-digit',
minute: '2-digit',
})}
{' · '}
{t('times_count', { count: feed.access_count })}
</SettingsRowNote>
)}
{/* Regenerate link */}
<div className="pt-2 border-t">
<SettingsRowEnd>
<Button
variant="outline"
variant="ghost"
size="sm"
onClick={regenerateToken}
disabled={isRegenerating}
>
{isRegenerating ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
<Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
{t('creating_new_link')}
</>
) : (
<>
<RefreshCw className="mr-2 h-4 w-4" />
<RefreshCw className="mr-2 h-3.5 w-3.5" />
{t('create_new_link')}
</>
)}
</Button>
<p className="text-xs text-muted-foreground mt-1">
{t('regen_help')}
</p>
</div>
</CardContent>
</Card>
</SettingsRowEnd>
</SettingsRow>
</SettingsGroup>
{/* Content settings */}
<Card>
<CardHeader>
<CardTitle>{t('content_title')}</CardTitle>
<CardDescription>
{t('content_description')}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="include-tax">{t('tax_deadlines_label')}</Label>
<p className="text-sm text-muted-foreground">
{t('tax_deadlines_help')}
</p>
</div>
<Switch
id="include-tax"
checked={feed.include_tax_deadlines}
onCheckedChange={(checked) =>
updateFeed('include_tax_deadlines', checked)
}
disabled={isSaving}
/>
</div>
<SettingsGroup label={t('content_title')} help={t('content_description')}>
<SettingsRow
label={t('tax_deadlines_label')}
htmlFor="include-tax"
help={t('tax_deadlines_help')}
>
<Switch
id="include-tax"
checked={feed.include_tax_deadlines}
onCheckedChange={(checked) =>
updateFeed('include_tax_deadlines', checked)
}
disabled={isSaving}
/>
</SettingsRow>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="include-invoices">{t('invoices_label')}</Label>
<p className="text-sm text-muted-foreground">
{t('invoices_help')}
</p>
</div>
<Switch
id="include-invoices"
checked={feed.include_invoices}
onCheckedChange={(checked) =>
updateFeed('include_invoices', checked)
}
disabled={isSaving}
/>
</div>
</CardContent>
</Card>
<SettingsRow
label={t('invoices_label')}
htmlFor="include-invoices"
help={t('invoices_help')}
>
<Switch
id="include-invoices"
checked={feed.include_invoices}
onCheckedChange={(checked) =>
updateFeed('include_invoices', checked)
}
disabled={isSaving}
/>
</SettingsRow>
</SettingsGroup>
<DestructiveConfirmDialog {...confirmDialogProps} />
</div>
</>
)
}
+27 -17
View File
@@ -16,6 +16,12 @@ import {
DialogTitle,
} from '@/components/ui/dialog'
import { RetentionNotice } from '@/components/ui/retention-notice'
import {
SettingsDangerZone,
SettingsRow,
SettingsRowEnd,
SettingsRowNote,
} from '@/components/settings/SettingsRows'
import { Loader2 } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { getBranding } from '@/lib/branding/service'
@@ -36,6 +42,7 @@ const branding = getBranding()
*/
export function CompanyDangerZone() {
const t = useTranslations('settings_company')
const tRetention = useTranslations('retention_notice')
const router = useRouter()
const { toast } = useToast()
const { company, role } = useCompany()
@@ -82,23 +89,26 @@ export function CompanyDangerZone() {
return (
<>
<section className="space-y-4 border-t border-border pt-8">
<h2 className="text-sm font-medium uppercase tracking-wider text-destructive">
{t('danger_heading')}
</h2>
<RetentionNotice variant="company" />
<div className="flex justify-end">
<Button
variant="destructive"
className="w-full sm:w-auto"
onClick={() => setShowDialog(true)}
>
{t('danger_button')}
</Button>
</div>
</section>
<SettingsDangerZone label={t('danger_heading')}>
<SettingsRow
label={t('danger_button')}
borderless
// The full BFL retention copy (incl. the backup link) lives behind
// the "?": the visible row stays one quiet line.
help={<RetentionNotice variant="company" className="border-0 bg-transparent p-0" />}
>
<SettingsRowNote>{tRetention('company_title')}</SettingsRowNote>
<SettingsRowEnd>
<button
type="button"
onClick={() => setShowDialog(true)}
className="text-sm font-medium text-destructive underline underline-offset-2 transition-colors duration-150 hover:text-destructive/80"
>
{t('danger_button')}
</button>
</SettingsRowEnd>
</SettingsRow>
</SettingsDangerZone>
<Dialog
open={showDialog}
+66 -83
View File
@@ -1,8 +1,11 @@
'use client'
import { useTranslations } from 'next-intl'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
SettingsGroup,
SettingsInput,
SettingsRow,
} from '@/components/settings/SettingsRows'
import type { CompanySettings } from '@/types'
interface CompanyInfoFormProps {
@@ -11,96 +14,76 @@ interface CompanyInfoFormProps {
export function CompanyInfoForm({ settings }: CompanyInfoFormProps) {
const t = useTranslations('settings_company')
const orgLocked = settings.onboarding_complete === true
return (
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('company_info_heading')}
</h2>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="company_name">{t('company_name_label')}</Label>
<Input
id="company_name"
name="company_name"
defaultValue={settings.company_name || ''}
/>
<p className="text-xs text-muted-foreground">
{t('company_name_help')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="org_number">{t('org_number_label')}</Label>
<Input
id="org_number"
name="org_number"
defaultValue={settings.org_number || ''}
disabled={settings.onboarding_complete === true}
/>
{settings.onboarding_complete && (
<p className="text-xs text-muted-foreground">{t('org_number_locked')}</p>
)}
</div>
</div>
<div className="space-y-2">
<Label htmlFor="address_line1">{t('address_label')}</Label>
<Input
<SettingsGroup label={t('company_info_heading')}>
<SettingsRow
label={t('company_name_label')}
htmlFor="company_name"
help={t('company_name_help')}
align="baseline"
>
<SettingsInput
id="company_name"
name="company_name"
defaultValue={settings.company_name || ''}
/>
</SettingsRow>
<SettingsRow
label={t('org_number_label')}
htmlFor="org_number"
help={orgLocked ? t('org_number_locked') : undefined}
align="baseline"
>
<SettingsInput
id="org_number"
name="org_number"
defaultValue={settings.org_number || ''}
disabled={orgLocked}
/>
</SettingsRow>
<SettingsRow label={t('address_label')} htmlFor="address_line1" align="baseline">
<SettingsInput
id="address_line1"
name="address_line1"
defaultValue={settings.address_line1 || ''}
/>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="postal_code">{t('postal_code_label')}</Label>
<Input
id="postal_code"
name="postal_code"
defaultValue={settings.postal_code || ''}
/>
</div>
<div className="space-y-2">
<Label htmlFor="city">{t('city_label')}</Label>
<Input
id="city"
name="city"
defaultValue={settings.city || ''}
/>
</div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="phone">{t('phone_label')}</Label>
<Input
id="phone"
name="phone"
type="tel"
defaultValue={settings.phone || ''}
/>
</div>
<div className="space-y-2">
<Label htmlFor="email">{t('email_label')}</Label>
<Input
id="email"
name="email"
type="email"
defaultValue={settings.email || ''}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="website">{t('website_label')}</Label>
<Input
</SettingsRow>
<SettingsRow label={t('postal_code_label')} htmlFor="postal_code" align="baseline">
<SettingsInput
id="postal_code"
name="postal_code"
defaultValue={settings.postal_code || ''}
className="max-w-24 flex-none"
/>
</SettingsRow>
<SettingsRow label={t('city_label')} htmlFor="city" align="baseline">
<SettingsInput id="city" name="city" defaultValue={settings.city || ''} />
</SettingsRow>
<SettingsRow label={t('phone_label')} htmlFor="phone" align="baseline">
<SettingsInput
id="phone"
name="phone"
type="tel"
defaultValue={settings.phone || ''}
/>
</SettingsRow>
<SettingsRow label={t('email_label')} htmlFor="email" align="baseline">
<SettingsInput
id="email"
name="email"
type="email"
defaultValue={settings.email || ''}
/>
</SettingsRow>
<SettingsRow label={t('website_label')} htmlFor="website" align="baseline">
<SettingsInput
id="website"
name="website"
defaultValue={settings.website || ''}
placeholder="https://"
/>
</div>
</section>
</SettingsRow>
</SettingsGroup>
)
}
+126 -161
View File
@@ -2,15 +2,17 @@
import { useState, useEffect, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useToast } from '@/components/ui/use-toast'
import { useCompany } from '@/contexts/CompanyContext'
import {
SettingsGroup,
SettingsInput,
SettingsRowNote,
SettingsSelect,
} from '@/components/settings/SettingsRows'
import { formatDateLong } from '@/lib/utils'
import { Loader2, Plus, Trash2, Mail, Clock, Users } from 'lucide-react'
import { Loader2, Plus, Trash2, Mail } from 'lucide-react'
interface CompanyMemberItem {
id: string
@@ -159,164 +161,127 @@ export function CompanyMembersSection() {
}
return (
<div className="space-y-6">
{/* Invite form */}
{canInvite && (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('members_invite_title', { companyName: company?.name ?? '' })}</CardTitle>
<CardDescription>
{t('members_invite_description')}
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleInvite} className="flex flex-col gap-3 sm:flex-row">
<div className="flex-1">
<Label htmlFor="company-invite-email" className="sr-only">{t('members_invite_email_label')}</Label>
<Input
id="company-invite-email"
type="email"
placeholder={t('members_invite_email_placeholder')}
value={inviteEmail}
onChange={(e) => setInviteEmail(e.target.value)}
disabled={isSending}
required
/>
</div>
<Select value={inviteRole} onValueChange={setInviteRole}>
<SelectTrigger className="w-full sm:w-[140px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="viewer">{t('members_role_viewer')}</SelectItem>
<SelectItem value="member">{t('members_role_member')}</SelectItem>
<SelectItem value="admin">{t('members_role_admin')}</SelectItem>
</SelectContent>
</Select>
<Button type="submit" disabled={isSending || !inviteEmail.trim()}>
{isSending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<Plus className="h-4 w-4 mr-1.5" />
{t('members_invite_button')}
</>
)}
</Button>
</form>
</CardContent>
</Card>
)}
{/* Members list */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Users className="h-4 w-4" />
{t('members_title')}
</CardTitle>
<CardDescription>
{t('members_count', { count: members.length, companyName: company?.name ?? '' })}
</CardDescription>
</CardHeader>
<CardContent>
<div className="divide-y divide-border/40">
{members.map((member) => (
<div key={member.id} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
<div className="flex items-center gap-3 min-w-0">
<div className="h-8 w-8 rounded-full bg-muted/60 flex items-center justify-center flex-shrink-0">
<span className="text-xs font-medium text-muted-foreground">
{member.email.charAt(0).toUpperCase()}
</span>
</div>
<div className="min-w-0">
<p className="text-sm font-medium truncate">
{member.email}
{member.is_current_user && (
<span className="text-muted-foreground font-normal ml-1">{t('members_you')}</span>
)}
</p>
<div className="flex items-center gap-1.5">
<span className="text-xs text-muted-foreground">
{roleLabels[member.role] || member.role}
</span>
{member.source === 'team' && (
<span className="text-xs text-muted-foreground">· {t('members_team_badge')}</span>
)}
</div>
</div>
</div>
{canInvite && !member.is_current_user && member.role !== 'owner' && member.source !== 'team' && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => handleRemoveMember(member.id)}
disabled={removingId === member.id}
>
{removingId === member.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
)}
</div>
))}
<SettingsGroup label={t('members_title')} help={t('members_invite_description')}>
{/* Member rows: flat hairline list, no cards. */}
{members.map((member) => (
<div
key={member.id}
className="flex items-center gap-3 border-b border-border px-1 py-3"
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted/60">
<span className="text-xs font-medium text-muted-foreground">
{member.email.charAt(0).toUpperCase()}
</span>
</div>
</CardContent>
</Card>
<p className="min-w-0 flex-1 truncate text-sm">
{member.email}
{member.is_current_user && (
<span className="ml-1 text-muted-foreground">{t('members_you')}</span>
)}
</p>
<span className="shrink-0 text-xs text-muted-foreground">
{roleLabels[member.role] || member.role}
{member.source === 'team' && <> · {t('members_team_badge')}</>}
</span>
{canInvite && !member.is_current_user && member.role !== 'owner' && member.source !== 'team' && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
aria-label={t('members_removed')}
onClick={() => handleRemoveMember(member.id)}
disabled={removingId === member.id}
>
{removingId === member.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
)}
</div>
))}
{/* Pending invitations */}
{invitations.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-base">{t('invitations_pending_title')}</CardTitle>
</CardHeader>
<CardContent>
<div className="divide-y divide-border/40">
{invitations.map((inv) => (
<div key={inv.id} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
<div className="flex items-center gap-3 min-w-0">
<div className="h-8 w-8 rounded-full bg-muted/60 flex items-center justify-center flex-shrink-0">
<Mail className="h-3.5 w-3.5 text-muted-foreground" />
</div>
<div className="min-w-0">
<p className="text-sm font-medium truncate">{inv.email}</p>
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Clock className="h-3 w-3" />
<span>
{t('invitations_expires', { date: formatDateLong(inv.expires_at) })}
</span>
</div>
</div>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">
{roleLabels[inv.role] || inv.role}
</span>
{canInvite && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-muted-foreground hover:text-destructive"
onClick={() => handleRevokeInvite(inv.id)}
disabled={revokingId === inv.id}
>
{revokingId === inv.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
)}
</div>
</div>
))}
</div>
</CardContent>
</Card>
{/* Pending invitations continue the same list, visually quieter. */}
{invitations.map((inv) => (
<div
key={inv.id}
className="flex items-center gap-3 border-b border-border px-1 py-3"
>
<div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-dashed border-border">
<Mail className="h-3.5 w-3.5 text-muted-foreground" />
</div>
<p className="min-w-0 flex-1 truncate text-sm text-muted-foreground">
{inv.email}
<span className="ml-1 text-xs">
· {t('invitations_expires', { date: formatDateLong(inv.expires_at) })}
</span>
</p>
<span className="shrink-0 text-xs text-muted-foreground">
{roleLabels[inv.role] || inv.role}
</span>
{canInvite && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive"
aria-label={t('members_invite_revoked')}
onClick={() => handleRevokeInvite(inv.id)}
disabled={revokingId === inv.id}
>
{revokingId === inv.id ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
)}
</div>
))}
{/* Inline invite: the list's own last row instead of a separate card. */}
{canInvite && (
<form onSubmit={handleInvite} className="flex flex-col gap-3 px-1 pt-3 sm:flex-row sm:items-center">
<label htmlFor="company-invite-email" className="sr-only">
{t('members_invite_email_label')}
</label>
<SettingsInput
id="company-invite-email"
type="email"
placeholder={t('members_invite_email_placeholder')}
value={inviteEmail}
onChange={(e) => setInviteEmail(e.target.value)}
disabled={isSending}
required
className="border-border sm:flex-1"
/>
<SettingsSelect
value={inviteRole}
onChange={(e) => setInviteRole(e.target.value)}
aria-label={t('members_invite_email_label')}
>
<option value="viewer">{t('members_role_viewer')}</option>
<option value="member">{t('members_role_member')}</option>
<option value="admin">{t('members_role_admin')}</option>
</SettingsSelect>
<Button type="submit" size="sm" disabled={isSending || !inviteEmail.trim()}>
{isSending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<Plus className="mr-2 h-4 w-4" />
{t('members_invite_button')}
</>
)}
</Button>
</form>
)}
</div>
<p className="px-1 pt-3">
<SettingsRowNote>
{t('members_count', { count: members.length, companyName: company?.name ?? '' })}
</SettingsRowNote>
</p>
</SettingsGroup>
)
}
+48 -49
View File
@@ -7,10 +7,14 @@ import { useCompany } from '@/contexts/CompanyContext'
import { CompanyProfileView } from '@/components/settings/CompanyProfileView'
import { refreshCompanyProfileAction } from '@/lib/company/tic-refresh'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import {
SettingsGroup,
SettingsInput,
SettingsRow,
SettingsRowNote,
} from '@/components/settings/SettingsRows'
import { formatDateLong } from '@/lib/utils'
type Snapshot = Parameters<typeof CompanyProfileView>[0]['snapshot']
@@ -24,9 +28,9 @@ const ERROR_MESSAGES: Record<string, string> = {
// Företagsprofil: the cached TIC company snapshot (Bolagsuppgifter), rendered
// as a read-only section on the Företag tab. Fetched client-side (low-traffic
// settings) so it sits alongside the client-rendered company form. RLS scopes
// the read to the user's own company. The "Hämta" form lets the user (re)fetch
// live when the snapshot is missing or wrong: the recovery path for an enskild
// firma whose personnummer previously resolved to the wrong entity.
// the read to the user's own company. The trailing "Hämta" row lets the user
// (re)fetch live when the snapshot is missing or wrong: the recovery path for
// an enskild firma whose personnummer previously resolved to the wrong entity.
export function CompanyProfileSection() {
const { company } = useCompany()
const [snapshot, setSnapshot] = useState<Snapshot>(null)
@@ -76,49 +80,44 @@ export function CompanyProfileSection() {
if (loading) return <Skeleton className="h-48 w-full rounded-lg" />
return (
<div className="space-y-4">
<CompanyProfileView snapshot={snapshot} fetchedAt={fetchedAt} />
<SettingsGroup label="Bolagsuppgifter">
<CompanyProfileView snapshot={snapshot} />
<Card>
<CardHeader>
<CardTitle className="text-base">
{snapshot ? 'Uppdatera bolagsuppgifter' : 'Hämta bolagsuppgifter'}
</CardTitle>
</CardHeader>
<CardContent>
<form onSubmit={handleFetch} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="tic_org_number">Organisationsnummer eller personnummer</Label>
<div className="flex gap-2">
<Input
id="tic_org_number"
value={orgInput}
onChange={(e) => setOrgInput(e.target.value)}
placeholder="XXXXXX-XXXX"
inputMode="numeric"
autoComplete="off"
className="max-w-xs tabular-nums"
/>
<Button type="submit" disabled={submitting || !orgInput.trim()}>
{submitting ? (
<>
<Loader2 className="animate-spin" />
Hämtar…
</>
) : (
'Hämta'
)}
</Button>
</div>
<p className="text-xs text-muted-foreground">
Uppgifterna hämtas från Bolagsverket. För enskild firma anges
personnumret.
</p>
{error && <p className="text-sm text-destructive">{error}</p>}
</div>
</form>
</CardContent>
</Card>
</div>
<SettingsRow
label={snapshot ? 'Uppdatera bolagsuppgifter' : 'Hämta bolagsuppgifter'}
help="Uppgifterna hämtas från Bolagsverket. För enskild firma anges personnumret."
borderless
>
<form
onSubmit={handleFetch}
className="flex min-w-0 flex-1 flex-wrap items-center gap-x-3 gap-y-1"
>
<SettingsInput
id="tic_org_number"
aria-label="Organisationsnummer eller personnummer"
value={orgInput}
onChange={(e) => setOrgInput(e.target.value)}
placeholder="XXXXXX-XXXX"
inputMode="numeric"
autoComplete="off"
className="max-w-xs tabular-nums"
/>
<Button type="submit" size="sm" disabled={submitting || !orgInput.trim()}>
{submitting ? (
<>
<Loader2 className="animate-spin" />
Hämtar…
</>
) : (
'Hämta'
)}
</Button>
{fetchedAt && (
<SettingsRowNote>Uppdaterad {formatDateLong(fetchedAt)}</SettingsRowNote>
)}
{error && <span className="basis-full text-xs text-destructive">{error}</span>}
</form>
</SettingsRow>
</SettingsGroup>
)
}
+147 -177
View File
@@ -1,9 +1,10 @@
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { formatDate, formatDateLong } from '@/lib/utils'
import { formatDate } from '@/lib/utils'
import { SettingsRow, SettingsRowNote } from '@/components/settings/SettingsRows'
// Read-only "Bolagsuppgifter" view of the cached TIC company profile
// (companies.tic_snapshot). Lives in core: reads the snapshot as plain
// (companies.tic_snapshot), rendered as flat settings rows inside the
// section's SettingsGroup. Lives in core: reads the snapshot as plain
// JSON rather than importing the TIC extension's types, so the
// core-build CI boundary (no core → @/extensions/) stays intact.
//
@@ -65,37 +66,14 @@ function cleanSignatory(raw: string): string[] {
.filter((s) => s.length > 0)
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section>
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mb-2">
{title}
</h2>
{children}
</section>
)
}
export function CompanyProfileView({
snapshot,
fetchedAt,
}: {
snapshot: SnapshotShape | null
fetchedAt: string | null
}) {
export function CompanyProfileView({ snapshot }: { snapshot: SnapshotShape | null }) {
if (!snapshot) {
// Dynamic status (nothing fetched yet): stays visible as a quiet line.
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Bolagsuppgifter</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Inga företagsuppgifter hämtade ännu. Uppgifterna hämtas automatiskt
från Bolagsverket via organisationsnumret.
</p>
</CardContent>
</Card>
<p className="border-b border-border px-1 py-3 text-sm text-muted-foreground">
Inga företagsuppgifter hämtade ännu. Uppgifterna hämtas automatiskt
från Bolagsverket via organisationsnumret.
</p>
)
}
@@ -118,164 +96,156 @@ export function CompanyProfileView({
? `${snapshot.fiscalYear.startMonthDay} till ${snapshot.fiscalYear.endMonthDay}`
: null
// Only show dated status entries: Bolagsverket emits informational
// flags like "Har aldrig varit verksam" with no date that read as
// noise next to the real ones. Plain text, no colour: per the
// design system, semantic colour is data-only and never chrome.
const datedStatuses = (snapshot.statuses ?? []).filter((s) => s.statusDate)
// Flatten every signatory row, clean ">" markers, split run-on
// clauses, and dedupe: the source repeats "Firman tecknas av
// styrelsen" across rows.
const signatoryRules = Array.from(
new Set(
(snapshot.signatory ?? []).flatMap((s) => cleanSignatory(s.description)),
),
)
return (
<Card>
<CardHeader>
<CardTitle className="text-base">Bolagsuppgifter</CardTitle>
{fetchedAt && (
<p className="text-xs text-muted-foreground">
Uppdaterad {formatDateLong(fetchedAt)}
</p>
)}
</CardHeader>
<CardContent className="space-y-8">
{/* Identity */}
<div>
<p className="font-display text-xl tracking-tight">
{snapshot.companyName ?? 'Okänt företag'}
</p>
<p className="text-sm text-muted-foreground tabular-nums">
<>
<SettingsRow label="Företag">
<span className="text-foreground">{snapshot.companyName ?? 'Okänt företag'}</span>
{(snapshot.orgNumber || entityLabel) && (
<SettingsRowNote className="tabular-nums">
{[snapshot.orgNumber, entityLabel].filter(Boolean).join(' · ')}
</p>
{snapshot.address && (
<p className="text-sm text-muted-foreground mt-2">
{[
snapshot.address.street,
[snapshot.address.postalCode, snapshot.address.city].filter(Boolean).join(' '),
]
.filter(Boolean)
.join(', ')}
</p>
)}
</div>
{regBadges.length > 0 && (
<Section title="Registrerat för">
<div className="flex flex-wrap gap-2">
{regBadges.map((b) => (
<Badge key={b} variant="secondary" className="font-normal">{b}</Badge>
))}
</div>
</Section>
</SettingsRowNote>
)}
</SettingsRow>
{Array.isArray(snapshot.sniCodes) && snapshot.sniCodes.length > 0 && (
<Section title="SNI-koder">
<ul className="space-y-1">
{snapshot.sniCodes.map((s) => (
<li key={s.code} className="text-sm tabular-nums">
<span className="text-foreground">{s.code}</span>{' '}
<span className="text-muted-foreground">{s.name}</span>
</li>
))}
</ul>
</Section>
)}
{snapshot.address && (
<SettingsRow label="Adress">
<span className="text-muted-foreground">
{[
snapshot.address.street,
[snapshot.address.postalCode, snapshot.address.city].filter(Boolean).join(' '),
]
.filter(Boolean)
.join(', ')}
</span>
</SettingsRow>
)}
{Array.isArray(snapshot.bankAccounts) && snapshot.bankAccounts.length > 0 && (
<Section title="Bankuppgifter">
<ul className="space-y-1">
{snapshot.bankAccounts.map((b, i) => (
<li key={`${b.type}-${b.accountNumber}-${i}`} className="text-sm tabular-nums">
<span className="text-muted-foreground">{b.type}:</span>{' '}
<span className="text-foreground">{b.accountNumber}</span>
</li>
))}
</ul>
</Section>
)}
{regBadges.length > 0 && (
<SettingsRow label="Registrerat för">
{regBadges.map((b) => (
<Badge key={b} variant="secondary" className="font-normal">{b}</Badge>
))}
</SettingsRow>
)}
{snapshot.purpose && (
<Section title="Verksamhet">
<p className="text-sm leading-6 text-muted-foreground">{snapshot.purpose}</p>
</Section>
)}
{Array.isArray(snapshot.sniCodes) && snapshot.sniCodes.length > 0 && (
<SettingsRow label="SNI-koder" align="baseline">
<ul className="w-full space-y-1">
{snapshot.sniCodes.map((s) => (
<li key={s.code} className="text-sm tabular-nums">
<span className="text-foreground">{s.code}</span>{' '}
<span className="text-muted-foreground">{s.name}</span>
</li>
))}
</ul>
</SettingsRow>
)}
<Section title="Anställda">
<p className="text-sm text-muted-foreground">
{snapshot.employeeRange ?? 'Inga anställda'}
</p>
</Section>
{Array.isArray(snapshot.bankAccounts) && snapshot.bankAccounts.length > 0 && (
<SettingsRow label="Bankuppgifter" align="baseline">
<ul className="w-full space-y-1">
{snapshot.bankAccounts.map((b, i) => (
<li key={`${b.type}-${b.accountNumber}-${i}`} className="text-sm tabular-nums">
<span className="text-muted-foreground">{b.type}:</span>{' '}
<span className="text-foreground">{b.accountNumber}</span>
</li>
))}
</ul>
</SettingsRow>
)}
<Section title="Senaste bokslut">
{snapshot.financials ? (
<dl className="grid grid-cols-2 gap-x-6 gap-y-1 text-sm">
<dt className="text-muted-foreground">Nettoomsättning</dt>
<dd className="text-right tabular-nums">
{snapshot.purpose && (
<SettingsRow label="Verksamhet" align="baseline">
<p className="text-sm leading-6 text-muted-foreground">{snapshot.purpose}</p>
</SettingsRow>
)}
<SettingsRow label="Anställda">
<span className="text-muted-foreground">
{snapshot.employeeRange ?? 'Inga anställda'}
</span>
</SettingsRow>
<SettingsRow label="Senaste bokslut">
{snapshot.financials ? (
<>
<span>
<span className="text-muted-foreground">Nettoomsättning </span>
<span className="tabular-nums">
{snapshot.financials.netSalesK != null
? `${snapshot.financials.netSalesK.toLocaleString('sv-SE')} tkr`
: '-'}
</dd>
<dt className="text-muted-foreground">Rörelseresultat</dt>
<dd className="text-right tabular-nums">
</span>
</span>
<span>
<span className="text-muted-foreground">Rörelseresultat </span>
<span className="tabular-nums">
{snapshot.financials.operatingProfitK != null
? `${snapshot.financials.operatingProfitK.toLocaleString('sv-SE')} tkr`
: '-'}
</dd>
</dl>
) : (
<p className="text-sm text-muted-foreground">Inga finansiella uppgifter tillgängliga.</p>
)}
</Section>
{(() => {
// Only show dated status entries: Bolagsverket emits informational
// flags like "Har aldrig varit verksam" with no date that read as
// noise next to the real ones. Plain text, no colour: per the
// design system, semantic colour is data-only and never chrome.
const datedStatuses = (snapshot.statuses ?? []).filter((s) => s.statusDate)
if (datedStatuses.length === 0) return null
return (
<Section title="Status">
<dl className="space-y-1">
{datedStatuses.map((s, i) => (
<div key={`${s.code}-${i}`} className="flex items-center justify-between gap-3 text-sm">
<dt className={s.isCeased ? 'text-destructive' : 'text-foreground'}>
{s.description ?? s.code ?? '-'}
</dt>
<dd className="text-xs text-muted-foreground tabular-nums">
{formatDate(s.statusDate!)}
</dd>
</div>
))}
</dl>
</Section>
)
})()}
{fyLabel && (
<Section title="Räkenskapsår">
<p className="text-sm tabular-nums text-muted-foreground">Nuvarande: {fyLabel}</p>
</Section>
</span>
</span>
</>
) : (
<span className="text-muted-foreground">Inga finansiella uppgifter tillgängliga.</span>
)}
</SettingsRow>
{(() => {
// Flatten every signatory row, clean ">" markers, split run-on
// clauses, and dedupe: the source repeats "Firman tecknas av
// styrelsen" across rows.
const rules = Array.from(
new Set(
(snapshot.signatory ?? []).flatMap((s) => cleanSignatory(s.description)),
),
)
if (rules.length === 0) return null
return (
<Section title="Firmateckning">
<ul className="space-y-1.5">
{rules.map((rule, i) => (
<li key={i} className="text-sm leading-6 text-muted-foreground">
{rule}
</li>
))}
</ul>
</Section>
)
})()}
{datedStatuses.length > 0 && (
<SettingsRow label="Status" align="baseline">
<dl className="w-full space-y-1">
{datedStatuses.map((s, i) => (
<div key={`${s.code}-${i}`} className="flex items-center justify-between gap-3 text-sm">
<dt className={s.isCeased ? 'text-destructive' : 'text-foreground'}>
{s.description ?? s.code ?? '-'}
</dt>
<dd className="text-xs text-muted-foreground tabular-nums">
{formatDate(s.statusDate!)}
</dd>
</div>
))}
</dl>
</SettingsRow>
)}
{Array.isArray(snapshot.representatives) && snapshot.representatives.length > 0 && (
<Section title="Företrädare">
{fyLabel && (
<SettingsRow label="Räkenskapsår">
<span className="tabular-nums text-muted-foreground">Nuvarande: {fyLabel}</span>
</SettingsRow>
)}
{signatoryRules.length > 0 && (
<SettingsRow label="Firmateckning" align="baseline">
<ul className="w-full space-y-1">
{signatoryRules.map((rule, i) => (
<li key={i} className="text-sm leading-6 text-muted-foreground">
{rule}
</li>
))}
</ul>
</SettingsRow>
)}
{Array.isArray(snapshot.representatives) && snapshot.representatives.length > 0 && (
<SettingsRow label="Företrädare" align="baseline">
<div className="w-full">
{snapshot.board && (
<p className="text-xs text-muted-foreground mb-2">
<p className="mb-2 text-xs text-muted-foreground">
{[
snapshot.board.numberOfBoardMembers != null
? `${snapshot.board.numberOfBoardMembers} styrelseledamot/-ledamöter`
@@ -292,7 +262,7 @@ export function CompanyProfileView({
{snapshot.representatives.map((r, i) => (
<li key={`${r.name}-${i}`} className="flex items-center justify-between gap-3 text-sm">
<span className="text-foreground">{r.name ?? '-'}</span>
<span className="text-xs text-muted-foreground text-right">
<span className="text-right text-xs text-muted-foreground">
{[r.positionType, r.positionStart ? formatDate(r.positionStart) : null]
.filter(Boolean)
.join(' · ')}
@@ -300,9 +270,9 @@ export function CompanyProfileView({
</li>
))}
</ul>
</Section>
)}
</CardContent>
</Card>
</div>
</SettingsRow>
)}
</>
)
}
+138 -154
View File
@@ -2,10 +2,10 @@
import { useTranslations } from 'next-intl'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { EmptyState } from '@/components/ui/empty-state'
import { useToast } from '@/components/ui/use-toast'
import { SettingsGroup } from '@/components/settings/SettingsRows'
import { Loader2, Trash2, Users, ChevronDown } from 'lucide-react'
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
import { formatCounterpartyName } from '@/lib/bookkeeping/counterparty-templates'
@@ -92,166 +92,150 @@ export function CounterpartyTemplatesPanel() {
}
return (
<div className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base">{t('title')}</CardTitle>
<CardDescription>
{t('description')}
</CardDescription>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : templates.length === 0 ? (
<EmptyState
icon={Users}
title={t('empty_title')}
description={t('empty_help')}
/>
) : (
<div className="space-y-1">
{templates.map((tt) => {
const isExpanded = expandedId === tt.id
const isMultiLine = tt.line_pattern && tt.line_pattern.length > 0
<SettingsGroup label={t('title')} help={t('description')}>
{isLoading ? (
<div className="flex items-center justify-center py-8">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
) : templates.length === 0 ? (
<EmptyState
icon={Users}
title={t('empty_title')}
description={t('empty_help')}
/>
) : (
templates.map((tt) => {
const isExpanded = expandedId === tt.id
const isMultiLine = tt.line_pattern && tt.line_pattern.length > 0
return (
<div key={tt.id} className="rounded-md border overflow-hidden">
{/* Clickable summary row */}
<button
type="button"
onClick={() => setExpandedId(isExpanded ? null : tt.id)}
className="w-full text-left px-4 py-3 flex items-center gap-3 hover:bg-muted/50 transition-colors"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="text-sm font-medium truncate">{formatCounterpartyName(tt.counterparty_name)}</p>
</div>
<div className="flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground">
{isMultiLine ? (
<span className="font-mono">
{tt.line_pattern!.filter(lp => lp.type === 'business').map(lp => lp.account).join(', ')}
return (
<div key={tt.id} className="border-b border-border">
{/* Clickable summary row: flat hairline, one line. */}
<button
type="button"
onClick={() => setExpandedId(isExpanded ? null : tt.id)}
aria-expanded={isExpanded}
className="flex w-full items-center gap-3 px-1 py-3 text-left transition-colors duration-150 hover:bg-secondary/60"
>
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-3 gap-y-1">
<span className="truncate text-sm">{formatCounterpartyName(tt.counterparty_name)}</span>
<span className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{isMultiLine ? (
<span className="font-mono">
{tt.line_pattern!.filter(lp => lp.type === 'business').map(lp => lp.account).join(', ')}
</span>
) : (
<span className="font-mono">
{tt.debit_account}
<span className="text-muted-foreground/50"> → </span>
{tt.credit_account}
</span>
)}
{tt.vat_treatment && (
<span>· {VAT_LABELS[tt.vat_treatment] || tt.vat_treatment}</span>
)}
<span>· {t('times_count', { count: tt.occurrence_count })}</span>
<span className={`tabular-nums ${confidenceColor(Number(tt.confidence))}`}>
{Math.round(Number(tt.confidence) * 100)}%
</span>
<span>· {SOURCE_LABELS[tt.source] || tt.source}</span>
</span>
</div>
<ChevronDown
className={`h-4 w-4 shrink-0 text-muted-foreground transition-transform ${isExpanded ? 'rotate-180' : ''}`}
/>
</button>
{/* Expanded detail */}
{isExpanded && (
<div className="space-y-3 px-1 pb-3">
{/* Account lines */}
<div>
<p className="mb-2 text-[10px] font-medium uppercase tracking-wider text-muted-foreground">{t('booking_label')}</p>
{isMultiLine ? (
<div className="space-y-1">
{tt.line_pattern!.map((lp, i) => (
<div key={i} className="flex items-center gap-2 text-xs">
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">
{lp.side === 'debit' ? t('debit_label') : t('credit_label')}
</span>
) : (
<>
<span className="font-mono">{tt.debit_account}</span>
<span className="text-muted-foreground/50">→</span>
<span className="font-mono">{tt.credit_account}</span>
</>
)}
{tt.vat_treatment && (
<>
<span className="text-muted-foreground/30">·</span>
<span>{VAT_LABELS[tt.vat_treatment] || tt.vat_treatment}</span>
</>
)}
<span className="text-muted-foreground/30">·</span>
<span>{t('times_count', { count: tt.occurrence_count })}</span>
<span className={`tabular-nums ${confidenceColor(Number(tt.confidence))}`}>
{Math.round(Number(tt.confidence) * 100)}%
</span>
<span className="text-muted-foreground/30">·</span>
<span>{SOURCE_LABELS[tt.source] || tt.source}</span>
</div>
</div>
<ChevronDown className={`h-4 w-4 text-muted-foreground shrink-0 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
</button>
{/* Expanded detail */}
{isExpanded && (
<div className="border-t bg-muted/30 px-4 py-3 space-y-3">
{/* Account lines */}
<div>
<p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1.5">{t('booking_label')}</p>
{isMultiLine ? (
<div className="space-y-1">
{tt.line_pattern!.map((lp, i) => (
<div key={i} className="flex items-center gap-2 text-xs">
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">
{lp.side === 'debit' ? t('debit_label') : t('credit_label')}
</span>
<span className="font-mono">{formatAccountWithName(lp.account)}</span>
{lp.type === 'vat' && lp.vat_rate && (
<span className="text-muted-foreground">{t('vat_paren', { rate: Math.round(lp.vat_rate * 100) })}</span>
)}
{lp.ratio !== undefined && (
<span className="text-muted-foreground">({Math.round(lp.ratio * 100)}%)</span>
)}
</div>
))}
</div>
) : (
<div className="space-y-1">
<div className="flex items-center gap-2 text-xs">
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">{t('debit_label')}</span>
<span className="font-mono">{formatAccountWithName(tt.debit_account)}</span>
</div>
<div className="flex items-center gap-2 text-xs">
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">{t('credit_label')}</span>
<span className="font-mono">{formatAccountWithName(tt.credit_account)}</span>
</div>
</div>
)}
</div>
{/* Metadata */}
<div className="grid grid-cols-2 gap-x-6 gap-y-1 text-xs">
{tt.vat_treatment && (
<div className="flex justify-between">
<span className="text-muted-foreground">{t('vat_label')}</span>
<span>{VAT_LABELS[tt.vat_treatment] || tt.vat_treatment}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">{t('occurrence_count_label')}</span>
<span className="tabular-nums">{tt.occurrence_count}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">{t('confidence_label')}</span>
<span className={`tabular-nums ${confidenceColor(Number(tt.confidence))}`}>
{Math.round(Number(tt.confidence) * 100)}%
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">{t('last_seen_label')}</span>
<span>{formatDate(tt.last_seen_date)}</span>
</div>
{tt.counterparty_aliases && tt.counterparty_aliases.length > 1 && (
<div className="col-span-2 flex justify-between">
<span className="text-muted-foreground">{t('aliases_label')}</span>
<span className="text-right truncate ml-4">{tt.counterparty_aliases.slice(0, 3).join(', ')}{tt.counterparty_aliases.length > 3 ? ` +${tt.counterparty_aliases.length - 3}` : ''}</span>
</div>
)}
</div>
{/* Delete */}
<div className="flex justify-end pt-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(tt.id)}
disabled={deletingId === tt.id}
className="text-destructive hover:text-destructive text-xs h-7"
>
{deletingId === tt.id ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
) : (
<Trash2 className="mr-1.5 h-3 w-3" />
<span className="font-mono">{formatAccountWithName(lp.account)}</span>
{lp.type === 'vat' && lp.vat_rate && (
<span className="text-muted-foreground">{t('vat_paren', { rate: Math.round(lp.vat_rate * 100) })}</span>
)}
{t('delete_button')}
</Button>
{lp.ratio !== undefined && (
<span className="text-muted-foreground">({Math.round(lp.ratio * 100)}%)</span>
)}
</div>
))}
</div>
) : (
<div className="space-y-1">
<div className="flex items-center gap-2 text-xs">
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">{t('debit_label')}</span>
<span className="font-mono">{formatAccountWithName(tt.debit_account)}</span>
</div>
<div className="flex items-center gap-2 text-xs">
<span className="w-14 shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">{t('credit_label')}</span>
<span className="font-mono">{formatAccountWithName(tt.credit_account)}</span>
</div>
</div>
)}
</div>
)
})}
{/* Metadata */}
<div className="grid grid-cols-2 gap-x-6 gap-y-1 text-xs">
{tt.vat_treatment && (
<div className="flex justify-between">
<span className="text-muted-foreground">{t('vat_label')}</span>
<span>{VAT_LABELS[tt.vat_treatment] || tt.vat_treatment}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">{t('occurrence_count_label')}</span>
<span className="tabular-nums">{tt.occurrence_count}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">{t('confidence_label')}</span>
<span className={`tabular-nums ${confidenceColor(Number(tt.confidence))}`}>
{Math.round(Number(tt.confidence) * 100)}%
</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">{t('last_seen_label')}</span>
<span>{formatDate(tt.last_seen_date)}</span>
</div>
{tt.counterparty_aliases && tt.counterparty_aliases.length > 1 && (
<div className="col-span-2 flex justify-between">
<span className="text-muted-foreground">{t('aliases_label')}</span>
<span className="ml-4 truncate text-right">{tt.counterparty_aliases.slice(0, 3).join(', ')}{tt.counterparty_aliases.length > 3 ? ` +${tt.counterparty_aliases.length - 3}` : ''}</span>
</div>
)}
</div>
{/* Delete */}
<div className="flex justify-end pt-1">
<Button
variant="ghost"
size="sm"
onClick={() => handleDelete(tt.id)}
disabled={deletingId === tt.id}
className="h-7 text-xs text-destructive hover:text-destructive"
>
{deletingId === tt.id ? (
<Loader2 className="mr-1.5 h-3 w-3 animate-spin" />
) : (
<Trash2 className="mr-1.5 h-3 w-3" />
)}
{t('delete_button')}
</Button>
</div>
</div>
)}
</div>
)}
</CardContent>
</Card>
</div>
)
})
)}
</SettingsGroup>
)
}

Some files were not shown because too many files have changed in this diff Show More