diff --git a/app/(dashboard)/receipts/page.tsx b/app/(dashboard)/receipts/page.tsx index 4aad8998..aefd4cb6 100644 --- a/app/(dashboard)/receipts/page.tsx +++ b/app/(dashboard)/receipts/page.tsx @@ -1 +1 @@ -export { default } from '@/extensions/receipt-ocr/pages/ReceiptsPage' +export { default } from '@/extensions/general/receipt-ocr/pages/ReceiptsPage' diff --git a/app/(dashboard)/receipts/scan/page.tsx b/app/(dashboard)/receipts/scan/page.tsx index 3d99fe62..c185df95 100644 --- a/app/(dashboard)/receipts/scan/page.tsx +++ b/app/(dashboard)/receipts/scan/page.tsx @@ -1 +1 @@ -export { default } from '@/extensions/receipt-ocr/pages/scan/ScanReceiptPage' +export { default } from '@/extensions/general/receipt-ocr/pages/scan/ScanReceiptPage' diff --git a/app/(dashboard)/settings/page.tsx b/app/(dashboard)/settings/page.tsx index 21024c0b..a837df74 100644 --- a/app/(dashboard)/settings/page.tsx +++ b/app/(dashboard)/settings/page.tsx @@ -24,7 +24,7 @@ import { Calendar, } from 'lucide-react' import type { CompanySettings, BankConnection } from '@/types' -import { NotificationSettings } from '@/extensions/push-notifications/NotificationSettings' +import { NotificationSettings } from '@/extensions/general/push-notifications/NotificationSettings' import { CalendarFeedSettings } from '@/components/settings/CalendarFeedSettings' export default function SettingsPage() { diff --git a/app/(onboarding)/onboarding/page.tsx b/app/(onboarding)/onboarding/page.tsx index 75539010..1c6e9507 100644 --- a/app/(onboarding)/onboarding/page.tsx +++ b/app/(onboarding)/onboarding/page.tsx @@ -1,10 +1,9 @@ 'use client' -import { useState, useEffect, useMemo, Suspense } from 'react' +import { useState, useEffect, Suspense } from 'react' import { useRouter, useSearchParams } from 'next/navigation' import { createClient } from '@/lib/supabase/client' import { Progress } from '@/components/ui/progress' -import { Button } from '@/components/ui/button' import { useToast } from '@/components/ui/use-toast' import { Loader2 } from 'lucide-react' import type { CompanySettings, EntityType, MomsPeriod } from '@/types' @@ -13,13 +12,18 @@ import Step1EntityType from '@/components/onboarding/Step1EntityType' import Step2CompanyDetails from '@/components/onboarding/Step2CompanyDetails' import Step3TaxRegistration from '@/components/onboarding/Step3TaxRegistration' import Step4PreliminaryTax from '@/components/onboarding/Step4PreliminaryTax' -import Step6ConnectBank from '@/components/onboarding/Step6ConnectBank' +import Step5ConnectBank from '@/components/onboarding/Step6ConnectBank' +import Step6SectorSelection from '@/components/onboarding/Step2SectorSelection' +import Step7ExtensionSuggestions from '@/components/onboarding/Step3ExtensionSuggestions' + const STEP_TITLES = [ 'Verksamhetsform', 'Företagsuppgifter', 'Skatteregistrering', 'F-skatt', 'Anslut bank', + 'Bransch', + 'Tillägg', ] export default function OnboardingPage() { @@ -40,8 +44,9 @@ function OnboardingPageContent() { const [isSaving, setIsSaving] = useState(false) const [currentStep, setCurrentStep] = useState(1) const [settings, setSettings] = useState>({}) + const [sectorSlug, setSectorSlug] = useState(null) - const totalSteps = 5 + const totalSteps = 7 const stepTitles = STEP_TITLES // Load existing settings on mount @@ -63,6 +68,9 @@ function OnboardingPageContent() { if (data) { setSettings(data) setCurrentStep(data.onboarding_step || 1) + if ((data as Record).sector_slug) { + setSectorSlug((data as Record).sector_slug as string) + } } setIsLoading(false) @@ -74,13 +82,13 @@ function OnboardingPageContent() { // Handle bank_connected callback from PSD2 flow useEffect(() => { if (searchParams.get('bank_connected') === 'true') { - saveSettings({ onboarding_complete: true }).then((success) => { + toast({ + title: 'Bank ansluten!', + description: 'Din bank har kopplats.', + }) + saveSettings({}, 6).then((success) => { if (success) { - toast({ - title: 'Bank ansluten!', - description: 'Din bank är kopplad och profilen är redo.', - }) - router.push('/') + setCurrentStep(6) } }) } @@ -205,18 +213,6 @@ function OnboardingPageContent() { } } - const handleComplete = async () => { - const success = await saveSettings({ onboarding_complete: true }) - - if (success) { - toast({ - title: 'Välkommen!', - description: 'Din profil är nu redo.', - }) - router.push('/') - } - } - if (isLoading) { return (
@@ -227,6 +223,41 @@ function OnboardingPageContent() { const progressPercent = ((currentStep - 1) / (totalSteps - 1)) * 100 + const handleSectorNext = async (data: { sector_slug: string | null }) => { + setSectorSlug(data.sector_slug) + const nextStep = currentStep + 1 + const settingsUpdate: Partial = {} + if (data.sector_slug) { + ;(settingsUpdate as Record).sector_slug = data.sector_slug + } + const success = await saveSettings(settingsUpdate, nextStep) + if (success) { + setCurrentStep(nextStep) + } + } + + const handleExtensionsNext = async (data: { enabled_extensions: { sector_slug: string; extension_slug: string }[] }) => { + // Insert extension toggles if any were selected + if (data.enabled_extensions.length > 0) { + try { + const { data: { user } } = await supabase.auth.getUser() + if (user) { + const rows = data.enabled_extensions.map(ext => ({ + user_id: user.id, + sector_slug: ext.sector_slug, + extension_slug: ext.extension_slug, + enabled: true, + })) + await supabase.from('extension_toggles').upsert(rows, { + onConflict: 'user_id,sector_slug,extension_slug', + }) + } + } catch (err) { + console.error('Failed to save extension toggles:', err) + } + } + } + const renderSteps = () => ( <> {currentStep === 1 && ( @@ -281,7 +312,7 @@ function OnboardingPageContent() { )} {currentStep === 5 && ( - { if (data) { - await saveSettings({ ...data, onboarding_complete: true }) - } else { - await saveSettings({ onboarding_complete: true }) + await saveSettings(data, 6) } + setCurrentStep(6) + }} + onBack={handleBack} + onSkip={() => setCurrentStep(6)} + isSaving={isSaving} + /> + )} + + {currentStep === 6 && ( + + )} + + {currentStep === 7 && ( + { + await handleExtensionsNext(data) + await saveSettings({ onboarding_complete: true }, totalSteps) toast({ title: 'Välkommen!', description: 'Din profil är nu redo.', @@ -302,7 +353,6 @@ function OnboardingPageContent() { router.push('/') }} onBack={handleBack} - onSkip={handleComplete} isSaving={isSaving} /> )} diff --git a/app/api/extensions/[sector]/[slug]/data/route.ts b/app/api/extensions/[sector]/[slug]/data/route.ts new file mode 100644 index 00000000..f9d346c8 --- /dev/null +++ b/app/api/extensions/[sector]/[slug]/data/route.ts @@ -0,0 +1,115 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' + +export async function GET( + request: Request, + { params }: { params: Promise<{ sector: string; slug: string }> } +) { + const { sector, slug } = await params + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const extensionId = `${sector}/${slug}` + + const { searchParams } = new URL(request.url) + const key = searchParams.get('key') + + let query = supabase + .from('extension_data') + .select('*') + .eq('user_id', user.id) + .eq('extension_id', extensionId) + + if (key) { + query = query.eq('key', key) + } + + const { data, error } = await query + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + return NextResponse.json({ data }) +} + +export async function POST( + request: Request, + { params }: { params: Promise<{ sector: string; slug: string }> } +) { + const { sector, slug } = await params + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const body = await request.json() + const { key, value } = body + + if (!key) { + return NextResponse.json({ error: 'key is required' }, { status: 400 }) + } + + const extensionId = `${sector}/${slug}` + + const { data, error } = await supabase + .from('extension_data') + .upsert( + { + user_id: user.id, + extension_id: extensionId, + key, + value, + }, + { onConflict: 'user_id,extension_id,key' } + ) + .select() + .single() + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + return NextResponse.json({ data }) +} + +export async function DELETE( + request: Request, + { params }: { params: Promise<{ sector: string; slug: string }> } +) { + const { sector, slug } = await params + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const { searchParams } = new URL(request.url) + const key = searchParams.get('key') + + if (!key) { + return NextResponse.json({ error: 'key query parameter is required' }, { status: 400 }) + } + + const extensionId = `${sector}/${slug}` + + const { error } = await supabase + .from('extension_data') + .delete() + .eq('user_id', user.id) + .eq('extension_id', extensionId) + .eq('key', key) + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + return NextResponse.json({ success: true }) +} diff --git a/app/api/extensions/[sector]/[slug]/settings/route.ts b/app/api/extensions/[sector]/[slug]/settings/route.ts new file mode 100644 index 00000000..5339166e --- /dev/null +++ b/app/api/extensions/[sector]/[slug]/settings/route.ts @@ -0,0 +1,74 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' + +export async function GET( + _request: Request, + { params }: { params: Promise<{ sector: string; slug: string }> } +) { + const { sector, slug } = await params + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const extensionId = `${sector}/${slug}` + + const { data } = await supabase + .from('extension_data') + .select('value') + .eq('user_id', user.id) + .eq('extension_id', extensionId) + .eq('key', 'settings') + .single() + + return NextResponse.json({ data: data?.value ?? {} }) +} + +export async function PATCH( + request: Request, + { params }: { params: Promise<{ sector: string; slug: string }> } +) { + const { sector, slug } = await params + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const body = await request.json() + const extensionId = `${sector}/${slug}` + + // Get existing settings and merge + const { data: existing } = await supabase + .from('extension_data') + .select('value') + .eq('user_id', user.id) + .eq('extension_id', extensionId) + .eq('key', 'settings') + .single() + + const mergedSettings = { ...(existing?.value ?? {}), ...body } + + const { data, error } = await supabase + .from('extension_data') + .upsert( + { + user_id: user.id, + extension_id: extensionId, + key: 'settings', + value: mergedSettings, + }, + { onConflict: 'user_id,extension_id,key' } + ) + .select() + .single() + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + return NextResponse.json({ data: data.value }) +} diff --git a/app/api/extensions/ai-categorization/settings/route.ts b/app/api/extensions/ai-categorization/settings/route.ts index 0c393628..9a76b945 100644 --- a/app/api/extensions/ai-categorization/settings/route.ts +++ b/app/api/extensions/ai-categorization/settings/route.ts @@ -1,6 +1,6 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { getSettings, saveSettings } from '@/extensions/ai-categorization' +import { getSettings, saveSettings } from '@/extensions/general/ai-categorization' /** * GET /api/extensions/ai-categorization/settings diff --git a/app/api/extensions/ai-categorization/suggestions/route.ts b/app/api/extensions/ai-categorization/suggestions/route.ts index 2fe4b2c2..c08a91c0 100644 --- a/app/api/extensions/ai-categorization/suggestions/route.ts +++ b/app/api/extensions/ai-categorization/suggestions/route.ts @@ -1,7 +1,7 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { categorizeTransactions } from '@/extensions/ai-categorization' -import type { CategorizationSuggestion } from '@/extensions/ai-categorization/categorizer' +import { categorizeTransactions } from '@/extensions/general/ai-categorization' +import type { CategorizationSuggestion } from '@/extensions/general/ai-categorization/categorizer' /** * GET /api/extensions/ai-categorization/suggestions?transaction_ids=id1,id2,... diff --git a/app/api/extensions/ai-chat/route.ts b/app/api/extensions/ai-chat/route.ts index 81cf364e..67f26416 100644 --- a/app/api/extensions/ai-chat/route.ts +++ b/app/api/extensions/ai-chat/route.ts @@ -1,7 +1,7 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { generateChatResponse } from '@/extensions/ai-chat/chatbot/chain' -import { CHATBOT_CONFIG } from '@/extensions/ai-chat/chatbot/config' +import { generateChatResponse } from '@/extensions/general/ai-chat/chatbot/chain' +import { CHATBOT_CONFIG } from '@/extensions/general/ai-chat/chatbot/config' import type { ChatMessage, ChatRequest } from '@/types/chat' // Simple in-memory rate limiting (per user) diff --git a/app/api/extensions/ai-chat/stream/route.ts b/app/api/extensions/ai-chat/stream/route.ts index 0edc89d3..bcf31bb3 100644 --- a/app/api/extensions/ai-chat/stream/route.ts +++ b/app/api/extensions/ai-chat/stream/route.ts @@ -1,6 +1,6 @@ import { createClient } from '@/lib/supabase/server' -import { streamChatResponse } from '@/extensions/ai-chat/chatbot/chain' -import { CHATBOT_CONFIG } from '@/extensions/ai-chat/chatbot/config' +import { streamChatResponse } from '@/extensions/general/ai-chat/chatbot/chain' +import { CHATBOT_CONFIG } from '@/extensions/general/ai-chat/chatbot/config' import type { ChatMessage, ChatRequest, SourceReference } from '@/types/chat' // Simple in-memory rate limiting (per user) diff --git a/app/api/extensions/enable-banking/callback/route.ts b/app/api/extensions/enable-banking/callback/route.ts index 431b7a92..497ed8be 100644 --- a/app/api/extensions/enable-banking/callback/route.ts +++ b/app/api/extensions/enable-banking/callback/route.ts @@ -1,7 +1,7 @@ import { createServiceClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { createSession, getAccountBalance, type AccountInfo } from '@/extensions/enable-banking/lib/api-client' -import type { StoredAccount } from '@/extensions/enable-banking/types' +import { createSession, getAccountBalance, type AccountInfo } from '@/extensions/general/enable-banking/lib/api-client' +import type { StoredAccount } from '@/extensions/general/enable-banking/types' /** * GET /api/extensions/enable-banking/callback diff --git a/app/api/extensions/enable-banking/sync/cron/route.ts b/app/api/extensions/enable-banking/sync/cron/route.ts index 0106692e..025b436d 100644 --- a/app/api/extensions/enable-banking/sync/cron/route.ts +++ b/app/api/extensions/enable-banking/sync/cron/route.ts @@ -1,8 +1,8 @@ import { createClient } from '@supabase/supabase-js' import { NextResponse } from 'next/server' -import { syncAccountTransactions } from '@/extensions/enable-banking/lib/sync' -import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/enable-banking/lib/api-client' -import type { StoredAccount } from '@/extensions/enable-banking/types' +import { syncAccountTransactions } from '@/extensions/general/enable-banking/lib/sync' +import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/general/enable-banking/lib/api-client' +import type { StoredAccount } from '@/extensions/general/enable-banking/types' /** * GET /api/extensions/enable-banking/sync/cron diff --git a/app/api/extensions/push-notifications/cron/route.ts b/app/api/extensions/push-notifications/cron/route.ts index 1c5cc5b6..12cc79ce 100644 --- a/app/api/extensions/push-notifications/cron/route.ts +++ b/app/api/extensions/push-notifications/cron/route.ts @@ -4,7 +4,7 @@ import { loadExtensions } from '@/lib/extensions/loader' import { sendTaxDeadlineNotifications, sendInvoiceNotifications, -} from '@/extensions/push-notifications/notification-scheduler' +} from '@/extensions/general/push-notifications/notification-scheduler' /** * GET /api/extensions/push-notifications/cron diff --git a/app/api/extensions/push-notifications/settings/route.ts b/app/api/extensions/push-notifications/settings/route.ts index 78891244..b9fecc7a 100644 --- a/app/api/extensions/push-notifications/settings/route.ts +++ b/app/api/extensions/push-notifications/settings/route.ts @@ -1,6 +1,6 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { getSettings, saveSettings } from '@/extensions/push-notifications' +import { getSettings, saveSettings } from '@/extensions/general/push-notifications' /** * GET /api/extensions/push-notifications/settings diff --git a/app/api/extensions/push-notifications/subscribe/route.ts b/app/api/extensions/push-notifications/subscribe/route.ts index 50e226c3..deddb7bf 100644 --- a/app/api/extensions/push-notifications/subscribe/route.ts +++ b/app/api/extensions/push-notifications/subscribe/route.ts @@ -1,6 +1,6 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { getVapidPublicKey } from '@/extensions/push-notifications/notification-sender' +import { getVapidPublicKey } from '@/extensions/general/push-notifications/notification-sender' /** * GET /api/extensions/push-notifications/subscribe diff --git a/app/api/extensions/receipt-ocr/[id]/match/route.ts b/app/api/extensions/receipt-ocr/[id]/match/route.ts index 1eff3cbe..00a1158b 100644 --- a/app/api/extensions/receipt-ocr/[id]/match/route.ts +++ b/app/api/extensions/receipt-ocr/[id]/match/route.ts @@ -1,6 +1,6 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { findTransactionMatches } from '@/extensions/receipt-ocr/lib/receipt-matcher' +import { findTransactionMatches } from '@/extensions/general/receipt-ocr/lib/receipt-matcher' import { eventBus } from '@/lib/events/bus' import { ensureInitialized } from '@/lib/init' import type { Receipt, Transaction } from '@/types' diff --git a/app/api/extensions/receipt-ocr/settings/route.ts b/app/api/extensions/receipt-ocr/settings/route.ts index d633785b..3562786a 100644 --- a/app/api/extensions/receipt-ocr/settings/route.ts +++ b/app/api/extensions/receipt-ocr/settings/route.ts @@ -1,6 +1,6 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { getSettings, saveSettings } from '@/extensions/receipt-ocr' +import { getSettings, saveSettings } from '@/extensions/general/receipt-ocr' /** * GET /api/extensions/receipt-ocr/settings diff --git a/app/api/extensions/receipt-ocr/upload/route.ts b/app/api/extensions/receipt-ocr/upload/route.ts index acb4f047..26af4ac7 100644 --- a/app/api/extensions/receipt-ocr/upload/route.ts +++ b/app/api/extensions/receipt-ocr/upload/route.ts @@ -1,7 +1,7 @@ import { createClient } from '@/lib/supabase/server' import { NextResponse } from 'next/server' -import { analyzeReceipt } from '@/extensions/receipt-ocr/lib/receipt-analyzer' -import { processLineItems } from '@/extensions/receipt-ocr/lib/receipt-categorizer' +import { analyzeReceipt } from '@/extensions/general/receipt-ocr/lib/receipt-analyzer' +import { processLineItems } from '@/extensions/general/receipt-ocr/lib/receipt-categorizer' import { eventBus } from '@/lib/events/bus' import { ensureInitialized } from '@/lib/init' import { uploadDocument } from '@/lib/core/documents/document-service' diff --git a/app/api/extensions/toggles/[sector]/[slug]/route.ts b/app/api/extensions/toggles/[sector]/[slug]/route.ts new file mode 100644 index 00000000..7b326dc8 --- /dev/null +++ b/app/api/extensions/toggles/[sector]/[slug]/route.ts @@ -0,0 +1,51 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' + +export async function GET( + _request: Request, + { params }: { params: Promise<{ sector: string; slug: string }> } +) { + const { sector, slug } = await params + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const { data } = await supabase + .from('extension_toggles') + .select('*') + .eq('user_id', user.id) + .eq('sector_slug', sector) + .eq('extension_slug', slug) + .single() + + return NextResponse.json({ data: data ?? { enabled: false } }) +} + +export async function DELETE( + _request: Request, + { params }: { params: Promise<{ sector: string; slug: string }> } +) { + const { sector, slug } = await params + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const { error } = await supabase + .from('extension_toggles') + .delete() + .eq('user_id', user.id) + .eq('sector_slug', sector) + .eq('extension_slug', slug) + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + return NextResponse.json({ success: true }) +} diff --git a/app/api/extensions/toggles/__tests__/route.test.ts b/app/api/extensions/toggles/__tests__/route.test.ts new file mode 100644 index 00000000..d49a6f95 --- /dev/null +++ b/app/api/extensions/toggles/__tests__/route.test.ts @@ -0,0 +1,105 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { + createMockRequest, + parseJsonResponse, + createQueuedMockSupabase, + makeExtensionToggle, +} from '@/tests/helpers' + +const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase() +vi.mock('@/lib/supabase/server', () => ({ + createClient: () => Promise.resolve(mockSupabase), +})) + +import { GET, POST } from '../route' + +describe('GET /api/extensions/toggles', () => { + const mockUser = { id: 'user-1', email: 'test@test.se' } + + beforeEach(() => { + vi.clearAllMocks() + reset() + mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } }) + }) + + it('returns 401 when not authenticated', async () => { + mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } }) + + const response = await GET() + const { status, body } = await parseJsonResponse(response) + + expect(status).toBe(401) + expect(body).toEqual({ error: 'Unauthorized' }) + }) + + it('returns enabled toggles for user', async () => { + const toggles = [ + makeExtensionToggle({ extension_slug: 'receipt-ocr' }), + makeExtensionToggle({ extension_slug: 'ai-chat' }), + ] + enqueue({ data: toggles, error: null }) + + const response = await GET() + const { status, body } = await parseJsonResponse<{ data: unknown[] }>(response) + + expect(status).toBe(200) + expect(body.data).toEqual(toggles) + expect(mockSupabase.from).toHaveBeenCalledWith('extension_toggles') + }) +}) + +describe('POST /api/extensions/toggles', () => { + const mockUser = { id: 'user-1', email: 'test@test.se' } + + beforeEach(() => { + vi.clearAllMocks() + reset() + mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } }) + }) + + it('returns 401 when not authenticated', async () => { + mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } }) + + const request = createMockRequest('/api/extensions/toggles', { + method: 'POST', + body: { sector_slug: 'general', extension_slug: 'receipt-ocr', enabled: true }, + }) + const response = await POST(request) + const { status, body } = await parseJsonResponse(response) + + expect(status).toBe(401) + expect(body).toEqual({ error: 'Unauthorized' }) + }) + + it('returns 400 when missing fields', async () => { + const request = createMockRequest('/api/extensions/toggles', { + method: 'POST', + body: { sector_slug: 'general' }, + }) + const response = await POST(request) + const { status, body } = await parseJsonResponse<{ error: string }>(response) + + expect(status).toBe(400) + expect(body.error).toBe('sector_slug, extension_slug, and enabled are required') + }) + + it('upserts toggle and returns data', async () => { + const toggle = makeExtensionToggle({ + sector_slug: 'general', + extension_slug: 'receipt-ocr', + enabled: true, + }) + enqueue({ data: toggle, error: null }) + + const request = createMockRequest('/api/extensions/toggles', { + method: 'POST', + body: { sector_slug: 'general', extension_slug: 'receipt-ocr', enabled: true }, + }) + const response = await POST(request) + const { status, body } = await parseJsonResponse<{ data: unknown }>(response) + + expect(status).toBe(200) + expect(body.data).toEqual(toggle) + expect(mockSupabase.from).toHaveBeenCalledWith('extension_toggles') + }) +}) diff --git a/app/api/extensions/toggles/route.ts b/app/api/extensions/toggles/route.ts new file mode 100644 index 00000000..62e4a6a8 --- /dev/null +++ b/app/api/extensions/toggles/route.ts @@ -0,0 +1,62 @@ +import { createClient } from '@/lib/supabase/server' +import { NextResponse } from 'next/server' + +export async function GET() { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const { data, error } = await supabase + .from('extension_toggles') + .select('*') + .eq('user_id', user.id) + .eq('enabled', true) + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + return NextResponse.json({ data }) +} + +export async function POST(request: Request) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + + if (!user) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) + } + + const body = await request.json() + const { sector_slug, extension_slug, enabled } = body + + if (!sector_slug || !extension_slug || typeof enabled !== 'boolean') { + return NextResponse.json( + { error: 'sector_slug, extension_slug, and enabled are required' }, + { status: 400 } + ) + } + + const { data, error } = await supabase + .from('extension_toggles') + .upsert( + { + user_id: user.id, + sector_slug, + extension_slug, + enabled, + }, + { onConflict: 'user_id,sector_slug,extension_slug' } + ) + .select() + .single() + + if (error) { + return NextResponse.json({ error: error.message }, { status: 500 }) + } + + return NextResponse.json({ data }) +} diff --git a/components/dashboard/DashboardNav.tsx b/components/dashboard/DashboardNav.tsx index bbdecbac..68dbe38b 100644 --- a/components/dashboard/DashboardNav.tsx +++ b/components/dashboard/DashboardNav.tsx @@ -1,6 +1,6 @@ 'use client' -import { useState } from 'react' +import { useState, useEffect, useCallback } from 'react' import Link from 'next/link' import { usePathname, useRouter } from 'next/navigation' import { createClient } from '@/lib/supabase/client' @@ -24,11 +24,14 @@ import { Building2, FileInput, } from 'lucide-react' +import { getExtensionDefinition } from '@/lib/extensions/sectors' +import { resolveIcon } from '@/lib/extensions/icon-resolver' import type { EntityType } from '@/types' interface DashboardNavProps { companyName: string entityType: EntityType + enabledExtensions?: { sector_slug: string; extension_slug: string }[] } interface NavItem { @@ -61,12 +64,31 @@ const groupLabels: Record = { övrigt: 'Övrigt', } -export default function DashboardNav({ companyName, entityType }: DashboardNavProps) { +export default function DashboardNav({ companyName, entityType, enabledExtensions }: DashboardNavProps) { const pathname = usePathname() const router = useRouter() const supabase = createClient() const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false) const [isOvrigtExpanded, setIsOvrigtExpanded] = useState(false) + const [isTillaggExpanded, setIsTillaggExpanded] = useState(false) + const [liveExtensions, setLiveExtensions] = useState(enabledExtensions ?? []) + + const fetchExtensions = useCallback(async () => { + try { + const res = await fetch('/api/extensions/toggles') + if (res.ok) { + const { data } = await res.json() + if (data) setLiveExtensions(data) + } + } catch { + // keep current state on error + } + }, []) + + // Refresh extensions when dropdown is opened or mobile menu is opened + useEffect(() => { + if (isTillaggExpanded || isMobileMenuOpen) fetchExtensions() + }, [isTillaggExpanded, isMobileMenuOpen, fetchExtensions]) const handleLogout = async () => { await supabase.auth.signOut() @@ -174,6 +196,53 @@ export default function DashboardNav({ companyName, entityType }: DashboardNavPr
+ {/* Tillägg - collapsible */} +
+ + {isTillaggExpanded && ( +
+ {liveExtensions.length > 0 ? liveExtensions.map((toggle) => { + const def = getExtensionDefinition(toggle.sector_slug, toggle.extension_slug) + if (!def) return null + const ExtIcon = resolveIcon(def.icon) + const href = `/e/${toggle.sector_slug}/${toggle.extension_slug}` + const active = isActive(href) + return ( + + + {def.name} + + ) + }) : ( +

+ Inga tillägg aktiverade +

+ )} +
+ )} +
+ {/* Övrigt group - collapsible */}
+ + + + ) +} diff --git a/components/extensions/shared/DateRangeFilter.tsx b/components/extensions/shared/DateRangeFilter.tsx new file mode 100644 index 00000000..1fb7e9fb --- /dev/null +++ b/components/extensions/shared/DateRangeFilter.tsx @@ -0,0 +1,66 @@ +'use client' + +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' + +type Period = 'month' | 'quarter' | 'year' | 'custom' + +interface DateRangeFilterProps { + onRangeChange: (start: string, end: string) => void + className?: string +} + +export default function DateRangeFilter({ onRangeChange, className }: DateRangeFilterProps) { + const [activePeriod, setActivePeriod] = useState('month') + + const now = new Date() + + const handlePeriod = (period: Period) => { + setActivePeriod(period) + const year = now.getFullYear() + const month = now.getMonth() + + switch (period) { + case 'month': { + const start = new Date(year, month, 1).toISOString().slice(0, 10) + const end = new Date(year, month + 1, 0).toISOString().slice(0, 10) + onRangeChange(start, end) + break + } + case 'quarter': { + const qStart = Math.floor(month / 3) * 3 + const start = new Date(year, qStart, 1).toISOString().slice(0, 10) + const end = new Date(year, qStart + 3, 0).toISOString().slice(0, 10) + onRangeChange(start, end) + break + } + case 'year': { + onRangeChange(`${year}-01-01`, `${year}-12-31`) + break + } + } + } + + const periods: { key: Period; label: string }[] = [ + { key: 'month', label: 'M\u00e5nad' }, + { key: 'quarter', label: 'Kvartal' }, + { key: 'year', label: '\u00c5r' }, + ] + + return ( +
+ {periods.map(({ key, label }) => ( + + ))} +
+ ) +} diff --git a/components/extensions/shared/EmptyExtensionState.tsx b/components/extensions/shared/EmptyExtensionState.tsx new file mode 100644 index 00000000..c03c7d25 --- /dev/null +++ b/components/extensions/shared/EmptyExtensionState.tsx @@ -0,0 +1,21 @@ +import { Puzzle } from 'lucide-react' + +interface EmptyExtensionStateProps { + title?: string + description?: string + icon?: React.ReactNode +} + +export default function EmptyExtensionState({ + title = 'Ingen data \u00e4nnu', + description = 'Data kommer att visas h\u00e4r n\u00e4r det finns tillg\u00e4ngligt.', + icon, +}: EmptyExtensionStateProps) { + return ( +
+ {icon ?? } +

{title}

+

{description}

+
+ ) +} diff --git a/components/extensions/shared/ExtensionLoadingSkeleton.tsx b/components/extensions/shared/ExtensionLoadingSkeleton.tsx new file mode 100644 index 00000000..2fdb0dde --- /dev/null +++ b/components/extensions/shared/ExtensionLoadingSkeleton.tsx @@ -0,0 +1,23 @@ +import { Skeleton } from '@/components/ui/skeleton' + +export default function ExtensionLoadingSkeleton() { + return ( +
+ {/* KPI cards skeleton */} +
+ {[1, 2, 3].map(i => ( +
+ + + +
+ ))} +
+ {/* Content skeleton */} +
+ + +
+
+ ) +} diff --git a/components/extensions/shared/KPICard.tsx b/components/extensions/shared/KPICard.tsx new file mode 100644 index 00000000..eb94faf8 --- /dev/null +++ b/components/extensions/shared/KPICard.tsx @@ -0,0 +1,34 @@ +'use client' + +import { Card, CardContent } from '@/components/ui/card' +import { cn } from '@/lib/utils' + +interface KPICardProps { + label: string + value: string | number + suffix?: string + trend?: { value: number; label: string } + className?: string +} + +export default function KPICard({ label, value, suffix, trend, className }: KPICardProps) { + return ( + + +

{label}

+
+ {value} + {suffix && {suffix}} +
+ {trend && ( +

0 ? 'text-green-600' : trend.value < 0 ? 'text-red-600' : 'text-muted-foreground' + )}> + {trend.value > 0 ? '+' : ''}{trend.value}% {trend.label} +

+ )} +
+
+ ) +} diff --git a/components/extensions/tech/BillableHoursWorkspace.tsx b/components/extensions/tech/BillableHoursWorkspace.tsx new file mode 100644 index 00000000..73c1ae85 --- /dev/null +++ b/components/extensions/tech/BillableHoursWorkspace.tsx @@ -0,0 +1,14 @@ +'use client' + +import { Clock } from 'lucide-react' +import EmptyExtensionState from '@/components/extensions/shared/EmptyExtensionState' + +export default function BillableHoursWorkspace() { + return ( + } + /> + ) +} diff --git a/components/extensions/tech/ProjectBillingWorkspace.tsx b/components/extensions/tech/ProjectBillingWorkspace.tsx new file mode 100644 index 00000000..e8c5b1a4 --- /dev/null +++ b/components/extensions/tech/ProjectBillingWorkspace.tsx @@ -0,0 +1,14 @@ +'use client' + +import { Layers } from 'lucide-react' +import EmptyExtensionState from '@/components/extensions/shared/EmptyExtensionState' + +export default function ProjectBillingWorkspace() { + return ( + } + /> + ) +} diff --git a/components/onboarding/Step2SectorSelection.tsx b/components/onboarding/Step2SectorSelection.tsx new file mode 100644 index 00000000..53329a7d --- /dev/null +++ b/components/onboarding/Step2SectorSelection.tsx @@ -0,0 +1,124 @@ +'use client' + +import { useState } from 'react' +import { Card, CardContent } from '@/components/ui/card' +import { Button } from '@/components/ui/button' +import { cn } from '@/lib/utils' +import { SECTORS } from '@/lib/extensions/sectors' +import { resolveIcon } from '@/lib/extensions/icon-resolver' +import { Briefcase, ArrowRight, Loader2 } from 'lucide-react' + +interface Step2SectorSelectionProps { + onNext: (data: { sector_slug: string | null }) => void + onBack: () => void + isSaving: boolean +} + +export default function Step2SectorSelection({ onNext, onBack, isSaving }: Step2SectorSelectionProps) { + const [selected, setSelected] = useState(null) + + const industrySectors = SECTORS.filter(s => s.slug !== 'general') + + return ( +
+
+

Vilken bransch verkar du inom?

+

+ Vi anpassar verktyg och tillägg baserat på din bransch. Du kan alltid ändra detta senare. +

+
+ +
+ {industrySectors.map(sector => { + const Icon = resolveIcon(sector.icon) + const isSelected = selected === sector.slug + return ( + setSelected(sector.slug)} + > + +
+
+ +
+
+

{sector.name}

+

{sector.description}

+

+ {sector.extensions.length} branschverktyg +

+
+
+
+
+ ) + })} + + {/* "Other" option */} + setSelected('other')} + > + +
+
+ +
+
+

