fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
const noParams = { params: Promise.resolve({}) }
|
||||
|
||||
function authed() {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
}
|
||||
|
||||
function unauthed() {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
}
|
||||
|
||||
function isoDaysFromNow(days: number): string {
|
||||
const d = new Date()
|
||||
d.setHours(0, 0, 0, 0)
|
||||
d.setDate(d.getDate() + days)
|
||||
// Local date parts, not toISOString(): UTC conversion would shift the day
|
||||
// in timezones ahead of UTC and skew the urgency math under test.
|
||||
const y = d.getFullYear()
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getDate()).padStart(2, '0')
|
||||
return `${y}-${m}-${day}`
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
describe('GET /api/clients', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
unauthed()
|
||||
const res = await GET(createMockRequest('/api/clients'), noParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a user without a byrå team', async () => {
|
||||
authed()
|
||||
// Query 1: byrå team membership lookup: no rows.
|
||||
enqueue({ data: [] })
|
||||
|
||||
const res = await GET(createMockRequest('/api/clients'), noParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: { code: string }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('FORBIDDEN')
|
||||
})
|
||||
|
||||
it('aggregates one urgency-sorted row per client company', async () => {
|
||||
authed()
|
||||
// 1. byrå membership
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
team_id: 'team-1',
|
||||
role: 'admin',
|
||||
teams: { id: 'team-1', name: 'Siffra', kind: 'byra' },
|
||||
},
|
||||
],
|
||||
})
|
||||
// 2. client companies
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'c1', name: 'Alpha AB', org_number: '5560125790' },
|
||||
{ id: 'c2', name: 'Beta AB', org_number: null },
|
||||
],
|
||||
})
|
||||
// 3. company_settings (display names)
|
||||
enqueue({
|
||||
data: [{ company_id: 'c1', company_name: 'Alpha Redovisning AB', org_number: null }],
|
||||
})
|
||||
// 4. unbooked transactions (canonical predicate)
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 't1', company_id: 'c1' },
|
||||
{ id: 't2', company_id: 'c1' },
|
||||
{ id: 't3', company_id: 'c1' },
|
||||
{ id: 't4', company_id: 'c2' },
|
||||
],
|
||||
})
|
||||
// 5. inbox items with a document that became nothing
|
||||
enqueue({ data: [{ id: 'i1', company_id: 'c1', document_id: 'd1' }] })
|
||||
// 6. document backstop: d1 still unlinked
|
||||
enqueue({ data: [{ id: 'd1', company_id: 'c1' }] })
|
||||
// 7. open deadlines: c2 has an overdue one
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
id: 'dl1',
|
||||
company_id: 'c2',
|
||||
title: 'Momsdeklaration',
|
||||
due_date: isoDaysFromNow(-5),
|
||||
tax_deadline_type: 'vat_declaration',
|
||||
status: 'overdue',
|
||||
},
|
||||
],
|
||||
})
|
||||
// 8. latest posted verifikat per company (embedded)
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'c1', journal_entries: [{ entry_date: '2026-07-15' }] },
|
||||
{ id: 'c2', journal_entries: [] },
|
||||
],
|
||||
})
|
||||
|
||||
const res = await GET(createMockRequest('/api/clients'), noParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: {
|
||||
team: { id: string; name: string }
|
||||
role: string
|
||||
clients: Array<{
|
||||
companyId: string
|
||||
name: string
|
||||
orgNumber: string | null
|
||||
unbookedCount: number
|
||||
inboxCount: number
|
||||
nextDeadline: { urgency: string; dueDate: string } | null
|
||||
lastBookedDate: string | null
|
||||
}>
|
||||
}
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.team).toEqual({ id: 'team-1', name: 'Siffra' })
|
||||
expect(body.data.role).toBe('admin')
|
||||
|
||||
// Urgency sort: c2 (overdue deadline) before c1 (bigger unbooked pile).
|
||||
expect(body.data.clients.map((c) => c.companyId)).toEqual(['c2', 'c1'])
|
||||
|
||||
const [c2, c1] = body.data.clients
|
||||
expect(c2).toMatchObject({
|
||||
name: 'Beta AB',
|
||||
unbookedCount: 1,
|
||||
inboxCount: 0,
|
||||
lastBookedDate: null,
|
||||
})
|
||||
expect(c2.nextDeadline).toMatchObject({
|
||||
urgency: 'overdue',
|
||||
dueDate: isoDaysFromNow(-5),
|
||||
})
|
||||
|
||||
expect(c1).toMatchObject({
|
||||
// company_settings display name wins over the frozen companies.name
|
||||
name: 'Alpha Redovisning AB',
|
||||
orgNumber: '5560125790',
|
||||
unbookedCount: 3,
|
||||
inboxCount: 1,
|
||||
nextDeadline: null,
|
||||
lastBookedDate: '2026-07-15',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns an empty client list for a byrå without companies', async () => {
|
||||
authed()
|
||||
enqueue({
|
||||
data: [
|
||||
{
|
||||
team_id: 'team-1',
|
||||
role: 'member',
|
||||
teams: { id: 'team-1', name: 'Siffra', kind: 'byra' },
|
||||
},
|
||||
],
|
||||
})
|
||||
enqueue({ data: [] }) // no client companies
|
||||
|
||||
const res = await GET(createMockRequest('/api/clients'), noParams)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { role: string; clients: unknown[] }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.role).toBe('member')
|
||||
expect(body.data.clients).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createQueuedMockSupabase,
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
const resolveLandingDestinationMock = vi.fn()
|
||||
vi.mock('@/lib/company/landing-server', () => ({
|
||||
resolveLandingDestination: (...args: unknown[]) => resolveLandingDestinationMock(...args),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
// The landing rule itself (role gate, brand/host matching, WL-01 canonical
|
||||
// fallback, error degradation) is covered where it lives:
|
||||
// lib/company/__tests__/landing-server.test.ts. This suite covers only the
|
||||
// HTTP wrapper contract.
|
||||
describe('GET /api/clients/landing', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await GET(createMockRequest('/api/clients/landing'))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns the helper destination, passing the forwarded host and user', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
resolveLandingDestinationMock.mockResolvedValue('/clients')
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/clients/landing', {
|
||||
headers: { 'x-forwarded-host': 'app.amnas.se' },
|
||||
})
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { destination: string } }>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.destination).toBe('/clients')
|
||||
// No active-company requirement: byrå staff without a company of their
|
||||
// own (the cockpit's primary persona) must still get a destination.
|
||||
expect(resolveLandingDestinationMock).toHaveBeenCalledWith(supabase, 'user-1', 'app.amnas.se')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { resolveLandingDestination } from '@/lib/company/landing-server'
|
||||
|
||||
/**
|
||||
* GET /api/clients/landing
|
||||
*
|
||||
* Post-login landing decision (WL-14): thin HTTP wrapper around
|
||||
* resolveLandingDestination (lib/company/landing-server.ts), for the client
|
||||
* auth surfaces (login and MFA-verify pages) that cannot call it in-process.
|
||||
* The helper carries the whole rule, including the owner/admin role gate
|
||||
* (2026-08-27). Called when no explicit destination was requested; any
|
||||
* failure degrades to '/' at the caller.
|
||||
*
|
||||
* Uses requireAuth() directly (the sanctioned withRouteContext opt-out, MFA
|
||||
* still enforced) because the decision needs no active company. Byrå staff
|
||||
* without a company of their own are the cockpit's primary persona and must
|
||||
* still land on /clients; withRouteContext would 4xx them with
|
||||
* COMPANY_CONTEXT_MISSING.
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const auth = await requireAuth()
|
||||
if (auth.error) return auth.error
|
||||
const { user, supabase } = auth
|
||||
|
||||
const host =
|
||||
request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? ''
|
||||
const destination = await resolveLandingDestination(supabase, user.id, host)
|
||||
return NextResponse.json({ data: { destination } })
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { fetchClientOverview } from '@/lib/clients/fetch-client-overview'
|
||||
|
||||
/**
|
||||
* GET /api/clients
|
||||
*
|
||||
* Byrå cockpit aggregate (WL-14): one row per client company on the caller's
|
||||
* byrå team (teams.kind = 'byra') with the four at-a-glance signals: unbooked
|
||||
* transaction count, unconsumed inbox document count, next deadline
|
||||
* (status-engine semantics, 14-day ACTION_NEEDED window) and last booked
|
||||
* (latest posted verifikat date). Rows arrive urgency-sorted: overdue
|
||||
* deadlines first, then largest unbooked pile.
|
||||
*
|
||||
* Read-only across memberships (WL-09 read-first): RLS already allows these
|
||||
* reads via user_company_ids(); the active company is untouched.
|
||||
*
|
||||
* Non-byrå users get 403 FORBIDDEN: the cockpit is byrå-exclusive in v1
|
||||
* (multi-company self-users keep the company switcher).
|
||||
*/
|
||||
export const GET = withRouteContext('clients.list', async (_request, ctx) => {
|
||||
const overview = await fetchClientOverview(ctx.supabase, ctx.user.id)
|
||||
|
||||
if (!overview) {
|
||||
return errorResponseFromCode('FORBIDDEN', ctx.log, {
|
||||
requestId: ctx.requestId,
|
||||
reason: 'not a byrå team member',
|
||||
messageSv: 'Klientlistan är endast tillgänglig för byråteam.',
|
||||
messageEn: 'The client list is only available to byrå team members.',
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: overview })
|
||||
})
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
const service = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
const byraMembershipMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/clients/fetch-client-overview', () => ({
|
||||
getByraMembership: (...args: unknown[]) => byraMembershipMock(...args),
|
||||
}))
|
||||
|
||||
const brandForTeamMock = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/lib/branding/resolve', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/branding/resolve')>()
|
||||
return {
|
||||
...actual,
|
||||
resolveBrandForTeam: (...args: unknown[]) => brandForTeamMock(...args),
|
||||
clearBrandCache: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', () => ({
|
||||
createServiceClientNoCookies: vi.fn(() => service.supabase),
|
||||
}))
|
||||
|
||||
import { GET, PATCH, POST, DELETE } from '../route'
|
||||
|
||||
const BRAND = {
|
||||
id: 'brand-1',
|
||||
teamId: 'team-1',
|
||||
domain: 'app.testbrand.example',
|
||||
appName: 'Testbrand',
|
||||
signupMode: 'invite_only',
|
||||
}
|
||||
|
||||
function makeRequest(method: string, body?: unknown): Request {
|
||||
return new Request('https://app.test/api/clients/signup-access', {
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
function authed() {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: { id: 'user-1', email: '[email protected]' },
|
||||
supabase,
|
||||
error: null,
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
service.reset()
|
||||
authed()
|
||||
byraMembershipMock.mockResolvedValue({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Byrån',
|
||||
role: 'owner',
|
||||
})
|
||||
brandForTeamMock.mockResolvedValue(BRAND)
|
||||
})
|
||||
|
||||
describe('/api/clients/signup-access', () => {
|
||||
it('401s when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET()
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('403s for non-byrå users', async () => {
|
||||
byraMembershipMock.mockResolvedValue(null)
|
||||
const res = await GET()
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('404s when the team has no brand', async () => {
|
||||
brandForTeamMock.mockResolvedValue(null)
|
||||
const res = await GET()
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns mode, role and entries', async () => {
|
||||
enqueue({
|
||||
data: [{ id: 'e1', email: '[email protected]', note: null, created_at: '2026-08-27' }],
|
||||
})
|
||||
|
||||
const res = await GET()
|
||||
const { body } = await parseJsonResponse<{
|
||||
data: {
|
||||
brand: { domain: string; signupMode: string }
|
||||
role: string
|
||||
entries: unknown[]
|
||||
}
|
||||
}>(res)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data.brand.signupMode).toBe('invite_only')
|
||||
expect(body.data.role).toBe('owner')
|
||||
expect(body.data.entries).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('PATCH 403s for plain members', async () => {
|
||||
byraMembershipMock.mockResolvedValue({
|
||||
teamId: 'team-1',
|
||||
teamName: 'Byrån',
|
||||
role: 'member',
|
||||
})
|
||||
const res = await PATCH(makeRequest('PATCH', { signup_mode: 'invite_only' }))
|
||||
expect(res.status).toBe(403)
|
||||
expect(service.supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('PATCH 400s on an unknown mode', async () => {
|
||||
const res = await PATCH(makeRequest('PATCH', { signup_mode: 'wide_open' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('PATCH flips the mode through the service client', async () => {
|
||||
service.enqueue({ data: null, error: null })
|
||||
const res = await PATCH(makeRequest('PATCH', { signup_mode: 'invite_only' }))
|
||||
expect(res.status).toBe(200)
|
||||
expect(service.findCall('brands', 'update')).toEqual([
|
||||
{ signup_mode: 'invite_only' },
|
||||
])
|
||||
expect(service.findCall('brands', 'eq')).toEqual(['id', 'brand-1'])
|
||||
})
|
||||
|
||||
it('POST adds a lowercased entry', async () => {
|
||||
enqueue({
|
||||
data: { id: 'e1', email: '[email protected]', note: 'VD', created_at: '2026-08-27' },
|
||||
})
|
||||
|
||||
const res = await POST(
|
||||
makeRequest('POST', { email: ' [email protected] ', note: 'VD' }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
const insert = supabase.from as unknown as ReturnType<typeof vi.fn>
|
||||
expect(insert).toHaveBeenCalledWith('brand_signup_allowlist')
|
||||
})
|
||||
|
||||
it('POST 409s on a duplicate email', async () => {
|
||||
enqueue({ data: null, error: { code: '23505', message: 'duplicate' } })
|
||||
const res = await POST(makeRequest('POST', { email: '[email protected]' }))
|
||||
expect(res.status).toBe(409)
|
||||
})
|
||||
|
||||
it('POST 400s on an invalid email', async () => {
|
||||
const res = await POST(makeRequest('POST', { email: 'not-an-email' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('DELETE removes scoped to the brand', async () => {
|
||||
enqueue({ data: null, error: null })
|
||||
const res = await DELETE(
|
||||
makeRequest('DELETE', { id: '11111111-1111-4111-8111-111111111111' }),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,220 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { getByraMembership } from '@/lib/clients/fetch-client-overview'
|
||||
import { clearBrandCache, resolveBrandForTeam, type Brand } from '@/lib/branding/resolve'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import {
|
||||
BrandAllowlistAddSchema,
|
||||
BrandAllowlistRemoveSchema,
|
||||
BrandSignupModeSchema,
|
||||
} from '@/lib/api/schemas'
|
||||
|
||||
/**
|
||||
* /api/clients/signup-access: the byrå cockpit's management surface for
|
||||
* invite-only signup on the team's brand domain (2026-08-27).
|
||||
*
|
||||
* GET signup mode + allowlist entries (any byrå team member)
|
||||
* PATCH { signup_mode } flip open/invite_only (owner/admin)
|
||||
* POST { email, note? } add an allowlist entry (owner/admin)
|
||||
* DELETE { id } remove an allowlist entry (owner/admin)
|
||||
*
|
||||
* Uses requireAuth() directly (the sanctioned withRouteContext opt-out, MFA
|
||||
* still enforced): byrå staff without a company of their own are the
|
||||
* cockpit's primary persona, and this surface needs no active company.
|
||||
*
|
||||
* Allowlist reads/writes go through the caller's client so RLS enforces the
|
||||
* same team/role rules a second time. The signup_mode flip uses the service
|
||||
* client because brands rows are ops-managed (no user write policies); the
|
||||
* owner/admin check here is the authorization for that single column.
|
||||
*/
|
||||
|
||||
type Access =
|
||||
| {
|
||||
ok: true
|
||||
supabase: SupabaseClient
|
||||
userId: string
|
||||
role: 'owner' | 'admin' | 'member'
|
||||
brand: Brand
|
||||
}
|
||||
| { ok: false; response: NextResponse }
|
||||
|
||||
async function resolveAccess(opts: { write: boolean }): Promise<Access> {
|
||||
const auth = await requireAuth()
|
||||
if (auth.error) return { ok: false, response: auth.error }
|
||||
const { user, supabase } = auth
|
||||
|
||||
const membership = await getByraMembership(supabase, user.id)
|
||||
if (!membership) {
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Endast byråteam har åtkomst till registreringsinställningarna.',
|
||||
message_en: 'Signup access settings are only available to byrå teams.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
if (opts.write && membership.role !== 'owner' && membership.role !== 'admin') {
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Endast byråns ägare och administratörer kan ändra registreringsåtkomst.',
|
||||
message_en: 'Only byrå owners and admins can change signup access.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
const brand = await resolveBrandForTeam(membership.teamId)
|
||||
if (!brand) {
|
||||
return {
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'NOT_FOUND',
|
||||
message: 'Byrån har ingen egen domän ännu.',
|
||||
message_en: 'The byrå has no white-label domain yet.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, supabase, userId: user.id, role: membership.role, brand }
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
const access = await resolveAccess({ write: false })
|
||||
if (!access.ok) return access.response
|
||||
|
||||
const { data: entries, error } = await access.supabase
|
||||
.from('brand_signup_allowlist')
|
||||
.select('id, email, note, created_at')
|
||||
.eq('brand_id', access.brand.id)
|
||||
.order('created_at', { ascending: false })
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'INTERNAL', message: 'Kunde inte hämta listan.', message_en: 'Could not load the list.' } },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
brand: {
|
||||
domain: access.brand.domain,
|
||||
appName: access.brand.appName,
|
||||
signupMode: access.brand.signupMode,
|
||||
},
|
||||
role: access.role,
|
||||
entries: entries ?? [],
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request) {
|
||||
const access = await resolveAccess({ write: true })
|
||||
if (!access.ok) return access.response
|
||||
|
||||
const validation = await validateBody(request, BrandSignupModeSchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
const service = createServiceClientNoCookies()
|
||||
const { error } = await service
|
||||
.from('brands')
|
||||
.update({ signup_mode: validation.data.signup_mode })
|
||||
.eq('id', access.brand.id)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'INTERNAL', message: 'Kunde inte spara.', message_en: 'Could not save.' } },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
|
||||
// The host-resolution cache holds the old mode for up to ~60s; drop it so
|
||||
// the gate on this server instance flips immediately. Other instances
|
||||
// converge within the TTL, same as every other brand edit.
|
||||
clearBrandCache()
|
||||
|
||||
return NextResponse.json({ data: { signupMode: validation.data.signup_mode } })
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const access = await resolveAccess({ write: true })
|
||||
if (!access.ok) return access.response
|
||||
|
||||
const validation = await validateBody(request, BrandAllowlistAddSchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
const { data: entry, error } = await access.supabase
|
||||
.from('brand_signup_allowlist')
|
||||
.insert({
|
||||
brand_id: access.brand.id,
|
||||
email: validation.data.email,
|
||||
note: validation.data.note ?? null,
|
||||
created_by: access.userId,
|
||||
})
|
||||
.select('id, email, note, created_at')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
if (error.code === '23505') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONFLICT',
|
||||
message: 'E-postadressen finns redan i listan.',
|
||||
message_en: 'That email is already on the list.',
|
||||
},
|
||||
},
|
||||
{ status: 409 },
|
||||
)
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'INTERNAL', message: 'Kunde inte lägga till.', message_en: 'Could not add the email.' } },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: entry })
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const access = await resolveAccess({ write: true })
|
||||
if (!access.ok) return access.response
|
||||
|
||||
const validation = await validateBody(request, BrandAllowlistRemoveSchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
const { error } = await access.supabase
|
||||
.from('brand_signup_allowlist')
|
||||
.delete()
|
||||
.eq('id', validation.data.id)
|
||||
.eq('brand_id', access.brand.id)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json(
|
||||
{ error: { code: 'INTERNAL', message: 'Kunde inte ta bort.', message_en: 'Could not remove the email.' } },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { removed: validation.data.id } })
|
||||
}
|
||||
Reference in New Issue
Block a user