Fix/multiple company (#203)
* Refactor onboarding and dashboard logic; add silent team creation for users - Removed unnecessary useCompany context in DashboardContent and SettingsSidebar components. - Simplified onboarding setup logic to allow direct access to the dashboard for users without companies. - Introduced WelcomeOnboarding component to handle user onboarding steps. - Added migration to create silent teams for all users at signup, backfilling existing users without teams, and cleaning up incomplete companies. * fix: update greeting logic and improve email handling in TIC extension * Redirect to onboarding for users without companies and update onboarding flow * Build issue fix * Enhance onboarding experience by adding existing companies check
This commit is contained in:
@@ -136,27 +136,37 @@ export async function GET(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if user has completed onboarding (for any company they belong to)
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('company_id')
|
||||
// Ensure user has a silent team (for new signups and existing users without one)
|
||||
const { data: teamMembership } = await supabase
|
||||
.from('team_members')
|
||||
.select('team_id')
|
||||
.eq('user_id', user.id)
|
||||
.limit(1)
|
||||
.single()
|
||||
.maybeSingle()
|
||||
|
||||
if (membership?.company_id) {
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
.eq('company_id', membership.company_id)
|
||||
.single()
|
||||
if (!teamMembership) {
|
||||
// Create team via service client (RPC requires auth.uid() which isn't available here)
|
||||
const serviceClient = createServerClient(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
{ cookies: { getAll: () => [], setAll: () => {} } }
|
||||
)
|
||||
|
||||
if (!settings?.onboarding_complete) {
|
||||
redirectPath = '/onboarding'
|
||||
}
|
||||
} else {
|
||||
redirectPath = '/onboarding'
|
||||
const teamId = crypto.randomUUID()
|
||||
await serviceClient.from('teams').insert({
|
||||
id: teamId,
|
||||
name: 'Personal',
|
||||
created_by: user.id,
|
||||
})
|
||||
await serviceClient.from('team_members').insert({
|
||||
team_id: teamId,
|
||||
user_id: user.id,
|
||||
role: 'owner',
|
||||
})
|
||||
}
|
||||
|
||||
// Always redirect to dashboard — it handles zero-company and incomplete states
|
||||
redirectPath = '/'
|
||||
}
|
||||
|
||||
// Create redirect and explicitly set auth cookies on the response
|
||||
|
||||
@@ -127,7 +127,7 @@ function RegisterPageContent() {
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/onboarding')
|
||||
router.push('/')
|
||||
router.refresh()
|
||||
} catch (error) {
|
||||
console.error('[register] BankID signup error', error)
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Plus, Search, Users } from 'lucide-react'
|
||||
import CustomerForm from '@/components/customers/CustomerForm'
|
||||
import { EmptyCustomers } from '@/components/ui/empty-state'
|
||||
import Link from 'next/link'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { Customer, CustomerType, CreateCustomerInput } from '@/types'
|
||||
|
||||
const customerTypeLabels: Record<CustomerType, string> = {
|
||||
@@ -31,6 +32,7 @@ function getInitials(name: string): string {
|
||||
}
|
||||
|
||||
export default function CustomersPage() {
|
||||
const { company } = useCompany()
|
||||
const [customers, setCustomers] = useState<Customer[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -40,10 +42,12 @@ export default function CustomersPage() {
|
||||
const supabase = createClient()
|
||||
|
||||
async function fetchCustomers() {
|
||||
if (!company) return
|
||||
setIsLoading(true)
|
||||
const { data, error } = await supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('company_id', company.id)
|
||||
.order('name', { ascending: true })
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -8,11 +8,13 @@ import { ToastAction } from '@/components/ui/toast'
|
||||
import { DeadlineList } from '@/components/deadlines/DeadlineList'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { AlertTriangle, ArrowRight } from 'lucide-react'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { Deadline } from '@/types'
|
||||
|
||||
const supabase = createClient()
|
||||
|
||||
export default function DeadlinesPage() {
|
||||
const { company } = useCompany()
|
||||
const [deadlines, setDeadlines] = useState<Deadline[]>([])
|
||||
const [customers, setCustomers] = useState<{ id: string; name: string }[]>([])
|
||||
const [overdueInvoices, setOverdueInvoices] = useState<{ count: number; total: number }>({ count: 0, total: 0 })
|
||||
@@ -20,15 +22,16 @@ export default function DeadlinesPage() {
|
||||
const { toast } = useToast()
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!company) return
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const today = new Date().toISOString().split('T')[0]
|
||||
|
||||
const [deadlinesRes, customersRes, overdueRes] = await Promise.all([
|
||||
supabase.from('deadlines').select('*, customer:customers(name)').order('due_date', { ascending: true }),
|
||||
supabase.from('customers').select('id, name').order('name', { ascending: true }),
|
||||
supabase.from('invoices').select('total_sek, total').in('status', ['sent', 'unpaid']).lt('due_date', today),
|
||||
supabase.from('deadlines').select('*, customer:customers(name)').eq('company_id', company.id).order('due_date', { ascending: true }),
|
||||
supabase.from('customers').select('id, name').eq('company_id', company.id).order('name', { ascending: true }),
|
||||
supabase.from('invoices').select('total_sek, total').eq('company_id', company.id).in('status', ['sent', 'unpaid']).lt('due_date', today),
|
||||
])
|
||||
|
||||
if (deadlinesRes.error) throw deadlinesRes.error
|
||||
|
||||
@@ -13,6 +13,7 @@ import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { Plus, Search, Wallet, Clock, AlertCircle } from 'lucide-react'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { SupplierInvoice } from '@/types'
|
||||
|
||||
type ExpenseInvoice = SupplierInvoice & { supplier?: { id: string; name: string } }
|
||||
@@ -60,6 +61,7 @@ function getRelativeTimeLabel(dueDateStr: string, status: string): { text: strin
|
||||
}
|
||||
|
||||
export default function ExpensesPage() {
|
||||
const { company } = useCompany()
|
||||
const [invoices, setInvoices] = useState<ExpenseInvoice[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -68,10 +70,12 @@ export default function ExpensesPage() {
|
||||
const supabase = createClient()
|
||||
|
||||
async function fetchExpenses() {
|
||||
if (!company) return
|
||||
setIsLoading(true)
|
||||
const { data, error } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select('*, supplier:suppliers(id, name)')
|
||||
.eq('company_id', company.id)
|
||||
.order('due_date', { ascending: true })
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { Plus, Search, Receipt } from 'lucide-react'
|
||||
import { EmptyInvoices } from '@/components/ui/empty-state'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { Invoice, InvoiceStatus } from '@/types'
|
||||
|
||||
const statusConfig: Record<InvoiceStatus, { label: string; variant: 'default' | 'secondary' | 'success' | 'warning' | 'destructive'; borderColor: string }> = {
|
||||
@@ -49,6 +50,7 @@ function getRelativeTimeLabel(dueDateStr: string, status: InvoiceStatus): { text
|
||||
}
|
||||
|
||||
export default function InvoicesPage() {
|
||||
const { company } = useCompany()
|
||||
const [invoices, setInvoices] = useState<Invoice[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -57,10 +59,12 @@ export default function InvoicesPage() {
|
||||
const supabase = createClient()
|
||||
|
||||
async function fetchInvoices() {
|
||||
if (!company) return
|
||||
setIsLoading(true)
|
||||
const { data, error } = await supabase
|
||||
.from('invoices')
|
||||
.select('*, customer:customers(name)')
|
||||
.eq('company_id', company.id)
|
||||
.order('invoice_date', { ascending: false })
|
||||
|
||||
if (error) {
|
||||
|
||||
+39
-81
@@ -47,45 +47,8 @@ export default async function DashboardLayout({
|
||||
|
||||
const isTeamMember = !!teamMembership
|
||||
|
||||
// Consultant with team but no companies — show dashboard with empty state
|
||||
// No companies — redirect to onboarding
|
||||
if (!companyId) {
|
||||
if (isTeamMember) {
|
||||
const companyContextValue = {
|
||||
company: null,
|
||||
role: null,
|
||||
companies: [],
|
||||
isTeamMember: true,
|
||||
team,
|
||||
}
|
||||
|
||||
return (
|
||||
<CompanyProvider value={companyContextValue}>
|
||||
<div className="min-h-screen bg-background">
|
||||
<a
|
||||
href="#main-content"
|
||||
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[100] focus:px-4 focus:py-2 focus:bg-primary focus:text-primary-foreground focus:rounded-lg focus:text-sm focus:font-medium"
|
||||
>
|
||||
Hoppa till innehåll
|
||||
</a>
|
||||
<DashboardNav
|
||||
companyName={team?.name || 'Mitt team'}
|
||||
entityType="enskild_firma"
|
||||
uncategorizedTransactionCount={0}
|
||||
pendingOperationsCount={0}
|
||||
isSandbox={false}
|
||||
extensionNavItems={getExtensionNavItems()}
|
||||
/>
|
||||
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-[232px]" role="main">
|
||||
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
<SentryIdentify userId={user.id} email={user.email} />
|
||||
</div>
|
||||
</CompanyProvider>
|
||||
)
|
||||
}
|
||||
|
||||
redirect('/onboarding')
|
||||
}
|
||||
|
||||
@@ -102,42 +65,38 @@ export default async function DashboardLayout({
|
||||
|
||||
if (!companyRow || !memberRow) {
|
||||
// Stale cookie pointing to a deleted/inaccessible company.
|
||||
// If the user is a team member, render the empty-state dashboard
|
||||
// instead of redirecting to onboarding (which would cause a loop).
|
||||
if (isTeamMember) {
|
||||
const companyContextValue = {
|
||||
company: null,
|
||||
role: null,
|
||||
companies: (allMemberships || []).filter(m => m.companies).map((m) => ({
|
||||
company: m.companies as unknown as import('@/types').Company,
|
||||
role: m.role as CompanyRole,
|
||||
})),
|
||||
isTeamMember: true,
|
||||
team,
|
||||
}
|
||||
|
||||
return (
|
||||
<CompanyProvider value={companyContextValue}>
|
||||
<div className="min-h-screen bg-background">
|
||||
<DashboardNav
|
||||
companyName={team?.name || 'Mitt team'}
|
||||
entityType="enskild_firma"
|
||||
uncategorizedTransactionCount={0}
|
||||
pendingOperationsCount={0}
|
||||
isSandbox={false}
|
||||
extensionNavItems={getExtensionNavItems()}
|
||||
/>
|
||||
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-[232px]" role="main">
|
||||
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
<SentryIdentify userId={user.id} email={user.email} />
|
||||
</div>
|
||||
</CompanyProvider>
|
||||
)
|
||||
// Render the empty-state dashboard so user can switch or create a company.
|
||||
const companyContextValue = {
|
||||
company: null,
|
||||
role: null,
|
||||
companies: (allMemberships || []).filter(m => m.companies).map((m) => ({
|
||||
company: m.companies as unknown as import('@/types').Company,
|
||||
role: m.role as CompanyRole,
|
||||
})),
|
||||
isTeamMember,
|
||||
team,
|
||||
}
|
||||
redirect('/onboarding')
|
||||
|
||||
return (
|
||||
<CompanyProvider value={companyContextValue}>
|
||||
<div className="min-h-screen bg-background">
|
||||
<DashboardNav
|
||||
companyName="gnubok"
|
||||
entityType="enskild_firma"
|
||||
uncategorizedTransactionCount={0}
|
||||
pendingOperationsCount={0}
|
||||
isSandbox={false}
|
||||
extensionNavItems={getExtensionNavItems()}
|
||||
/>
|
||||
<main id="main-content" className="safe-area-main-padding md:!pb-0 md:pl-[232px]" role="main">
|
||||
<div className="max-w-5xl mx-auto px-5 py-8 md:px-8 md:py-10">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
<SentryIdentify userId={user.id} email={user.email} />
|
||||
</div>
|
||||
</CompanyProvider>
|
||||
)
|
||||
}
|
||||
|
||||
const [{ data: settings }, { count: uncategorizedCount }, { count: pendingOpsCount }] = await Promise.all([
|
||||
@@ -158,12 +117,11 @@ export default async function DashboardLayout({
|
||||
.eq('status', 'pending'),
|
||||
])
|
||||
|
||||
if (!settings?.onboarding_complete) {
|
||||
redirect('/onboarding')
|
||||
}
|
||||
// If onboarding incomplete, still render the dashboard — the page component
|
||||
// will show the inline onboarding card instead of the normal dashboard content.
|
||||
|
||||
// Use company_name from settings as the display name (companies.name may be stale)
|
||||
const displayName = settings.company_name || companyRow.name
|
||||
const displayName = settings?.company_name || companyRow.name
|
||||
const companyWithName = { ...companyRow, name: displayName }
|
||||
|
||||
const companyContextValue = {
|
||||
@@ -181,9 +139,9 @@ export default async function DashboardLayout({
|
||||
team,
|
||||
}
|
||||
|
||||
const entityType = (settings.entity_type as EntityType) || 'enskild_firma'
|
||||
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
|
||||
|
||||
const isSandbox = settings.is_sandbox === true
|
||||
const isSandbox = settings?.is_sandbox === true
|
||||
|
||||
return (
|
||||
<CompanyProvider value={companyContextValue}>
|
||||
@@ -197,7 +155,7 @@ export default async function DashboardLayout({
|
||||
</a>
|
||||
{isSandbox && <SandboxBanner />}
|
||||
<DashboardNav
|
||||
companyName={settings.company_name || 'Min verksamhet'}
|
||||
companyName={settings?.company_name || 'Min verksamhet'}
|
||||
entityType={entityType}
|
||||
uncategorizedTransactionCount={uncategorizedCount ?? 0}
|
||||
pendingOperationsCount={pendingOpsCount ?? 0}
|
||||
@@ -214,7 +172,7 @@ export default async function DashboardLayout({
|
||||
<RecaptIdentify
|
||||
userId={user.id}
|
||||
email={user.email}
|
||||
displayName={settings.company_name || undefined}
|
||||
displayName={settings?.company_name || undefined}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,6 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { redirect } from 'next/navigation'
|
||||
import { cookies } from 'next/headers'
|
||||
import DashboardContent from '@/components/dashboard/DashboardContent'
|
||||
import ConsultantEmptyState from '@/components/dashboard/ConsultantEmptyState'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import type { Deadline, ReceiptQueueSummary, OnboardingProgress } from '@/types'
|
||||
|
||||
@@ -34,24 +33,6 @@ export default async function DashboardPage() {
|
||||
}
|
||||
|
||||
if (!companyId) {
|
||||
// Consultants (team members) see an empty state; solo users go to onboarding
|
||||
const { data: teamMembership } = await supabase
|
||||
.from('team_members')
|
||||
.select('team_id')
|
||||
.eq('user_id', user.id)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
|
||||
if (teamMembership) {
|
||||
const { data: profile } = await supabase
|
||||
.from('profiles')
|
||||
.select('full_name')
|
||||
.eq('id', user.id)
|
||||
.single()
|
||||
const firstName = profile?.full_name?.split(' ')[0] || null
|
||||
return <ConsultantEmptyState firstName={firstName} />
|
||||
}
|
||||
|
||||
redirect('/onboarding')
|
||||
}
|
||||
|
||||
@@ -122,6 +103,11 @@ export default async function DashboardPage() {
|
||||
|
||||
const firstName = profile?.full_name?.split(' ')[0] || null
|
||||
|
||||
// If onboarding is not complete, redirect to onboarding
|
||||
if (!settings?.onboarding_complete) {
|
||||
redirect('/onboarding')
|
||||
}
|
||||
|
||||
const onboardingProgress: OnboardingProgress = {
|
||||
hasCustomers: (customerCount || 0) > 0,
|
||||
hasInvoices: (invoiceCount || 0) > 0,
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { Plus, Search, Building2, Globe } from 'lucide-react'
|
||||
import SupplierForm from '@/components/suppliers/SupplierForm'
|
||||
import Link from 'next/link'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import type { Supplier, SupplierType, CreateSupplierInput } from '@/types'
|
||||
|
||||
const supplierTypeLabels: Record<SupplierType, string> = {
|
||||
@@ -26,6 +27,7 @@ const supplierTypeIcons: Record<SupplierType, React.ElementType> = {
|
||||
}
|
||||
|
||||
export default function SuppliersPage() {
|
||||
const { company } = useCompany()
|
||||
const [suppliers, setSuppliers] = useState<Supplier[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchTerm, setSearchTerm] = useState('')
|
||||
@@ -35,10 +37,12 @@ export default function SuppliersPage() {
|
||||
const supabase = createClient()
|
||||
|
||||
async function fetchSuppliers() {
|
||||
if (!company) return
|
||||
setIsLoading(true)
|
||||
const { data, error } = await supabase
|
||||
.from('suppliers')
|
||||
.select('*')
|
||||
.eq('company_id', company.id)
|
||||
.order('name', { ascending: true })
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -104,10 +104,12 @@ export default function TransactionsPage() {
|
||||
const PAGE_SIZE = 200
|
||||
|
||||
async function fetchTransactions() {
|
||||
if (!company) return
|
||||
setIsLoading(true)
|
||||
const { data: txData, error: txError } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('company_id', company.id)
|
||||
.order('date', { ascending: false })
|
||||
.limit(PAGE_SIZE)
|
||||
|
||||
@@ -165,11 +167,13 @@ export default function TransactionsPage() {
|
||||
}
|
||||
|
||||
async function loadMoreTransactions() {
|
||||
if (!company) return
|
||||
setIsLoadingMore(true)
|
||||
const offset = transactions.length
|
||||
const { data: txData, error: txError } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('company_id', company.id)
|
||||
.order('date', { ascending: false })
|
||||
.range(offset, offset + PAGE_SIZE - 1)
|
||||
|
||||
|
||||
@@ -10,9 +10,11 @@ export default async function OnboardingLayout({
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
<div className="min-h-screen bg-background flex items-center justify-center">
|
||||
<div className="w-full max-w-lg px-5">
|
||||
{children}
|
||||
</div>
|
||||
{user && <SentryIdentify userId={user.id} email={user.email} />}
|
||||
</>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -170,9 +170,7 @@ export async function GET(request: Request) {
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
const redirectTarget = userSettings?.onboarding_complete
|
||||
? `/settings/banking?bank_connected=true&connection_id=${connectionId}`
|
||||
: `/onboarding?bank_connected=true&connection_id=${connectionId}`
|
||||
const redirectTarget = `/settings/banking?bank_connected=true&connection_id=${connectionId}`
|
||||
|
||||
return NextResponse.redirect(`${baseUrl}${redirectTarget}`)
|
||||
} catch (error) {
|
||||
|
||||
@@ -77,7 +77,9 @@ function NewCompanyContent() {
|
||||
|
||||
const totalSteps = 4
|
||||
|
||||
// Just verify auth on mount
|
||||
const [teamId, setTeamId] = useState<string | null>(null)
|
||||
|
||||
// Verify auth and fetch team_id on mount
|
||||
useEffect(() => {
|
||||
async function checkAuth() {
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
@@ -85,6 +87,23 @@ function NewCompanyContent() {
|
||||
router.push('/login')
|
||||
return
|
||||
}
|
||||
|
||||
// Fetch user's team_id
|
||||
const { data: teamMembership } = await supabase
|
||||
.from('team_members')
|
||||
.select('team_id')
|
||||
.eq('user_id', user.id)
|
||||
.limit(1)
|
||||
.maybeSingle()
|
||||
|
||||
if (teamMembership?.team_id) {
|
||||
setTeamId(teamMembership.team_id)
|
||||
} else {
|
||||
// Ensure user has a team (fallback)
|
||||
const { data: newTeamId } = await supabase.rpc('ensure_user_team')
|
||||
setTeamId(newTeamId)
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
}
|
||||
checkAuth()
|
||||
@@ -162,6 +181,7 @@ function NewCompanyContent() {
|
||||
const { data: newCompanyId, error: companyError } = await supabase.rpc('create_company_with_owner', {
|
||||
p_name: 'Nytt företag',
|
||||
p_entity_type: stepData.entity_type,
|
||||
p_team_id: teamId,
|
||||
})
|
||||
|
||||
if (companyError || !newCompanyId) {
|
||||
|
||||
Reference in New Issue
Block a user