Annan bransch

+

+ Generella verktyg utan branschspecifika tillägg +

+
+
+
+
+
+ +
+
+ + +
+ +
+
+ ) +} diff --git a/components/onboarding/Step3ExtensionSuggestions.tsx b/components/onboarding/Step3ExtensionSuggestions.tsx new file mode 100644 index 00000000..16771a4d --- /dev/null +++ b/components/onboarding/Step3ExtensionSuggestions.tsx @@ -0,0 +1,134 @@ +'use client' + +import { useState } from 'react' +import { Button } from '@/components/ui/button' +import { Switch } from '@/components/ui/switch' +import { cn } from '@/lib/utils' +import { getSector } from '@/lib/extensions/sectors' +import { resolveIcon } from '@/lib/extensions/icon-resolver' +import CategoryBadge from '@/components/extensions/CategoryBadge' +import { ArrowRight, Loader2 } from 'lucide-react' +import type { SectorSlug, ExtensionDefinition } from '@/lib/extensions/types' + +interface Step3Props { + sectorSlug: string | null + onNext: (data: { enabled_extensions: { sector_slug: string; extension_slug: string }[] }) => void + onBack: () => void + isSaving: boolean +} + +export default function Step3ExtensionSuggestions({ sectorSlug, onNext, onBack, isSaving }: Step3Props) { + const generalSector = getSector('general') + const selectedSector = sectorSlug ? getSector(sectorSlug as SectorSlug) : null + + const [toggles, setToggles] = useState>({}) + + const handleToggle = (ext: ExtensionDefinition) => { + const key = `${ext.sector}/${ext.slug}` + setToggles(prev => ({ ...prev, [key]: !prev[key] })) + } + + const handleSubmit = () => { + const enabled = Object.entries(toggles) + .filter(([, enabled]) => enabled) + .map(([key]) => { + const [sector_slug, extension_slug] = key.split('/') + return { sector_slug, extension_slug } + }) + onNext({ enabled_extensions: enabled }) + } + + const handleSkip = () => { + onNext({ enabled_extensions: [] }) + } + + // Group: first general, then sector-specific + const sections: { label: string; extensions: ExtensionDefinition[] }[] = [] + if (generalSector) { + sections.push({ label: generalSector.name, extensions: generalSector.extensions }) + } + if (selectedSector) { + sections.push({ label: selectedSector.name, extensions: selectedSector.extensions }) + } + + const enabledCount = Object.values(toggles).filter(Boolean).length + + return ( +
+
+

Välj dina tillägg

+

+ Aktivera de verktyg du vill använda. Du kan alltid ändra detta senare under Tillägg. +

+
+ + {sections.map(section => ( +
+

+ {section.label} +

+
+ {section.extensions.map(ext => { + const Icon = resolveIcon(ext.icon) + const key = `${ext.sector}/${ext.slug}` + const isEnabled = toggles[key] ?? false + return ( +
+
+
+ +
+
+
+

{ext.name}

+ +
+

{ext.description}

+
+
+ handleToggle(ext)} + /> +
+ ) + })} +
+
+ ))} + +
+
+ + +
+ +
+
+ ) +} diff --git a/extensions.md b/extensions.md new file mode 100644 index 00000000..95adaf40 --- /dev/null +++ b/extensions.md @@ -0,0 +1,521 @@ +# Extension System — Design Document + +## The App + +erp-base is a Swedish accounting platform for sole traders (enskild firma) and limited companies (aktiebolag). It handles the legally required bookkeeping and financial management that every Swedish business needs. + +## Core Functionality + +The core is the standard accounting system. It's what every user gets out of the box — the features that exist in any accounting platform like Fortnox, Visma, or Björn Lundén. Nothing more, nothing less: + +- Double-entry bookkeeping (journal entries, BAS chart of accounts, voucher numbering) +- Invoicing (create, send, track, payment matching) +- Supplier invoice management +- Bank transaction reconciliation +- Financial reports (income statement, balance sheet, trial balance, VAT declaration, general ledger) +- Tax compliance (SRU export, NE-bilaga, tax deadline tracking) +- Document archive with 7-year legal retention +- Customer and supplier management + +That's the core. It doesn't include receipt scanning, AI categorization, AI chat, push notifications, or PSD2 bank connection. Those are not standard accounting features — they're value-adds. + +## Extensions + +Extensions are **everything beyond the core accounting system**. They are self-contained tools that a user adds to their dashboard. No extensions are active by default — the user chooses which ones they want. + +There are two kinds of extensions: + +### General Extensions + +General extensions are not tied to any specific business sector. They're useful for any business but they go beyond what a standard accounting system offers. They are optional — the user toggles them on from the marketplace. + +Examples: +- **Receipt OCR** — Scan receipts and extract data automatically +- **AI Categorization** — AI-powered transaction categorization suggestions +- **AI Chat** — AI assistant for tax and bookkeeping questions +- **Push Notifications** — Event notifications for accounting activities +- **Enable Banking** — PSD2 automatic bank transaction sync + +These currently exist in the codebase at `extensions/` and are always loaded. They need to be migrated to the toggle system so users choose to enable them. + +### Sector Extensions + +Sector extensions are tied to a specific market sector. They're only relevant to businesses operating in that sector. A restaurant owner wants "Food Cost %" but an IT consultant does not. + +Examples: +- **Restaurant:** Food Cost %, Earnings Per Alcohol Liter, POS Z-Report Import, Tip Tracking +- **Construction:** ROT Calculator, Project Cost Tracking +- **Hotel:** RevPAR, Occupancy Tracking +- **IT/Consulting:** Billable Hours Ratio, Project Billing Metrics +- **E-commerce:** Shopify Order Import, Multi-channel Revenue Analytics + +### The Unified Model + +Both general and sector extensions live in the same system: + +``` +extensions/ + general/ ← General extensions (any business) + receipt-ocr/ + ai-categorization/ + ai-chat/ + push-notifications/ + enable-banking/ + restaurant/ ← Restaurant sector extensions + food-cost/ + earnings-per-liter/ + pos-import/ + tip-tracking/ + construction/ ← Construction sector extensions + rot-calculator/ + project-cost/ + hotel/ ← Hotel sector extensions + revpar/ + occupancy/ + tech/ ← IT/Consulting sector extensions + billable-hours/ + project-billing/ + ecommerce/ ← E-commerce sector extensions + shopify-import/ + multichannel-revenue/ +``` + +In the marketplace: +- General extensions are shown to everyone, always visible +- Sector extensions are suggested based on the user's primary sector +- But all extensions are browsable by everyone regardless of sector + +In the sidebar under "Your Extensions": +- Both general and sector extensions appear together +- Whatever the user has enabled shows up here + +--- + +## Design Decisions (Confirmed) + +### 1. Extensions are self-contained — they do NOT write to the core accounting system + +Extensions are **independent tools that live on the dashboard**. They are NOT part of the core accounting system. They have their own world, their own data, their own purpose. They never create journal entries, invoices, or modify any accounting records. + +There are two one-way data flows into an extension. Data never flows back: + +``` +Core Accounting Data ──→ Extension (reads it, displays it, uses it in calculations) +User Manual Input ──→ Extension (stores it in extension's own data, processes it) +Extension ──✗──→ Core Accounting (never writes back) +``` + +An extension may: +- **Be fed core data** — the platform feeds accounting data (journal entries, transactions, invoices) into the extension for it to read and use in calculations +- **Accept user input** — the user submits data directly into the extension for data that doesn't exist in any accounting system (e.g. liters of alcohol sold per day, POS Z-report files, Shopify order exports) +- **Store its own data** — extension-specific data lives in the extension's own storage, separate from core accounting +- **Calculate and display** — combine core data + extension data to produce metrics, reports, insights + +An extension may NOT: +- Create journal entries +- Create or modify invoices +- Modify transactions or any core accounting table +- Write back to the core accounting system in any way + +This is a critical architectural constraint. Extensions are safe — enabling or disabling one can never corrupt or affect the accounting data. The core bookkeeping is a walled garden that extensions can look into but never modify. + +**Important:** Features like POS Z-Report Import and Shopify Order Import are EXTENSIONS. They import data into the extension's own storage and provide analytics on that data. They do not create journal entries from imported data. The bookkeeping of POS data or Shopify orders is a separate activity the user does in the core platform. + +### 2. Data source depends on the extension — three patterns + +**Pattern A: Fed from core accounting data** +Some extensions are fed existing bookkeeping data. For example, a "Food Cost %" extension reads journal entries for food purchase accounts (4000-series) and food revenue accounts (3000-series), then calculates and displays the metric. The user doesn't enter anything — the data already exists in the bookkeeping. These are extensions for data that Fortnox, Visma, and other accounting systems already have. + +**Pattern B: User submits data manually** +Some extensions need data that doesn't exist in any accounting system. No system tracks liters of alcohol sold, or daily staff tips, or room occupancy counts. For these extensions, the user manually submits data into the extension's workspace. The extension stores, processes, and displays this data. This has nothing to do with the core accounting functionality. + +**Pattern C: Both** +Some extensions combine core accounting data with user-submitted data. "Earnings Per Alcohol Liter" reads alcohol revenue from the bookkeeping (Pattern A) and takes user-entered liter counts (Pattern B) to calculate revenue per liter. + +### 3. Full marketplace for post-onboarding management + +After onboarding, users have a dedicated "Extensions" marketplace page where they can: +- Browse all available extensions (general + all sectors) +- Read descriptions and details +- Toggle extensions on/off at any time +- Discover extensions from sectors other than their primary one + +### 4. Primary sector with cross-sector browsing + +During onboarding, the user selects a **primary sector** (e.g. "Restaurant & Cafe"). The app then suggests extensions for that sector, plus general extensions. But the user is NOT locked in — they can browse and enable extensions from any sector at any time via the marketplace. + +The primary sector serves as a **recommendation filter**, not a restriction. + +### 5. First-party now, third-party later + +We build all extensions ourselves initially. But the architecture should be clean and well-defined enough that external developers could eventually build extensions too. This means: +- Clear extension interface/contract +- Well-documented data access patterns +- Self-contained extension structure (each extension is a standalone module) + +--- + +## The User Experience + +1. User signs up, goes through onboarding +2. During onboarding, they select their business sector ("Restaurant & Cafe") +3. The app suggests extensions: general extensions + extensions for that sector +4. User toggles on the ones they want +5. On the dashboard, the sidebar has a **"Your Extensions"** section listing all enabled extensions +6. Clicking an extension opens its workspace — a dedicated page with the extension's own UI +7. The user interacts with the extension: views data, enters inputs, sees calculations/reports +8. User can browse the marketplace anytime to add/remove extensions + +--- + +## Extension Definition + +### What an Extension Contains + +| Part | Required? | Description | +|------|-----------|-------------| +| **Metadata** | Yes | Name, description, sector (or 'general'), category, icon — for marketplace and sidebar | +| **Workspace UI** | Yes | A React component — the main page the user sees when they click the extension | +| **Extension data** | Depends | Storage for user-submitted data and extension state | +| **Configuration** | Optional | Settings panel for customizing the extension's behavior | +| **Core data queries** | Optional | Queries that read from journal entries, transactions, invoices, etc. | + +### Extension Interface + +```typescript +interface ExtensionDefinition { + // Identity + slug: string // URL-safe ID, unique within sector (e.g. 'earnings-per-liter') + name: string // Display name (e.g. 'Earnings Per Alcohol Liter') + sector: string // 'general' | 'restaurant' | 'construction' | 'hotel' | 'tech' | 'ecommerce' + category: ExtensionCategory // 'accounting' | 'reports' | 'import' | 'operations' + + // Display (for marketplace and sidebar) + description: string // One-line description + longDescription: string // Detailed description with features + icon: string // Lucide icon name + entityTypes?: EntityType[] // Supported entity types (default: both EF and AB) + + // Data patterns + dataPattern: 'core' | 'manual' | 'both' // How the extension gets its data + readsCoreTables?: string[] // Which core tables this extension reads (for pattern A/C) + hasOwnData?: boolean // Whether users submit data into this extension (for pattern B/C) +} +``` + +### Sector Definition + +```typescript +interface Sector { + slug: string // 'general' | 'restaurant' | 'construction' | etc. + name: string // 'General' | 'Restaurant & Cafe' | etc. + icon: string // Lucide icon name + description: string // Short tagline + extensions: ExtensionDefinition[] +} +``` + +### Extension Categories + +```typescript +type ExtensionCategory = 'accounting' | 'reports' | 'import' | 'operations' +``` + +| Category | Color | Purpose | +|----------|-------|---------| +| Accounting & Tax | Red | Calculations related to bookkeeping, VAT, deductions | +| Industry Reports | Blue | KPIs, analytics, metrics | +| Smart Import | Green | Parse and import data from external tools | +| Operational Tools | Gray | Day-to-day business tools | + +--- + +## Concrete Examples + +| Extension | Sector | Data Pattern | User Input | Reads Core Data | What it Does | +|-----------|--------|--------------|------------|-----------------|--------------| +| Receipt OCR | General | B (manual) | Uploads receipt images | None | Scans receipts, extracts merchant/amount/VAT data | +| AI Categorization | General | A (core) | None | Uncategorized transactions | Suggests BAS account categories using AI | +| Enable Banking | General | B (manual) | Bank connection setup | None | Syncs bank transactions via PSD2 | +| Earnings Per Alcohol Liter | Restaurant | A + B (both) | Liters sold per day/week | Alcohol revenue from BAS 3001 | Calculates revenue/liter, trends over time | +| Food Cost % | Restaurant | A (core) | None | Food purchases (4000-series), food revenue (3000-series) | Calculates food_cost/food_revenue %, trends | +| Tip Tracking | Restaurant | B (manual) | Tip amounts per shift | Optionally reads staff cost accounts | Total tips, tips/employee, tip % of revenue | +| POS Z-Report Import | Restaurant | B (manual) | Uploads Z-report CSV/Excel | None | Parses POS data, stores in extension, shows daily sales analytics | +| Shopify Order Import | E-commerce | B (manual) | Uploads order export | None | Imports orders into extension, shows revenue by product, trends | +| ROT Calculator | Construction | A + B (both) | Labor hours, material costs per job | Invoice data for customer billing | ROT deduction amounts (30% of labor, max 50k/year per customer) | +| RevPAR | Hotel | A + B (both) | Room count and occupancy | Room revenue accounts | Revenue Per Available Room, occupancy rate | +| Billable Hours Ratio | IT/Consulting | A + B (both) | Hours worked per project | Invoice data for billed amounts | Billable/total hours, effective hourly rate | + +--- + +## Architecture + +### Where Things Live + +``` +extensions/ + general/ ← General extensions + receipt-ocr/ + index.ts ← Extension definition + logic + lib/ + __tests__/ + ai-categorization/ + index.ts + lib/ + ai-chat/ + index.ts + lib/ + push-notifications/ + index.ts + lib/ + enable-banking/ + index.ts + lib/ + restaurant/ ← Restaurant sector + earnings-per-liter/ + index.ts + lib/ + food-cost/ + index.ts + lib/ + pos-import/ + index.ts + lib/ + tip-tracking/ + index.ts + lib/ + construction/ ← Construction sector + rot-calculator/ + index.ts + lib/ + hotel/ ← Hotel sector + revpar/ + index.ts + lib/ + tech/ ← IT/Consulting sector + billable-hours/ + index.ts + lib/ + ecommerce/ ← E-commerce sector + shopify-import/ + index.ts + lib/ + +lib/ + extensions/ + types.ts ← ExtensionDefinition, Sector, ExtensionCategory types + sectors.ts ← Sector + extension metadata registry (source of truth) + workspace-registry.tsx ← Maps sector/slug → lazy-loaded React component + hooks.ts ← useExtensionToggle, useEnabledExtensions + +components/ + extensions/ + ExtensionWorkspaceShell.tsx ← Shared layout wrapper + shared/ ← Shared UI primitives + KPICard.tsx + DataEntryForm.tsx + DateRangeFilter.tsx + EmptyExtensionState.tsx + ExtensionLoadingSkeleton.tsx + general/ ← General extension workspaces + ReceiptOcrWorkspace.tsx + AiCategorizationWorkspace.tsx + AiChatWorkspace.tsx + restaurant/ ← Restaurant extension workspaces + EarningsPerLiterWorkspace.tsx + FoodCostWorkspace.tsx + PosImportWorkspace.tsx + construction/ + RotCalculatorWorkspace.tsx + hotel/ + RevparWorkspace.tsx + tech/ + BillableHoursWorkspace.tsx + ecommerce/ + ShopifyImportWorkspace.tsx + +app/(dashboard)/ + extensions/ ← Marketplace + page.tsx ← Extension hub (browse sectors + general) + [sector]/ + page.tsx ← Extensions for a specific sector + [extension]/ + page.tsx ← Extension detail + toggle + e/ ← Extension workspaces + [sector]/ + [slug]/ + page.tsx ← Renders the workspace component +``` + +### Data Storage + +Extensions store their data in the existing `extension_data` table: + +``` +extension_data: + user_id: auth user + extension_id: 'restaurant/earnings-per-liter' (sector/slug format) + key: 'settings' | 'entries' | 'config' | custom keys + value: JSONB (flexible) +``` + +For the "Earnings Per Liter" extension, data might look like: +``` +key: 'settings' → { "defaultUnit": "liter", "currency": "SEK" } +key: 'entries' → [{ "date": "2025-01-15", "liters": 42.5, "type": "spirits" }, ...] +key: 'config' → { "revenueAccounts": ["3001"], "trackByType": true } +``` + +### The Toggle System + +New database table: + +```sql +create table extension_toggles ( + id uuid primary key default uuid_generate_v4(), + user_id uuid not null references auth.users on delete cascade, + sector_slug text not null, -- 'general' | 'restaurant' | 'construction' | etc. + extension_slug text not null, + enabled boolean not null default true, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint extension_toggles_unique unique (user_id, sector_slug, extension_slug) +); +``` + +Also add to company_settings: +```sql +alter table company_settings add column sector_slug text; +``` + +### API Routes for Extensions + +Each extension that needs data persistence gets API routes: + +``` +app/api/extensions/[sector]/[slug]/ + data/route.ts — GET (read entries), POST (submit new entry), DELETE (remove entry) + settings/route.ts — GET (read settings), PATCH (update settings) +``` + +These are simple CRUD routes that read/write to `extension_data`. They follow the existing API route pattern (auth check, RLS, user_id filtering). + +### Sidebar Integration + +The sidebar (`DashboardNav.tsx`) gets a new section: **"Your Extensions"**. It reads enabled extensions from `extension_toggles` and renders links: + +``` +── Your Extensions ────────── + 📷 Receipt OCR → /e/general/receipt-ocr + 🤖 AI Categorization → /e/general/ai-categorization + 📊 Food Cost % → /e/restaurant/food-cost + 🍷 Earnings Per Liter → /e/restaurant/earnings-per-liter +``` + +Each link goes to `/e/{sector}/{slug}` which renders the extension's workspace component. + +### Onboarding Integration + +Add two new steps to the onboarding flow (after entity type selection): + +**Step 2: Sector Selection** +"What type of business do you run?" +Grid of sectors with icons and descriptions. User picks one. +Stores `sector_slug` on `company_settings`. + +**Step 3: Extension Suggestions** +"Here are tools for your business. Pick the ones you want." +Shows general extensions + extensions for the selected sector, grouped by category. +User toggles desired extensions. Inserts into `extension_toggles`. +Can be skipped — user can always add extensions later from the marketplace. + +--- + +## The Extension Workspace Pattern + +Every extension workspace follows the same pattern: + +``` +┌─────────────────────────────────────────────────┐ +│ Extension Workspace Shell │ +│ ┌─────────────────────────────────────────────┐ │ +│ │ Header: Extension name + settings link │ │ +│ ├─────────────────────────────────────────────┤ │ +│ │ │ │ +│ │ Extension-specific UI │ │ +│ │ │ │ +│ │ This is where the extension does its thing │ │ +│ │ - Data entry forms │ │ +│ │ - KPI cards and charts │ │ +│ │ - Tables of submitted data │ │ +│ │ - Calculation results │ │ +│ │ - Date range filters │ │ +│ │ │ │ +│ └─────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────┘ +``` + +The `ExtensionWorkspaceShell` provides consistent chrome (header, breadcrumbs, settings link). The extension fills in the content area with whatever UI it needs. + +### Example: Earnings Per Alcohol Liter + +When the user clicks this extension, they see: + +1. **KPI cards at top**: Current earnings/liter, trend vs last month, total liters this month +2. **Data entry section**: Form to log daily sales (date, liters sold, alcohol type) +3. **History table**: Past entries with edit/delete +4. **Chart**: Earnings per liter over time (line chart) +5. **Revenue breakdown**: Reads from core journal entries — alcohol revenue by account + +The extension reads revenue data from journal_entry_lines (BAS 3001 for 25% alcohol revenue) and combines it with user-submitted liter data to calculate the metric. + +--- + +## Migration from Current Architecture + +The current codebase has receipt-ocr, ai-categorization, ai-chat, push-notifications, sru-export, ne-bilaga, and enable-banking implemented as always-on server-side plugins using the `Extension` interface, the extension registry, and the event bus. + +These need to become general extensions in the new system: +1. Move from `extensions/{name}/` to `extensions/general/{name}/` +2. Add metadata (description, icon, category) to each +3. Register them in the sector data registry under the `general` sector +4. Create workspace components for each +5. Make them toggleable via `extension_toggles` (instead of always loaded) +6. The existing event bus integration and server-side behavior stays — general extensions may still use the event bus for background processing (e.g. ai-categorization reacting to transaction.synced). The toggle check becomes a gate in their event handlers. + +Note: SRU export and NE-bilaga may remain as core features since they're legally required for Swedish accounting compliance, not optional value-adds. This is a decision to make during implementation. + +--- + +## What Needs to Be Built + +1. **Extension types** — ExtensionDefinition, Sector, ExtensionCategory in types +2. **Sector data registry** — All sectors and extension metadata in code +3. **Database migration** — extension_toggles table + sector_slug on company_settings +4. **Toggle hooks** — useExtensionToggle, useEnabledExtensions (client-side) +5. **Workspace component registry** — Maps sector/slug → lazy-loaded React component +6. **Workspace routing** — `app/(dashboard)/e/[sector]/[slug]/page.tsx` +7. **Workspace shell** — Shared layout wrapper component +8. **Marketplace pages** — `app/(dashboard)/extensions/` for browsing and toggling +9. **Sidebar "Your Extensions"** — Wire enabled extensions into DashboardNav +10. **Onboarding steps** — Sector selection + extension suggestions +11. **Shared UI components** — KPICard, DataEntryForm, DateRangeFilter, EmptyExtensionState +12. **Extension API routes** — Generic CRUD for extension_data +13. **Migrate general extensions** — Move current extensions to new toggle system +14. **Build first sector extensions** — Starting with restaurant sector + +--- + +## Summary + +**The app** is a Swedish accounting platform. + +**Core functionality** is the standard accounting system: bookkeeping, invoicing, reports, tax, bank reconciliation. Every user gets this. + +**Extensions** are everything beyond core accounting. They come in two kinds: +- **General extensions** (receipt-ocr, ai-categorization, etc.) — useful for any business, not sector-specific +- **Sector extensions** (food cost %, earnings per liter, etc.) — tied to a specific market sector + +All extensions live in the same system, use the same toggle mechanism, appear in the same marketplace, and show up under "Your Extensions" in the sidebar. No extensions are active by default — the user chooses which ones to add. + +Extensions are read-only with respect to the core accounting system. They can be fed accounting data, they can accept manual user input, but they never write back to the bookkeeping. diff --git a/extensions/construction/project-cost/index.ts b/extensions/construction/project-cost/index.ts new file mode 100644 index 00000000..f7ceca3c --- /dev/null +++ b/extensions/construction/project-cost/index.ts @@ -0,0 +1,2 @@ +// Project Cost extension — Track costs per construction project +export const PROJECT_COST_EXTENSION_ID = 'construction/project-cost' diff --git a/extensions/construction/rot-calculator/index.ts b/extensions/construction/rot-calculator/index.ts new file mode 100644 index 00000000..1ef83776 --- /dev/null +++ b/extensions/construction/rot-calculator/index.ts @@ -0,0 +1,2 @@ +// ROT Calculator extension — Calculate ROT tax deductions for construction work +export const ROT_CALCULATOR_EXTENSION_ID = 'construction/rot-calculator' diff --git a/extensions/ecommerce/multichannel-revenue/index.ts b/extensions/ecommerce/multichannel-revenue/index.ts new file mode 100644 index 00000000..c39074f1 --- /dev/null +++ b/extensions/ecommerce/multichannel-revenue/index.ts @@ -0,0 +1,2 @@ +// Multichannel Revenue extension — Track revenue across sales channels +export const MULTICHANNEL_REVENUE_EXTENSION_ID = 'ecommerce/multichannel-revenue' diff --git a/extensions/ecommerce/shopify-import/index.ts b/extensions/ecommerce/shopify-import/index.ts new file mode 100644 index 00000000..0b125e35 --- /dev/null +++ b/extensions/ecommerce/shopify-import/index.ts @@ -0,0 +1,2 @@ +// Shopify Import extension — Import orders and transactions from Shopify +export const SHOPIFY_IMPORT_EXTENSION_ID = 'ecommerce/shopify-import' diff --git a/extensions/ai-categorization/categorizer.ts b/extensions/general/ai-categorization/categorizer.ts similarity index 100% rename from extensions/ai-categorization/categorizer.ts rename to extensions/general/ai-categorization/categorizer.ts diff --git a/extensions/ai-categorization/index.ts b/extensions/general/ai-categorization/index.ts similarity index 100% rename from extensions/ai-categorization/index.ts rename to extensions/general/ai-categorization/index.ts diff --git a/extensions/ai-chat/chatbot/chain.ts b/extensions/general/ai-chat/chatbot/chain.ts similarity index 100% rename from extensions/ai-chat/chatbot/chain.ts rename to extensions/general/ai-chat/chatbot/chain.ts diff --git a/extensions/ai-chat/chatbot/config.ts b/extensions/general/ai-chat/chatbot/config.ts similarity index 100% rename from extensions/ai-chat/chatbot/config.ts rename to extensions/general/ai-chat/chatbot/config.ts diff --git a/extensions/ai-chat/chatbot/embeddings.ts b/extensions/general/ai-chat/chatbot/embeddings.ts similarity index 100% rename from extensions/ai-chat/chatbot/embeddings.ts rename to extensions/general/ai-chat/chatbot/embeddings.ts diff --git a/extensions/ai-chat/chatbot/prompts.ts b/extensions/general/ai-chat/chatbot/prompts.ts similarity index 100% rename from extensions/ai-chat/chatbot/prompts.ts rename to extensions/general/ai-chat/chatbot/prompts.ts diff --git a/extensions/ai-chat/chatbot/retriever.ts b/extensions/general/ai-chat/chatbot/retriever.ts similarity index 100% rename from extensions/ai-chat/chatbot/retriever.ts rename to extensions/general/ai-chat/chatbot/retriever.ts diff --git a/extensions/ai-chat/index.ts b/extensions/general/ai-chat/index.ts similarity index 100% rename from extensions/ai-chat/index.ts rename to extensions/general/ai-chat/index.ts diff --git a/extensions/ai-chat/ingestion/ingest.ts b/extensions/general/ai-chat/ingestion/ingest.ts similarity index 100% rename from extensions/ai-chat/ingestion/ingest.ts rename to extensions/general/ai-chat/ingestion/ingest.ts diff --git a/extensions/enable-banking/components/BankConnectionStatus.tsx b/extensions/general/enable-banking/components/BankConnectionStatus.tsx similarity index 100% rename from extensions/enable-banking/components/BankConnectionStatus.tsx rename to extensions/general/enable-banking/components/BankConnectionStatus.tsx diff --git a/extensions/enable-banking/components/BankSelector.tsx b/extensions/general/enable-banking/components/BankSelector.tsx similarity index 100% rename from extensions/enable-banking/components/BankSelector.tsx rename to extensions/general/enable-banking/components/BankSelector.tsx diff --git a/extensions/enable-banking/index.ts b/extensions/general/enable-banking/index.ts similarity index 100% rename from extensions/enable-banking/index.ts rename to extensions/general/enable-banking/index.ts diff --git a/extensions/enable-banking/lib/api-client.ts b/extensions/general/enable-banking/lib/api-client.ts similarity index 100% rename from extensions/enable-banking/lib/api-client.ts rename to extensions/general/enable-banking/lib/api-client.ts diff --git a/extensions/enable-banking/lib/jwt.ts b/extensions/general/enable-banking/lib/jwt.ts similarity index 100% rename from extensions/enable-banking/lib/jwt.ts rename to extensions/general/enable-banking/lib/jwt.ts diff --git a/extensions/enable-banking/lib/sync.ts b/extensions/general/enable-banking/lib/sync.ts similarity index 100% rename from extensions/enable-banking/lib/sync.ts rename to extensions/general/enable-banking/lib/sync.ts diff --git a/extensions/enable-banking/types.ts b/extensions/general/enable-banking/types.ts similarity index 100% rename from extensions/enable-banking/types.ts rename to extensions/general/enable-banking/types.ts diff --git a/extensions/example-logger/index.ts b/extensions/general/example-logger/index.ts similarity index 100% rename from extensions/example-logger/index.ts rename to extensions/general/example-logger/index.ts diff --git a/extensions/push-notifications/NotificationSettings.tsx b/extensions/general/push-notifications/NotificationSettings.tsx similarity index 100% rename from extensions/push-notifications/NotificationSettings.tsx rename to extensions/general/push-notifications/NotificationSettings.tsx diff --git a/extensions/push-notifications/PushPrompt.tsx b/extensions/general/push-notifications/PushPrompt.tsx similarity index 100% rename from extensions/push-notifications/PushPrompt.tsx rename to extensions/general/push-notifications/PushPrompt.tsx diff --git a/extensions/push-notifications/index.ts b/extensions/general/push-notifications/index.ts similarity index 100% rename from extensions/push-notifications/index.ts rename to extensions/general/push-notifications/index.ts diff --git a/extensions/push-notifications/notification-scheduler.ts b/extensions/general/push-notifications/notification-scheduler.ts similarity index 100% rename from extensions/push-notifications/notification-scheduler.ts rename to extensions/general/push-notifications/notification-scheduler.ts diff --git a/extensions/push-notifications/notification-sender.ts b/extensions/general/push-notifications/notification-sender.ts similarity index 100% rename from extensions/push-notifications/notification-sender.ts rename to extensions/general/push-notifications/notification-sender.ts diff --git a/extensions/push-notifications/payload-builders.ts b/extensions/general/push-notifications/payload-builders.ts similarity index 100% rename from extensions/push-notifications/payload-builders.ts rename to extensions/general/push-notifications/payload-builders.ts diff --git a/extensions/push-notifications/types.ts b/extensions/general/push-notifications/types.ts similarity index 100% rename from extensions/push-notifications/types.ts rename to extensions/general/push-notifications/types.ts diff --git a/extensions/receipt-ocr/__tests__/index.test.ts b/extensions/general/receipt-ocr/__tests__/index.test.ts similarity index 100% rename from extensions/receipt-ocr/__tests__/index.test.ts rename to extensions/general/receipt-ocr/__tests__/index.test.ts diff --git a/extensions/receipt-ocr/components/ReceiptCamera.tsx b/extensions/general/receipt-ocr/components/ReceiptCamera.tsx similarity index 100% rename from extensions/receipt-ocr/components/ReceiptCamera.tsx rename to extensions/general/receipt-ocr/components/ReceiptCamera.tsx diff --git a/extensions/receipt-ocr/components/ReceiptDashboard.tsx b/extensions/general/receipt-ocr/components/ReceiptDashboard.tsx similarity index 100% rename from extensions/receipt-ocr/components/ReceiptDashboard.tsx rename to extensions/general/receipt-ocr/components/ReceiptDashboard.tsx diff --git a/extensions/receipt-ocr/components/ReceiptLineItemRow.tsx b/extensions/general/receipt-ocr/components/ReceiptLineItemRow.tsx similarity index 100% rename from extensions/receipt-ocr/components/ReceiptLineItemRow.tsx rename to extensions/general/receipt-ocr/components/ReceiptLineItemRow.tsx diff --git a/extensions/receipt-ocr/components/ReceiptReviewView.tsx b/extensions/general/receipt-ocr/components/ReceiptReviewView.tsx similarity index 100% rename from extensions/receipt-ocr/components/ReceiptReviewView.tsx rename to extensions/general/receipt-ocr/components/ReceiptReviewView.tsx diff --git a/extensions/receipt-ocr/components/TransactionMatcher.tsx b/extensions/general/receipt-ocr/components/TransactionMatcher.tsx similarity index 100% rename from extensions/receipt-ocr/components/TransactionMatcher.tsx rename to extensions/general/receipt-ocr/components/TransactionMatcher.tsx diff --git a/extensions/receipt-ocr/components/index.ts b/extensions/general/receipt-ocr/components/index.ts similarity index 100% rename from extensions/receipt-ocr/components/index.ts rename to extensions/general/receipt-ocr/components/index.ts diff --git a/extensions/receipt-ocr/index.ts b/extensions/general/receipt-ocr/index.ts similarity index 100% rename from extensions/receipt-ocr/index.ts rename to extensions/general/receipt-ocr/index.ts diff --git a/extensions/receipt-ocr/lib/__tests__/receipt-categorizer.test.ts b/extensions/general/receipt-ocr/lib/__tests__/receipt-categorizer.test.ts similarity index 100% rename from extensions/receipt-ocr/lib/__tests__/receipt-categorizer.test.ts rename to extensions/general/receipt-ocr/lib/__tests__/receipt-categorizer.test.ts diff --git a/extensions/receipt-ocr/lib/__tests__/receipt-matcher.test.ts b/extensions/general/receipt-ocr/lib/__tests__/receipt-matcher.test.ts similarity index 100% rename from extensions/receipt-ocr/lib/__tests__/receipt-matcher.test.ts rename to extensions/general/receipt-ocr/lib/__tests__/receipt-matcher.test.ts diff --git a/extensions/receipt-ocr/lib/receipt-analyzer.ts b/extensions/general/receipt-ocr/lib/receipt-analyzer.ts similarity index 100% rename from extensions/receipt-ocr/lib/receipt-analyzer.ts rename to extensions/general/receipt-ocr/lib/receipt-analyzer.ts diff --git a/extensions/receipt-ocr/lib/receipt-categorizer.ts b/extensions/general/receipt-ocr/lib/receipt-categorizer.ts similarity index 100% rename from extensions/receipt-ocr/lib/receipt-categorizer.ts rename to extensions/general/receipt-ocr/lib/receipt-categorizer.ts diff --git a/extensions/receipt-ocr/lib/receipt-matcher.ts b/extensions/general/receipt-ocr/lib/receipt-matcher.ts similarity index 100% rename from extensions/receipt-ocr/lib/receipt-matcher.ts rename to extensions/general/receipt-ocr/lib/receipt-matcher.ts diff --git a/extensions/receipt-ocr/lib/receipt-utils.ts b/extensions/general/receipt-ocr/lib/receipt-utils.ts similarity index 100% rename from extensions/receipt-ocr/lib/receipt-utils.ts rename to extensions/general/receipt-ocr/lib/receipt-utils.ts diff --git a/extensions/receipt-ocr/pages/ReceiptsPage.tsx b/extensions/general/receipt-ocr/pages/ReceiptsPage.tsx similarity index 100% rename from extensions/receipt-ocr/pages/ReceiptsPage.tsx rename to extensions/general/receipt-ocr/pages/ReceiptsPage.tsx diff --git a/extensions/receipt-ocr/pages/scan/ScanReceiptPage.tsx b/extensions/general/receipt-ocr/pages/scan/ScanReceiptPage.tsx similarity index 100% rename from extensions/receipt-ocr/pages/scan/ScanReceiptPage.tsx rename to extensions/general/receipt-ocr/pages/scan/ScanReceiptPage.tsx diff --git a/extensions/receipt-ocr/types.ts b/extensions/general/receipt-ocr/types.ts similarity index 100% rename from extensions/receipt-ocr/types.ts rename to extensions/general/receipt-ocr/types.ts diff --git a/extensions/hotel/occupancy/index.ts b/extensions/hotel/occupancy/index.ts new file mode 100644 index 00000000..5e5508ff --- /dev/null +++ b/extensions/hotel/occupancy/index.ts @@ -0,0 +1,2 @@ +// Occupancy extension — Track and report hotel room occupancy rates +export const OCCUPANCY_EXTENSION_ID = 'hotel/occupancy' diff --git a/extensions/hotel/revpar/index.ts b/extensions/hotel/revpar/index.ts new file mode 100644 index 00000000..13279cd4 --- /dev/null +++ b/extensions/hotel/revpar/index.ts @@ -0,0 +1,2 @@ +// RevPAR extension — Revenue Per Available Room calculation for hotels +export const REVPAR_EXTENSION_ID = 'hotel/revpar' diff --git a/extensions/restaurant/earnings-per-liter/index.ts b/extensions/restaurant/earnings-per-liter/index.ts new file mode 100644 index 00000000..42a30759 --- /dev/null +++ b/extensions/restaurant/earnings-per-liter/index.ts @@ -0,0 +1,3 @@ +// Earnings Per Liter extension — Pattern B (manual data entry) +// Tracks alcohol volume sold and calculates revenue per liter. +export const EARNINGS_PER_LITER_EXTENSION_ID = 'restaurant/earnings-per-liter' diff --git a/extensions/restaurant/earnings-per-liter/lib/__tests__/earnings-calculator.test.ts b/extensions/restaurant/earnings-per-liter/lib/__tests__/earnings-calculator.test.ts new file mode 100644 index 00000000..2ec54d7a --- /dev/null +++ b/extensions/restaurant/earnings-per-liter/lib/__tests__/earnings-calculator.test.ts @@ -0,0 +1,82 @@ +import { describe, it, expect } from 'vitest' +import { + calculateEarningsPerLiter, + type LiterEntry, +} from '../earnings-calculator' + +describe('calculateEarningsPerLiter', () => { + const period = { start: '2025-01-01', end: '2025-01-31' } + + it('calculates earnings per liter correctly', () => { + const entries: LiterEntry[] = [ + { date: '2025-01-05', liters: 50, type: 'wine' }, + { date: '2025-01-15', liters: 30, type: 'spirits' }, + { date: '2025-01-20', liters: 120, type: 'beer' }, + ] + + const result = calculateEarningsPerLiter(100000, entries, period.start, period.end) + + expect(result.totalRevenue).toBe(100000) + expect(result.totalLiters).toBe(200) + expect(result.earningsPerLiter).toBe(500) + expect(result.period).toEqual(period) + }) + + it('returns 0 earnings per liter when no liters sold', () => { + const entries: LiterEntry[] = [] + + const result = calculateEarningsPerLiter(50000, entries, period.start, period.end) + + expect(result.totalRevenue).toBe(50000) + expect(result.totalLiters).toBe(0) + expect(result.earningsPerLiter).toBe(0) + }) + + it('filters entries by date range correctly', () => { + const entries: LiterEntry[] = [ + { date: '2025-01-10', liters: 40, type: 'wine' }, + { date: '2025-02-15', liters: 999, type: 'beer' }, // Outside period + { date: '2024-12-31', liters: 888, type: 'spirits' }, // Outside period + ] + + const result = calculateEarningsPerLiter(20000, entries, period.start, period.end) + + expect(result.totalLiters).toBe(40) + expect(result.earningsPerLiter).toBe(500) + }) + + it('handles monetary rounding correctly', () => { + const entries: LiterEntry[] = [ + { date: '2025-01-10', liters: 3, type: 'spirits' }, + ] + + const result = calculateEarningsPerLiter(10000, entries, period.start, period.end) + + // 10000 / 3 = 3333.333... -> 3333.33 + expect(result.earningsPerLiter).toBe(3333.33) + }) + + it('handles liter rounding correctly', () => { + const entries: LiterEntry[] = [ + { date: '2025-01-05', liters: 1.555, type: 'wine' }, + { date: '2025-01-10', liters: 2.777, type: 'beer' }, + ] + + const result = calculateEarningsPerLiter(5000, entries, period.start, period.end) + + // 1.555 + 2.777 = 4.332 -> rounded to 4.33 + expect(result.totalLiters).toBe(4.33) + }) + + it('includes boundary dates in the period', () => { + const entries: LiterEntry[] = [ + { date: '2025-01-01', liters: 10, type: 'wine' }, + { date: '2025-01-31', liters: 20, type: 'beer' }, + ] + + const result = calculateEarningsPerLiter(9000, entries, period.start, period.end) + + expect(result.totalLiters).toBe(30) + expect(result.earningsPerLiter).toBe(300) + }) +}) diff --git a/extensions/restaurant/earnings-per-liter/lib/earnings-calculator.ts b/extensions/restaurant/earnings-per-liter/lib/earnings-calculator.ts new file mode 100644 index 00000000..063c6047 --- /dev/null +++ b/extensions/restaurant/earnings-per-liter/lib/earnings-calculator.ts @@ -0,0 +1,40 @@ +/** + * Calculate earnings per liter of alcohol sold. + * Earnings Per Liter = Alcohol Revenue / Total Liters Sold + */ +export interface LiterEntry { + date: string + liters: number + type: string // 'spirits' | 'wine' | 'beer' +} + +export interface EarningsPerLiterResult { + totalRevenue: number + totalLiters: number + earningsPerLiter: number + period: { start: string; end: string } +} + +export function calculateEarningsPerLiter( + revenue: number, + entries: LiterEntry[], + periodStart: string, + periodEnd: string +): EarningsPerLiterResult { + const periodEntries = entries.filter( + e => e.date >= periodStart && e.date <= periodEnd + ) + + const totalLiters = periodEntries.reduce((sum, e) => sum + e.liters, 0) + + const earningsPerLiter = totalLiters > 0 + ? Math.round((revenue / totalLiters) * 100) / 100 + : 0 + + return { + totalRevenue: Math.round(revenue * 100) / 100, + totalLiters: Math.round(totalLiters * 100) / 100, + earningsPerLiter, + period: { start: periodStart, end: periodEnd }, + } +} diff --git a/extensions/restaurant/food-cost/index.ts b/extensions/restaurant/food-cost/index.ts new file mode 100644 index 00000000..9eeba578 --- /dev/null +++ b/extensions/restaurant/food-cost/index.ts @@ -0,0 +1,4 @@ +// Food Cost % extension — Pattern A (core data only) +// Reads food purchase accounts (4000-series) and food revenue (3000-series) +// from journal_entry_lines to calculate food cost percentage. +export const FOOD_COST_EXTENSION_ID = 'restaurant/food-cost' diff --git a/extensions/restaurant/food-cost/lib/__tests__/food-cost-calculator.test.ts b/extensions/restaurant/food-cost/lib/__tests__/food-cost-calculator.test.ts new file mode 100644 index 00000000..b783c9fc --- /dev/null +++ b/extensions/restaurant/food-cost/lib/__tests__/food-cost-calculator.test.ts @@ -0,0 +1,114 @@ +import { describe, it, expect } from 'vitest' +import { + calculateFoodCost, + type JournalLineData, +} from '../food-cost-calculator' + +describe('calculateFoodCost', () => { + const period = { start: '2025-01-01', end: '2025-01-31' } + + it('calculates food cost percentage correctly', () => { + const lines: JournalLineData[] = [ + // Food purchases (4010 - varuinkop livsmedel) + { account_number: '4010', debit_amount: 40000, credit_amount: 0, entry_date: '2025-01-15' }, + // Food revenue (3001 - intakter 25%) + { account_number: '3001', debit_amount: 0, credit_amount: 100000, entry_date: '2025-01-15' }, + ] + + const result = calculateFoodCost(lines, period.start, period.end) + + expect(result.foodPurchases).toBe(40000) + expect(result.foodRevenue).toBe(100000) + expect(result.foodCostPercent).toBe(40) + expect(result.period).toEqual(period) + }) + + it('returns 0% when revenue is zero', () => { + const lines: JournalLineData[] = [ + { account_number: '4010', debit_amount: 5000, credit_amount: 0, entry_date: '2025-01-10' }, + ] + + const result = calculateFoodCost(lines, period.start, period.end) + + expect(result.foodPurchases).toBe(5000) + expect(result.foodRevenue).toBe(0) + expect(result.foodCostPercent).toBe(0) + }) + + it('returns 0 purchases and 0 revenue when no matching accounts', () => { + const lines: JournalLineData[] = [ + { account_number: '1930', debit_amount: 10000, credit_amount: 0, entry_date: '2025-01-05' }, + { account_number: '2440', debit_amount: 0, credit_amount: 10000, entry_date: '2025-01-05' }, + ] + + const result = calculateFoodCost(lines, period.start, period.end) + + expect(result.foodPurchases).toBe(0) + expect(result.foodRevenue).toBe(0) + expect(result.foodCostPercent).toBe(0) + }) + + it('filters lines by date range correctly', () => { + const lines: JournalLineData[] = [ + // Inside period + { account_number: '4010', debit_amount: 20000, credit_amount: 0, entry_date: '2025-01-15' }, + { account_number: '3001', debit_amount: 0, credit_amount: 50000, entry_date: '2025-01-15' }, + // Outside period (February) + { account_number: '4010', debit_amount: 99999, credit_amount: 0, entry_date: '2025-02-15' }, + { account_number: '3001', debit_amount: 0, credit_amount: 99999, entry_date: '2025-02-15' }, + ] + + const result = calculateFoodCost(lines, period.start, period.end) + + expect(result.foodPurchases).toBe(20000) + expect(result.foodRevenue).toBe(50000) + expect(result.foodCostPercent).toBe(40) + }) + + it('handles monetary rounding correctly', () => { + const lines: JournalLineData[] = [ + { account_number: '4010', debit_amount: 33333.33, credit_amount: 0, entry_date: '2025-01-10' }, + { account_number: '3001', debit_amount: 0, credit_amount: 99999.99, entry_date: '2025-01-10' }, + ] + + const result = calculateFoodCost(lines, period.start, period.end) + + expect(result.foodPurchases).toBe(33333.33) + expect(result.foodRevenue).toBe(99999.99) + // 33333.33 / 99999.99 * 100 = 33.333334... -> rounded to 33.33 + expect(result.foodCostPercent).toBe(33.33) + }) + + it('handles multiple purchase and revenue lines', () => { + const lines: JournalLineData[] = [ + { account_number: '4010', debit_amount: 15000, credit_amount: 0, entry_date: '2025-01-05' }, + { account_number: '4020', debit_amount: 10000, credit_amount: 0, entry_date: '2025-01-10' }, + { account_number: '4010', debit_amount: 0, credit_amount: 2000, entry_date: '2025-01-12' }, // Return/credit + { account_number: '3001', debit_amount: 0, credit_amount: 60000, entry_date: '2025-01-15' }, + { account_number: '3002', debit_amount: 0, credit_amount: 20000, entry_date: '2025-01-20' }, + ] + + const result = calculateFoodCost(lines, period.start, period.end) + + // Purchases: 15000 + 10000 - 2000 = 23000 + expect(result.foodPurchases).toBe(23000) + // Revenue: 60000 + 20000 = 80000 + expect(result.foodRevenue).toBe(80000) + // 23000 / 80000 * 100 = 28.75 + expect(result.foodCostPercent).toBe(28.75) + }) + + it('includes boundary dates in the period', () => { + const lines: JournalLineData[] = [ + { account_number: '4010', debit_amount: 5000, credit_amount: 0, entry_date: '2025-01-01' }, + { account_number: '4010', debit_amount: 5000, credit_amount: 0, entry_date: '2025-01-31' }, + { account_number: '3001', debit_amount: 0, credit_amount: 50000, entry_date: '2025-01-15' }, + ] + + const result = calculateFoodCost(lines, period.start, period.end) + + expect(result.foodPurchases).toBe(10000) + expect(result.foodRevenue).toBe(50000) + expect(result.foodCostPercent).toBe(20) + }) +}) diff --git a/extensions/restaurant/food-cost/lib/food-cost-calculator.ts b/extensions/restaurant/food-cost/lib/food-cost-calculator.ts new file mode 100644 index 00000000..2362b791 --- /dev/null +++ b/extensions/restaurant/food-cost/lib/food-cost-calculator.ts @@ -0,0 +1,51 @@ +/** + * Calculate food cost percentage from journal entry line data. + * Food Cost % = (Food Purchases / Food Revenue) * 100 + * + * Food purchases: accounts 4000-4999 (varuinkop) + * Food revenue: accounts 3000-3999 (intakter) + */ +export interface FoodCostResult { + foodPurchases: number + foodRevenue: number + foodCostPercent: number + period: { start: string; end: string } +} + +export interface JournalLineData { + account_number: string + debit_amount: number + credit_amount: number + entry_date: string +} + +export function calculateFoodCost( + lines: JournalLineData[], + periodStart: string, + periodEnd: string +): FoodCostResult { + const periodLines = lines.filter( + l => l.entry_date >= periodStart && l.entry_date <= periodEnd + ) + + // Food purchases: debit side of 4000-4999 accounts + const foodPurchases = periodLines + .filter(l => l.account_number >= '4000' && l.account_number <= '4999') + .reduce((sum, l) => sum + l.debit_amount - l.credit_amount, 0) + + // Food revenue: credit side of 3000-3999 accounts + const foodRevenue = periodLines + .filter(l => l.account_number >= '3000' && l.account_number <= '3999') + .reduce((sum, l) => sum + l.credit_amount - l.debit_amount, 0) + + const foodCostPercent = foodRevenue > 0 + ? Math.round((foodPurchases / foodRevenue) * 10000) / 100 + : 0 + + return { + foodPurchases: Math.round(foodPurchases * 100) / 100, + foodRevenue: Math.round(foodRevenue * 100) / 100, + foodCostPercent, + period: { start: periodStart, end: periodEnd }, + } +} diff --git a/extensions/restaurant/pos-import/index.ts b/extensions/restaurant/pos-import/index.ts new file mode 100644 index 00000000..60299110 --- /dev/null +++ b/extensions/restaurant/pos-import/index.ts @@ -0,0 +1,2 @@ +// POS Import extension — Z-rapport import for restaurant POS systems +export const POS_IMPORT_EXTENSION_ID = 'restaurant/pos-import' diff --git a/extensions/restaurant/tip-tracking/index.ts b/extensions/restaurant/tip-tracking/index.ts new file mode 100644 index 00000000..d6a35912 --- /dev/null +++ b/extensions/restaurant/tip-tracking/index.ts @@ -0,0 +1,2 @@ +// Tip Tracking extension — Track tips per shift for restaurant staff +export const TIP_TRACKING_EXTENSION_ID = 'restaurant/tip-tracking' diff --git a/extensions/tech/billable-hours/index.ts b/extensions/tech/billable-hours/index.ts new file mode 100644 index 00000000..519f121c --- /dev/null +++ b/extensions/tech/billable-hours/index.ts @@ -0,0 +1,2 @@ +// Billable Hours extension — Track and report billable consultant hours +export const BILLABLE_HOURS_EXTENSION_ID = 'tech/billable-hours' diff --git a/extensions/tech/project-billing/index.ts b/extensions/tech/project-billing/index.ts new file mode 100644 index 00000000..ba6efaca --- /dev/null +++ b/extensions/tech/project-billing/index.ts @@ -0,0 +1,2 @@ +// Project Billing extension — Track billing per client project +export const PROJECT_BILLING_EXTENSION_ID = 'tech/project-billing' diff --git a/lib/extensions/__tests__/sectors.test.ts b/lib/extensions/__tests__/sectors.test.ts new file mode 100644 index 00000000..07d0fec8 --- /dev/null +++ b/lib/extensions/__tests__/sectors.test.ts @@ -0,0 +1,74 @@ +import { + SECTORS, + getSector, + getExtensionDefinition, + getAllExtensions, + getExtensionsBySector, +} from '../sectors' + +describe('sectors registry', () => { + it('should have 6 sectors', () => { + expect(SECTORS.length).toBe(6) + }) + + it('should have 17 total extensions', () => { + expect(getAllExtensions().length).toBe(17) + }) + + it('should have unique slugs within each sector', () => { + for (const sector of SECTORS) { + const slugs = sector.extensions.map(e => e.slug) + const uniqueSlugs = new Set(slugs) + expect(uniqueSlugs.size).toBe(slugs.length) + } + }) + + it('should have at least one extension per sector', () => { + for (const sector of SECTORS) { + expect(sector.extensions.length).toBeGreaterThan(0) + } + }) + + it('getSector returns correct sector', () => { + const sector = getSector('restaurant') + expect(sector).toBeDefined() + expect(sector!.slug).toBe('restaurant') + expect(sector!.name).toBe('Restaurang & Café') + }) + + it('getSector returns undefined for unknown slug', () => { + const sector = getSector('invalid' as any) + expect(sector).toBeUndefined() + }) + + it('getExtensionDefinition returns correct extension', () => { + const ext = getExtensionDefinition('restaurant', 'food-cost') + expect(ext).toBeDefined() + expect(ext!.slug).toBe('food-cost') + expect(ext!.name).toBe('Food Cost %') + expect(ext!.sector).toBe('restaurant') + }) + + it('getExtensionDefinition returns undefined for unknown extension', () => { + const ext = getExtensionDefinition('restaurant', 'nonexistent') + expect(ext).toBeUndefined() + }) + + it('getExtensionsBySector returns extensions for a sector', () => { + const extensions = getExtensionsBySector('restaurant') + expect(extensions.length).toBe(4) + }) + + it('all extensions have required fields', () => { + for (const ext of getAllExtensions()) { + expect(ext.slug).toBeTruthy() + expect(ext.name).toBeTruthy() + expect(ext.sector).toBeTruthy() + expect(ext.category).toBeTruthy() + expect(ext.description).toBeTruthy() + expect(ext.longDescription).toBeTruthy() + expect(ext.icon).toBeTruthy() + expect(ext.dataPattern).toBeTruthy() + } + }) +}) diff --git a/lib/extensions/__tests__/toggle-check.test.ts b/lib/extensions/__tests__/toggle-check.test.ts new file mode 100644 index 00000000..3a83d24f --- /dev/null +++ b/lib/extensions/__tests__/toggle-check.test.ts @@ -0,0 +1,48 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { createMockSupabase } from '@/tests/helpers' + +const { supabase: mockSupabase, mockResult } = createMockSupabase() +vi.mock('@/lib/supabase/server', () => ({ + createServiceClient: () => Promise.resolve(mockSupabase), +})) + +import { isExtensionEnabled } from '../toggle-check' + +describe('isExtensionEnabled', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('returns true when toggle exists and is enabled', async () => { + mockResult({ data: { enabled: true }, error: null }) + + const result = await isExtensionEnabled('user-1', 'general', 'receipt-ocr') + + expect(result).toBe(true) + expect(mockSupabase.from).toHaveBeenCalledWith('extension_toggles') + }) + + it('returns false when toggle exists and is disabled', async () => { + mockResult({ data: { enabled: false }, error: null }) + + const result = await isExtensionEnabled('user-1', 'general', 'receipt-ocr') + + expect(result).toBe(false) + }) + + it('returns true for legacy general extensions when no toggle row exists', async () => { + mockResult({ data: null, error: null }) + + const result = await isExtensionEnabled('user-1', 'general', 'receipt-ocr') + + expect(result).toBe(true) + }) + + it('returns false for non-legacy extensions when no toggle row exists', async () => { + mockResult({ data: null, error: null }) + + const result = await isExtensionEnabled('user-1', 'restaurant', 'tip-tracking') + + expect(result).toBe(false) + }) +}) diff --git a/lib/extensions/hooks.ts b/lib/extensions/hooks.ts new file mode 100644 index 00000000..267cb15d --- /dev/null +++ b/lib/extensions/hooks.ts @@ -0,0 +1,72 @@ +'use client' + +import { useState, useEffect, useCallback } from 'react' +import type { ExtensionToggle } from './types' + +export function useEnabledExtensions() { + const [extensions, setExtensions] = useState([]) + const [isLoading, setIsLoading] = useState(true) + + const refresh = useCallback(async () => { + setIsLoading(true) + try { + const res = await fetch('/api/extensions/toggles') + if (res.ok) { + const { data } = await res.json() + setExtensions(data ?? []) + } + } finally { + setIsLoading(false) + } + }, []) + + useEffect(() => { + refresh() + }, [refresh]) + + return { extensions, isLoading, refresh } +} + +export function useExtensionToggle(sectorSlug: string, extensionSlug: string) { + const [enabled, setEnabled] = useState(false) + const [isLoading, setIsLoading] = useState(true) + + useEffect(() => { + const check = async () => { + setIsLoading(true) + try { + const res = await fetch(`/api/extensions/toggles/${sectorSlug}/${extensionSlug}`) + if (res.ok) { + const { data } = await res.json() + setEnabled(data?.enabled ?? false) + } + } finally { + setIsLoading(false) + } + } + check() + }, [sectorSlug, extensionSlug]) + + const toggle = useCallback(async () => { + const newValue = !enabled + setEnabled(newValue) // Optimistic update + try { + const res = await fetch('/api/extensions/toggles', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + sector_slug: sectorSlug, + extension_slug: extensionSlug, + enabled: newValue, + }), + }) + if (!res.ok) { + setEnabled(!newValue) // Revert on error + } + } catch { + setEnabled(!newValue) // Revert on error + } + }, [enabled, sectorSlug, extensionSlug]) + + return { enabled, isLoading, toggle } +} diff --git a/lib/extensions/icon-resolver.tsx b/lib/extensions/icon-resolver.tsx new file mode 100644 index 00000000..00f25858 --- /dev/null +++ b/lib/extensions/icon-resolver.tsx @@ -0,0 +1,58 @@ +import { + Camera, + Sparkles, + MessageSquare, + Bell, + Landmark, + UtensilsCrossed, + ChefHat, + Wine, + FileSpreadsheet, + HandCoins, + HardHat, + Calculator, + FolderKanban, + Hotel, + TrendingUp, + BedDouble, + Monitor, + Clock, + ReceiptText, + ShoppingCart, + Store, + BarChart3, + Layers, + Puzzle, + type LucideIcon, +} from 'lucide-react' + +const ICON_MAP: Record = { + Camera, + Sparkles, + MessageSquare, + Bell, + Landmark, + UtensilsCrossed, + ChefHat, + Wine, + FileSpreadsheet, + HandCoins, + HardHat, + Calculator, + FolderKanban, + Hotel, + TrendingUp, + BedDouble, + Monitor, + Clock, + ReceiptText, + ShoppingCart, + Store, + BarChart3, + Layers, + Puzzle, +} + +export function resolveIcon(name: string): LucideIcon { + return ICON_MAP[name] ?? Puzzle +} diff --git a/lib/extensions/loader.ts b/lib/extensions/loader.ts index 9bb8b9d4..1c28ad04 100644 --- a/lib/extensions/loader.ts +++ b/lib/extensions/loader.ts @@ -1,17 +1,17 @@ import { extensionRegistry } from './registry' -import { receiptOcrExtension } from '@/extensions/receipt-ocr' -import { aiCategorizationExtension } from '@/extensions/ai-categorization' -import { pushNotificationsExtension } from '@/extensions/push-notifications' +import { receiptOcrExtension } from '@/extensions/general/receipt-ocr' +import { aiCategorizationExtension } from '@/extensions/general/ai-categorization' +import { pushNotificationsExtension } from '@/extensions/general/push-notifications' import { sruExportExtension } from '@/extensions/sru-export' import { neBilagaExtension } from '@/extensions/ne-bilaga' -import { aiChatExtension } from '@/extensions/ai-chat' +import { aiChatExtension } from '@/extensions/general/ai-chat' import type { Extension } from './types' // ── Enable Banking (PSD2) — opt-in extension ─────────────────────────── // Uncomment the following line to enable automatic PSD2 bank transaction sync. // Requires ENABLE_BANKING_APP_ID and ENABLE_BANKING_PRIVATE_KEY env vars. // -// import { enableBankingExtension } from '@/extensions/enable-banking' +// import { enableBankingExtension } from '@/extensions/general/enable-banking' /** * Explicit list of first-party extensions. diff --git a/lib/extensions/sectors.ts b/lib/extensions/sectors.ts new file mode 100644 index 00000000..e908f4d7 --- /dev/null +++ b/lib/extensions/sectors.ts @@ -0,0 +1,304 @@ +import type { Sector, SectorSlug, ExtensionDefinition } from './types' + +// ============================================================ +// Sector & Extension Registry +// ============================================================ +// +// Pure data file. No React, no database calls. +// All sector and extension metadata lives here. +// ============================================================ + +export const SECTORS: Sector[] = [ + // ── General ────────────────────────────────────────────── + { + slug: 'general', + name: 'Generella verktyg', + icon: 'Layers', + description: 'Verktyg som passar alla verksamheter', + extensions: [ + { + slug: 'receipt-ocr', + name: 'Kvittoscanning', + sector: 'general', + category: 'import', + icon: 'Camera', + dataPattern: 'manual', + hasOwnData: true, + description: 'Skanna kvitton och extrahera data automatiskt', + longDescription: + 'Ladda upp kvittofoton och låt systemet automatiskt extrahera leverantör, belopp, moms och datum. Sparar tid och minskar manuell inmatning.', + }, + { + slug: 'ai-categorization', + name: 'AI-kategorisering', + sector: 'general', + category: 'operations', + icon: 'Sparkles', + dataPattern: 'core', + readsCoreTables: ['transactions'], + description: 'AI-drivna kategoriförslag för transaktioner', + longDescription: + 'Använder AI för att automatiskt föreslå BAS-kontokategorier för dina banktransaktioner. Lär sig från dina tidigare bokföringsval.', + }, + { + slug: 'ai-chat', + name: 'AI-assistent', + sector: 'general', + category: 'operations', + icon: 'MessageSquare', + dataPattern: 'manual', + hasOwnData: true, + description: 'AI-assistent för skatte- och bokföringsfrågor', + longDescription: + 'Ställ frågor om skatt, bokföring och företagande till en AI-assistent som förstår svensk redovisning. Svar baserade på aktuella regler och praxis.', + }, + { + slug: 'push-notifications', + name: 'Push-notiser', + sector: 'general', + category: 'operations', + icon: 'Bell', + dataPattern: 'core', + readsCoreTables: ['journal_entries', 'invoices', 'receipts'], + description: 'Händelsenotiser för bokföringsaktiviteter', + longDescription: + 'Få push-notiser direkt i webbläsaren när viktiga händelser sker — nya fakturor, förfallna betalningar, slutförda bokföringar med mera.', + }, + { + slug: 'enable-banking', + name: 'Bankintegration (PSD2)', + sector: 'general', + category: 'import', + icon: 'Landmark', + dataPattern: 'manual', + hasOwnData: true, + description: 'Automatisk banktransaktionssynk via PSD2', + longDescription: + 'Koppla ditt bankkonto direkt och synka transaktioner automatiskt via säker PSD2-bankintegration. Stöder de flesta svenska banker.', + }, + ], + }, + + // ── Restaurant ─────────────────────────────────────────── + { + slug: 'restaurant', + name: 'Restaurang & Café', + icon: 'UtensilsCrossed', + description: 'Branschverktyg för restauranger och caféverksamhet', + extensions: [ + { + slug: 'food-cost', + name: 'Food Cost %', + sector: 'restaurant', + category: 'reports', + icon: 'ChefHat', + dataPattern: 'core', + readsCoreTables: ['journal_entry_lines'], + description: 'Beräkna råvarukostnad i procent av omsättning', + longDescription: + 'Beräkna och följ upp din råvarukostnadsprocent (food cost) automatiskt utifrån bokföringen. Jämför inköpskonton (4000-serien) mot livsmedelsomsättning (3000-serien) och se trender över tid.', + }, + { + slug: 'earnings-per-liter', + name: 'Intäkt per liter alkohol', + sector: 'restaurant', + category: 'reports', + icon: 'Wine', + dataPattern: 'both', + readsCoreTables: ['journal_entry_lines'], + hasOwnData: true, + description: 'Beräkna intäkt per såld liter alkohol', + longDescription: + 'Kombinerar alkoholintäkter från bokföringen med manuellt inmatade literuppgifter för att räkna ut intäkt per liter. Följ trender och optimera ditt sortiment.', + }, + { + slug: 'pos-import', + name: 'Kassa Z-rapport Import', + sector: 'restaurant', + category: 'import', + icon: 'FileSpreadsheet', + dataPattern: 'manual', + hasOwnData: true, + description: 'Importera Z-rapporter från kassasystem', + longDescription: + 'Importera dagliga Z-rapporter från ditt kassasystem (CSV/Excel). Se daglig försäljningsstatistik, betalsättsfördelning och trender.', + }, + { + slug: 'tip-tracking', + name: 'Dricksuppföljning', + sector: 'restaurant', + category: 'operations', + icon: 'HandCoins', + dataPattern: 'both', + readsCoreTables: ['journal_entry_lines'], + hasOwnData: true, + description: 'Spåra dricks per skift och anställd', + longDescription: + 'Registrera dricks per skift och anställd. Se totaler, snitt per anställd och dricks som andel av omsättningen.', + }, + ], + }, + + // ── Construction ───────────────────────────────────────── + { + slug: 'construction', + name: 'Bygg & Anläggning', + icon: 'HardHat', + description: 'Branschverktyg för byggföretag och hantverkare', + extensions: [ + { + slug: 'rot-calculator', + name: 'ROT-kalkylator', + sector: 'construction', + category: 'accounting', + icon: 'Calculator', + dataPattern: 'both', + readsCoreTables: ['invoices'], + hasOwnData: true, + description: 'Beräkna ROT-avdrag per kund och jobb', + longDescription: + 'Beräkna ROT-avdrag (30% av arbetskostnad, max 50 000 kr/år per kund). Håll koll på utnyttjad kvot per kund och undvik att överskrida maxbeloppet.', + }, + { + slug: 'project-cost', + name: 'Projektkostnad', + sector: 'construction', + category: 'reports', + icon: 'FolderKanban', + dataPattern: 'both', + readsCoreTables: ['journal_entry_lines', 'invoices'], + hasOwnData: true, + description: 'Följ upp kostnader och intäkter per byggprojekt', + longDescription: + 'Samla alla kostnader och intäkter för varje byggprojekt. Se marginaler, jämför budget mot utfall och identifiera olönsamma projekt.', + }, + ], + }, + + // ── Hotel ──────────────────────────────────────────────── + { + slug: 'hotel', + name: 'Hotell & Logi', + icon: 'Hotel', + description: 'Branschverktyg för hotell och logi', + extensions: [ + { + slug: 'revpar', + name: 'RevPAR', + sector: 'hotel', + category: 'reports', + icon: 'TrendingUp', + dataPattern: 'both', + readsCoreTables: ['journal_entry_lines'], + hasOwnData: true, + description: 'Revenue Per Available Room', + longDescription: + 'Beräkna Revenue Per Available Room (RevPAR) — det viktigaste nyckeltalet inom hotellbranschen. Kombinerar beläggningsgrad och snittpris per rum.', + }, + { + slug: 'occupancy', + name: 'Beläggningsgrad', + sector: 'hotel', + category: 'reports', + icon: 'BedDouble', + dataPattern: 'manual', + hasOwnData: true, + description: 'Spåra beläggning och rumsstatus', + longDescription: + 'Registrera daglig beläggning, tillgängliga rum och belagda rum. Se beläggningsgrad över tid och identifiera säsongsmönster.', + }, + ], + }, + + // ── Tech ───────────────────────────────────────────────── + { + slug: 'tech', + name: 'IT & Konsulting', + icon: 'Monitor', + description: 'Branschverktyg för IT-konsulter och teknikföretag', + extensions: [ + { + slug: 'billable-hours', + name: 'Debiterbar tid', + sector: 'tech', + category: 'reports', + icon: 'Clock', + dataPattern: 'both', + readsCoreTables: ['invoices'], + hasOwnData: true, + description: 'Följ debiteringsgrad och effektiv timtaxa', + longDescription: + 'Registrera arbetade timmar per projekt och beräkna debiteringsgrad (debiterbar/total tid). Se effektiv timtaxa och optimera din tidsanvändning.', + }, + { + slug: 'project-billing', + name: 'Projektfakturering', + sector: 'tech', + category: 'reports', + icon: 'ReceiptText', + dataPattern: 'both', + readsCoreTables: ['invoices', 'journal_entry_lines'], + hasOwnData: true, + description: 'Fakturerade belopp per projekt och kund', + longDescription: + 'Följ fakturerade belopp per projekt och kund. Jämför mot budget, se olönsamma projekt och identifiera dina mest lönsamma kunder.', + }, + ], + }, + + // ── E-commerce ─────────────────────────────────────────── + { + slug: 'ecommerce', + name: 'E-handel', + icon: 'ShoppingCart', + description: 'Branschverktyg för nätbutiker och e-handel', + extensions: [ + { + slug: 'shopify-import', + name: 'Shopify-import', + sector: 'ecommerce', + category: 'import', + icon: 'Store', + dataPattern: 'manual', + hasOwnData: true, + description: 'Importera ordrar från Shopify', + longDescription: + 'Importera orderdata från Shopify-export (CSV). Se intäkter per produkt, ordertrender och genomsnittligt ordervärde.', + }, + { + slug: 'multichannel-revenue', + name: 'Flerkanalsintäkter', + sector: 'ecommerce', + category: 'reports', + icon: 'BarChart3', + dataPattern: 'both', + readsCoreTables: ['journal_entry_lines'], + hasOwnData: true, + description: 'Intäktsanalys per försäljningskanal', + longDescription: + 'Analysera intäkter fördelat på försäljningskanaler — webshop, marknadsplatser, fysisk butik. Identifiera dina mest lönsamma kanaler.', + }, + ], + }, +] + +// ============================================================ +// Helper functions +// ============================================================ + +export function getSector(slug: SectorSlug): Sector | undefined { + return SECTORS.find(s => s.slug === slug) +} + +export function getExtensionDefinition(sectorSlug: string, extensionSlug: string): ExtensionDefinition | undefined { + const sector = SECTORS.find(s => s.slug === sectorSlug) + return sector?.extensions.find(e => e.slug === extensionSlug) +} + +export function getAllExtensions(): ExtensionDefinition[] { + return SECTORS.flatMap(s => s.extensions) +} + +export function getExtensionsBySector(slug: SectorSlug): ExtensionDefinition[] { + return getSector(slug)?.extensions ?? [] +} diff --git a/lib/extensions/toggle-check.ts b/lib/extensions/toggle-check.ts new file mode 100644 index 00000000..d4a2618f --- /dev/null +++ b/lib/extensions/toggle-check.ts @@ -0,0 +1,40 @@ +import { createServiceClient } from '@/lib/supabase/server' + +/** + * Check if an extension is enabled for a specific user. + * Used by event handlers to gate execution. + * + * For backward compatibility during the transition period, + * general extensions that were previously always-on default to + * enabled when no toggle row exists. + */ +const LEGACY_GENERAL_EXTENSIONS = [ + 'receipt-ocr', + 'ai-categorization', + 'ai-chat', + 'push-notifications', + 'enable-banking', +] + +export async function isExtensionEnabled( + userId: string, + sectorSlug: string, + extensionSlug: string +): Promise { + const supabase = await createServiceClient() + + const { data } = await supabase + .from('extension_toggles') + .select('enabled') + .eq('user_id', userId) + .eq('sector_slug', sectorSlug) + .eq('extension_slug', extensionSlug) + .single() + + // If no toggle row exists, check if this is a legacy extension + if (!data) { + return sectorSlug === 'general' && LEGACY_GENERAL_EXTENSIONS.includes(extensionSlug) + } + + return data.enabled +} diff --git a/lib/extensions/types.ts b/lib/extensions/types.ts index 736a77f0..bfd917a5 100644 --- a/lib/extensions/types.ts +++ b/lib/extensions/types.ts @@ -1,4 +1,53 @@ import type { CoreEventType } from '@/lib/events/types' +import type { EntityType } from '@/types' + +// ============================================================ +// Extension Marketplace Types +// ============================================================ + +/** Extension category for marketplace grouping */ +export type ExtensionCategory = 'accounting' | 'reports' | 'import' | 'operations' + +/** Sector slugs for extension organization */ +export type SectorSlug = 'general' | 'restaurant' | 'construction' | 'hotel' | 'tech' | 'ecommerce' + +/** How an extension gets its data */ +export type ExtensionDataPattern = 'core' | 'manual' | 'both' + +/** Extension metadata for the marketplace and workspace routing */ +export interface ExtensionDefinition { + slug: string + name: string + sector: SectorSlug + category: ExtensionCategory + description: string + longDescription: string + icon: string + entityTypes?: EntityType[] + dataPattern: ExtensionDataPattern + readsCoreTables?: string[] + hasOwnData?: boolean +} + +/** Sector definition with its extensions */ +export interface Sector { + slug: SectorSlug + name: string + icon: string + description: string + extensions: ExtensionDefinition[] +} + +/** Database row for extension toggle state */ +export interface ExtensionToggle { + id: string + user_id: string + sector_slug: string + extension_slug: string + enabled: boolean + created_at: string + updated_at: string +} // ============================================================ // Extension Interface & Supporting Types diff --git a/lib/extensions/workspace-registry.tsx b/lib/extensions/workspace-registry.tsx new file mode 100644 index 00000000..bf68d3c0 --- /dev/null +++ b/lib/extensions/workspace-registry.tsx @@ -0,0 +1,41 @@ +import dynamic from 'next/dynamic' +import type { ComponentType } from 'react' + +export interface WorkspaceComponentProps { + userId: string +} + +type WorkspaceKey = `${string}/${string}` + +const WORKSPACES: Record> = { + // General + 'general/receipt-ocr': dynamic(() => import('@/components/extensions/general/ReceiptOcrWorkspace')), + 'general/ai-categorization': dynamic(() => import('@/components/extensions/general/AiCategorizationWorkspace')), + 'general/ai-chat': dynamic(() => import('@/components/extensions/general/AiChatWorkspace')), + 'general/push-notifications': dynamic(() => import('@/components/extensions/general/PushNotificationsWorkspace')), + 'general/enable-banking': dynamic(() => import('@/components/extensions/general/EnableBankingWorkspace')), + // Restaurant + 'restaurant/food-cost': dynamic(() => import('@/components/extensions/restaurant/FoodCostWorkspace')), + 'restaurant/earnings-per-liter': dynamic(() => import('@/components/extensions/restaurant/EarningsPerLiterWorkspace')), + 'restaurant/pos-import': dynamic(() => import('@/components/extensions/restaurant/PosImportWorkspace')), + 'restaurant/tip-tracking': dynamic(() => import('@/components/extensions/restaurant/TipTrackingWorkspace')), + // Construction + 'construction/rot-calculator': dynamic(() => import('@/components/extensions/construction/RotCalculatorWorkspace')), + 'construction/project-cost': dynamic(() => import('@/components/extensions/construction/ProjectCostWorkspace')), + // Hotel + 'hotel/revpar': dynamic(() => import('@/components/extensions/hotel/RevparWorkspace')), + 'hotel/occupancy': dynamic(() => import('@/components/extensions/hotel/OccupancyWorkspace')), + // Tech + 'tech/billable-hours': dynamic(() => import('@/components/extensions/tech/BillableHoursWorkspace')), + 'tech/project-billing': dynamic(() => import('@/components/extensions/tech/ProjectBillingWorkspace')), + // E-commerce + 'ecommerce/shopify-import': dynamic(() => import('@/components/extensions/ecommerce/ShopifyImportWorkspace')), + 'ecommerce/multichannel-revenue': dynamic(() => import('@/components/extensions/ecommerce/MultichannelRevenueWorkspace')), +} + +export function getWorkspaceComponent( + sector: string, + slug: string +): ComponentType | null { + return WORKSPACES[`${sector}/${slug}` as WorkspaceKey] ?? null +} diff --git a/scripts/copy-extensions.mjs b/scripts/copy-extensions.mjs new file mode 100644 index 00000000..fb821a05 --- /dev/null +++ b/scripts/copy-extensions.mjs @@ -0,0 +1,36 @@ +import { cpSync, rmSync, existsSync } from 'fs' +import { join } from 'path' + +const root = process.cwd() +const extensions = ['receipt-ocr', 'ai-categorization', 'ai-chat', 'push-notifications', 'enable-banking', 'example-logger'] + +for (const ext of extensions) { + const src = join(root, 'extensions', ext) + const dest = join(root, 'extensions', 'general', ext) + + if (!existsSync(src)) { + console.log(`SKIP: ${src} does not exist`) + continue + } + + if (existsSync(dest)) { + console.log(`CLEAN: ${dest} already exists, removing`) + rmSync(dest, { recursive: true, force: true }) + } + + console.log(`COPY: ${src} -> ${dest}`) + cpSync(src, dest, { recursive: true }) +} + +console.log('Done copying extensions to general/') + +// Now remove the old directories +for (const ext of extensions) { + const src = join(root, 'extensions', ext) + if (existsSync(src)) { + console.log(`REMOVE: ${src}`) + rmSync(src, { recursive: true, force: true }) + } +} + +console.log('Done removing old extension directories') diff --git a/scripts/move-extensions.js b/scripts/move-extensions.js new file mode 100644 index 00000000..21a50157 --- /dev/null +++ b/scripts/move-extensions.js @@ -0,0 +1,33 @@ +const fs = require('fs'); +const path = require('path'); + +const root = path.resolve(__dirname, '..'); +const extsDir = path.join(root, 'extensions'); +const generalDir = path.join(extsDir, 'general'); + +const dirs = [ + 'receipt-ocr', + 'ai-categorization', + 'ai-chat', + 'push-notifications', + 'enable-banking', + 'example-logger', +]; + +if (!fs.existsSync(generalDir)) { + fs.mkdirSync(generalDir, { recursive: true }); +} + +for (const ext of dirs) { + const src = path.join(extsDir, ext); + const dest = path.join(generalDir, ext); + if (fs.existsSync(src)) { + fs.cpSync(src, dest, { recursive: true }); + fs.rmSync(src, { recursive: true, force: true }); + console.log('Done: ' + ext); + } else { + console.log('Skip: ' + ext); + } +} + +console.log('All done.'); diff --git a/scripts/setup-phase8.js b/scripts/setup-phase8.js new file mode 100644 index 00000000..837cf06e --- /dev/null +++ b/scripts/setup-phase8.js @@ -0,0 +1 @@ +const fs=require('fs'),p=require('path'),r=p.resolve(__dirname,'..'),b=p.join(r,'extensions'),t=p.join(b,'general'),d=['receipt-ocr','ai-categorization','ai-chat','push-notifications','enable-banking','example-logger'];fs.mkdirSync(t,{recursive:!0});d.forEach(n=>{const s=p.join(b,n),e=p.join(t,n);fs.existsSync(s)?(fs.cpSync(s,e,{recursive:!0}),fs.rmSync(s,{recursive:!0,force:!0}),console.log(n)):console.log('!'+n)}); diff --git a/supabase/migrations/20240101000029_extension_toggles.sql b/supabase/migrations/20240101000029_extension_toggles.sql new file mode 100644 index 00000000..9d9935d4 --- /dev/null +++ b/supabase/migrations/20240101000029_extension_toggles.sql @@ -0,0 +1,37 @@ +-- Extension Toggles +-- Tracks which extensions each user has enabled. + +create table public.extension_toggles ( + id uuid primary key default gen_random_uuid(), + user_id uuid not null references auth.users on delete cascade, + sector_slug text not null, + extension_slug text not null, + enabled boolean not null default true, + created_at timestamptz not null default now(), + updated_at timestamptz not null default now(), + constraint extension_toggles_unique unique (user_id, sector_slug, extension_slug) +); + +alter table public.extension_toggles enable row level security; + +create policy "extension_toggles_select" on public.extension_toggles + for select using (auth.uid() = user_id); +create policy "extension_toggles_insert" on public.extension_toggles + for insert with check (auth.uid() = user_id); +create policy "extension_toggles_update" on public.extension_toggles + for update using (auth.uid() = user_id); +create policy "extension_toggles_delete" on public.extension_toggles + for delete using (auth.uid() = user_id); + +create index extension_toggles_user_idx + on public.extension_toggles (user_id); +create index extension_toggles_user_sector_idx + on public.extension_toggles (user_id, sector_slug, extension_slug); + +create trigger extension_toggles_updated_at + before update on public.extension_toggles + for each row execute function public.update_updated_at_column(); + +-- Add sector_slug to company_settings +alter table public.company_settings + add column if not exists sector_slug text; diff --git a/tests/helpers.ts b/tests/helpers.ts index 100c7163..9e410314 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -16,6 +16,7 @@ import type { SupplierInvoice, CompanySettings, } from '@/types' +import type { ExtensionToggle } from '@/lib/extensions/types' // ============================================================ // Chainable Supabase mock @@ -435,6 +436,22 @@ export function makeCompanySettings( invoice_default_days: 30, onboarding_step: 6, onboarding_complete: true, + sector_slug: null, + created_at: '2024-01-01T00:00:00Z', + updated_at: '2024-01-01T00:00:00Z', + ...overrides, + } +} + +export function makeExtensionToggle( + overrides: Partial = {} +): ExtensionToggle { + return { + id: nextId(), + user_id: 'user-1', + sector_slug: 'general', + extension_slug: 'receipt-ocr', + enabled: true, created_at: '2024-01-01T00:00:00Z', updated_at: '2024-01-01T00:00:00Z', ...overrides, diff --git a/types/index.ts b/types/index.ts index 73629f8b..053c7bd9 100644 --- a/types/index.ts +++ b/types/index.ts @@ -118,6 +118,9 @@ export interface CompanySettings { onboarding_step: number onboarding_complete: boolean + // Sector + sector_slug: string | null + // Timestamps created_at: string updated_at: string @@ -1143,7 +1146,7 @@ export interface CreateDeadlineInput { // ============================================================ // Push Notification Types (canonical source: extensions/push-notifications/types.ts) // ============================================================ -export type { PushSubscription, NotificationSettings, NotificationType, NotificationLog } from '@/extensions/push-notifications/types' +export type { PushSubscription, NotificationSettings, NotificationType, NotificationLog } from '@/extensions/general/push-notifications/types' // ============================================================ // Calendar Feed Types (ICS) @@ -1239,8 +1242,8 @@ export interface SIEAccountMapping { // ============================================================ // Receipt Types (canonical source: extensions/receipt-ocr/types.ts) // ============================================================ -export type { ReceiptStatus, Receipt, ReceiptLineItem, ReceiptExtractionResult, ExtractedLineItem, ReceiptMatchCandidate, CreateReceiptInput, ConfirmReceiptInput, ConfirmLineItemInput, ReceiptQueueSummary, CameraQualityFeedback } from '@/extensions/receipt-ocr/types' -export { RECEIPT_STATUS_LABELS } from '@/extensions/receipt-ocr/types' +export type { ReceiptStatus, Receipt, ReceiptLineItem, ReceiptExtractionResult, ExtractedLineItem, ReceiptMatchCandidate, CreateReceiptInput, ConfirmReceiptInput, ConfirmLineItemInput, ReceiptQueueSummary, CameraQualityFeedback } from '@/extensions/general/receipt-ocr/types' +export { RECEIPT_STATUS_LABELS } from '@/extensions/general/receipt-ocr/types' // ============================================================ // VAT Declaration Types (Momsdeklaration)