feat(sandbox,branding): prod-parity demo with AI gating + accounted rebrand (#585)
* feat(sandbox,branding): prod-parity demo with AI gating + accounted rebrand Sandbox now ships with seeded suppliers, supplier invoices, an asset, a verified agent_profile, and pending operations so the demo company exercises every prod surface. Server-side `guardSandbox()` short- circuits any AI or paid-external API call (Bedrock chat/composer, Resend invoice send, Riksbanken FX, VIES, etc.) and the AgentSheet swaps in a SandboxAgentPreview that explains what's gated and offers a register CTA. DashboardContent no longer mounts the NewUserChecklist when the agent is already built, fixing the path that let sandbox users still trigger /onboarding/agent. Visible branding flips from Gnubok to Accounted: new BrandWordmark component (Hedvig Letters Serif 700), new app/icon.png + PWA icons generated from the accounted icon, default appName updated. URLs, header names, API key prefixes, hostnames, and event/cookie/ localStorage keys keep `gnubok` — the rebrand is visual only. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(sandbox): hardcode supplier-invoice arrival numbers in seed get_next_arrival_number is MAX(arrival_number) + 1 against the same table we're about to insert into. Calling it twice before either row lands made both calls return 1, which then violated the (company_id, arrival_number) unique index — POST /api/sandbox/seed 500'd on first sandbox start. The seeded company is brand new in this branch so 1 and 2 are guaranteed unused; hardcoding side-steps the race entirely. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(sandbox): set paid_amount=0 on unpaid supplier invoice PostgREST normalizes the column set across rows in a bulk insert, so the second supplier invoice (Espresso House, status=registered) was being sent with paid_amount=null because the first row (Telia, paid) set it. supplier_invoices.paid_amount is NOT NULL DEFAULT 0; the default only kicks in when the column is *absent* from the payload, not when it's explicitly null. Set it inline to side-step the normalization. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(sandbox): set actor_type=agent_chat on seeded pending_operations pending_operations only allows user-scoped INSERTs via the `pending_operations_chat_insert` policy, which requires actor_type='agent_chat' alongside auth.uid()=user_id + company membership. The seed was inserting with the default actor_type='user', tripping the RLS check. Also lift risk_level from preview_data (where it was unused) onto the row itself, matching the column added in 20260430120000_pending_operations_actor_and_risk. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(pr-review): address PR #585 review feedback Fixes called out by the core-only CI check, Greptile, and the compliance + Swedish-accounting bots: - AGI Programnamn pinned back to 'gnubok' (CI blocker). The XML Skatteverket receives must keep the stable software identifier regardless of the visual rebrand — same rule as the v1 health endpoint's `service: 'gnubok'` literal. - handleCreateAccount in SandboxAgentPreview + ChatEmptyState now wraps signOut() in try/catch so a transient Supabase failure doesn't strand the user on a dead button (greptile P2 × 2). - /api/currency/rate hard-fails on missing companyId instead of conditionally skipping the sandbox guard (greptile P2 / compliance V8.2.1). - topUpSandboxAdditions now delegates to ensureSandboxAgentProfile; the assistant persona lives in exactly one place across the seed, layout backfills, and top-up path (greptile P2 outside-diff / compliance SOC2 CC6.1). - ensureSandboxAgentProfile drops the userId param and sets verified_by_user_id to NULL — synthetic seed data should not attribute verification to a real user (compliance V8.2.1 / GDPR Art. 25(2)). Errors now logged via the structured logger instead of being silently swallowed (V16). - Sandbox seed swaps real-world company names (Telia, Espresso House) for clearly-synthetic Demo-prefixed brands using the 5559... documentation org-number range (compliance A.8.33). Asset cost bumped 24 000 → 35 000 SEK so the demo clears the förbrukningsinventarier threshold and illustrates capitalization unambiguously (swedish-asset-accounting). - Representation pending-operation preview corrected: VAT label fixed from 6% → 12%, and input VAT split between the avdragsgill (2641) and ej-avdragsgill (5811) portions to match swedish-vat / ML 8 kap rules (swedish-vat). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(pr-review): seed preview consistency + AGI Programnamn constant Two last review-bot items before merge: - Sandbox seed: the representation pending-operation preview was splitting the 240 SEK café meal 60/180 between 5810 and 5811, which is wrong for a single attendee under the 300 SEK / person avdragsgill cap (ML 8 kap) — the entire amount is fully avdragsgill in that case. Collapse the preview to a single 5810 + 2641 + 2440 entry so it matches the supplier_invoice_items row 1:1 and stops teaching demo users an incorrect bookkeeping pattern. - Hoist the AGI Programnamn 'gnubok' literal into a named constant with a comment pointing to potential future Skatteverket vendor registration (per the swedish-compliance bot's nit). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(sandbox): avoid BFL duplicate-verification on pending op + fix VAT cap comment Swedish-compliance bot caught two final nits: - The pending operation for the Demokafé representation was using the same supplier_invoice_number as the already-seeded supplier_invoices row (88245). If the sandbox user approved the staged operation, the insert would have created (or attempted) a duplicate verification — BFL 5 kap. requires each affärshändelse be recorded exactly once. Swap the staged operation's invoice number to a distinct value (INKOMMANDE-2026-001) so approval cleanly creates a new row. - The preview comment described the 300 SEK threshold as an "avdragsgill cap". The actual rule (ML 8 kap. 9 §) caps the deductible VAT at 25 % × 300 SEK × antal_personer = 75 SEK per person — the 300 SEK is the tax base, not the total. Math here is correct either way, but the comment now states the correct formula so future seed edits don't propagate the wrong understanding. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
f53725b20a
commit
20989379bb
@@ -4,6 +4,7 @@ import { z } from 'zod'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { composeAgentProfile } from '@/lib/agent/composer'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
|
||||
const BodySchema = z.object({
|
||||
// Optional override; if absent we use the user's active_company_id.
|
||||
@@ -63,6 +64,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Not a member of this company' }, { status: 403 })
|
||||
}
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
try {
|
||||
const composed = await composeAgentProfile(supabase, companyId, { dryRun: body.dry_run })
|
||||
return NextResponse.json({ data: composed })
|
||||
|
||||
@@ -6,6 +6,7 @@ import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { getIntent } from '@/lib/agent/intents/registry'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { runChatTurn, friendlyModelError } from '@/lib/agent/chat/run-turn'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
|
||||
// Make sure extensions are loaded — the chat loop dispatches against the
|
||||
// agent tool registry which is populated by the mcp-server extension at load.
|
||||
@@ -105,6 +106,11 @@ export async function POST(request: Request) {
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
// No Anthropic Bedrock calls in the sandbox — the demo runs entirely on
|
||||
// seed data and the assistant is gated to a "look, don't touch" preview.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
// onboarding.intake completion signal — once the user has actually
|
||||
// engaged (typed a real reply, not the auto-fired greeting prompt that
|
||||
// mounts the chat), stamp intake_completed_at on the profile so re-entry
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { gatherComposerInputs, inputsToSourceSignals } from '@/lib/agent/composer/inputs'
|
||||
import { selectAtoms } from '@/lib/agent/composer/atom-selection'
|
||||
@@ -100,6 +101,11 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Not a member of this company' }, { status: 403 })
|
||||
}
|
||||
|
||||
// No live composer run for sandbox companies — they ship with a pre-built
|
||||
// verified agent_profile so the chrome is visible without burning Bedrock.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
const encoder = new TextEncoder()
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import type { Currency } from '@/types'
|
||||
|
||||
const VALID_CURRENCIES: Currency[] = ['EUR', 'USD', 'GBP', 'NOK', 'DKK']
|
||||
@@ -12,6 +14,16 @@ export async function GET(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await getActiveCompanyId(supabase, user.id)
|
||||
// Refuse the request when no active company resolves rather than letting
|
||||
// a session without one slip past the sandbox guard. Riksbanken's open
|
||||
// API is IP rate-limited; we don't want demo traffic eating that budget.
|
||||
if (!companyId) {
|
||||
return NextResponse.json({ error: 'No active company' }, { status: 400 })
|
||||
}
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const currency = searchParams.get('currency') as Currency | null
|
||||
const dateStr = searchParams.get('date')
|
||||
|
||||
@@ -65,6 +65,15 @@ vi.mock('@/lib/bookkeeping/invoice-entries', () => ({
|
||||
mockCreateInvoiceJournalEntry(...args),
|
||||
}))
|
||||
|
||||
// The sandbox guard issues a company_settings query at the top of the route;
|
||||
// short-circuit it in tests since the queued mock-supabase is shaped for the
|
||||
// route's existing fetch chain, not an extra pre-flight read.
|
||||
vi.mock('@/lib/sandbox/guard', () => ({
|
||||
guardSandbox: vi.fn().mockResolvedValue(null),
|
||||
isSandboxCompany: vi.fn().mockResolvedValue(false),
|
||||
sandboxBlockedResponse: vi.fn(),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
describe('POST /api/invoices/[id]/send', () => {
|
||||
|
||||
@@ -15,6 +15,7 @@ import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -26,6 +27,11 @@ export const POST = withRouteContext(
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
const opLog = log.child({ invoiceId: id })
|
||||
|
||||
// The sandbox must never deliver a real email to a real customer — block
|
||||
// the entire send pipeline (PDF render + Resend send + status flip).
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const emailService = getEmailService()
|
||||
if (!emailService.isConfigured()) {
|
||||
return errorResponseFromCode('INVOICE_SEND_EMAIL_NOT_CONFIGURED', opLog, { requestId })
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import crypto from 'crypto'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
|
||||
import { truncateIp } from '@/lib/api/v1/with-api-v1'
|
||||
import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
|
||||
|
||||
// Anonymous sign-in is enabled in all environments so visitors can try the
|
||||
// product; a per-/24 cap on the seed endpoint keeps a single network from
|
||||
@@ -80,7 +82,11 @@ export async function POST(request: Request) {
|
||||
companyId = newCompanyId as string
|
||||
}
|
||||
|
||||
// Idempotency: if already seeded, return early
|
||||
// Idempotency: if the core seed already ran (company_settings exists), skip
|
||||
// the bulk insert path. We still TOP UP the newer surfaces (agent_profile,
|
||||
// suppliers, asset, pending operations) afterwards so an old sandbox session
|
||||
// — created before those were added to the seed — picks them up on the next
|
||||
// call instead of being stuck without a verified assistant.
|
||||
const { data: existing } = await supabase
|
||||
.from('company_settings')
|
||||
.select('id')
|
||||
@@ -88,7 +94,13 @@ export async function POST(request: Request) {
|
||||
.maybeSingle()
|
||||
|
||||
if (existing) {
|
||||
return NextResponse.json({ seeded: false })
|
||||
try {
|
||||
await topUpSandboxAdditions(supabase, companyId)
|
||||
return NextResponse.json({ seeded: false, topped_up: true })
|
||||
} catch (err) {
|
||||
log.error('failed to top up sandbox additions', { error: err, userId: user.id, companyId })
|
||||
return NextResponse.json({ seeded: false, topped_up: false })
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -581,6 +593,246 @@ export async function POST(request: Request) {
|
||||
|
||||
if (dlError) throw dlError
|
||||
|
||||
// 13. Seed suppliers + one registered supplier invoice + one paid one.
|
||||
// Supplier invoices are arguably the second-most-used surface after
|
||||
// bank transactions; without them the /suppliers and /supplier-invoices
|
||||
// pages render the empty state and the demo loses a big chunk of the
|
||||
// accounts-payable story.
|
||||
// Supplier names use the "Demo" prefix and the documentation-reserved
|
||||
// 5559... org-number range so the seeded rows cannot be confused with
|
||||
// production data should they ever leak into a real environment.
|
||||
const { data: suppliers, error: supError } = await supabase
|
||||
.from('suppliers')
|
||||
.insert([
|
||||
{
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: 'Demo Telekom AB',
|
||||
supplier_type: 'swedish_business',
|
||||
org_number: '5559000001',
|
||||
vat_number: 'SE555900000101',
|
||||
email: 'demo+telekom@example.com',
|
||||
bankgiro: '5559-0001',
|
||||
address_line1: 'Demovägen 10',
|
||||
postal_code: '111 22',
|
||||
city: 'Stockholm',
|
||||
country: 'SE',
|
||||
default_payment_terms: 30,
|
||||
},
|
||||
{
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: 'Demokafé AB',
|
||||
supplier_type: 'swedish_business',
|
||||
org_number: '5559000002',
|
||||
vat_number: 'SE555900000201',
|
||||
bankgiro: '5559-0002',
|
||||
address_line1: 'Demovägen 11',
|
||||
postal_code: '111 22',
|
||||
city: 'Stockholm',
|
||||
country: 'SE',
|
||||
default_payment_terms: 15,
|
||||
},
|
||||
])
|
||||
.select('id, name')
|
||||
|
||||
if (supError) throw supError
|
||||
const supplierMap = Object.fromEntries(suppliers.map(s => [s.name, s.id]))
|
||||
|
||||
// Supplier invoice #1 — Telia, paid 15 days ago (mobile + bredband, 25% VAT).
|
||||
const sevenDaysFromNow = new Date(today)
|
||||
sevenDaysFromNow.setDate(today.getDate() + 7)
|
||||
|
||||
// Hardcode 1 and 2 — get_next_arrival_number is MAX+1 against the same
|
||||
// table we're about to insert into, so calling it twice before the first
|
||||
// insert lands gives the same value for both rows and violates the
|
||||
// (company_id, arrival_number) unique index. The company is brand new
|
||||
// here, so 1 and 2 are guaranteed to be free.
|
||||
const { data: supInvoices, error: supInvError } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.insert([
|
||||
{
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
supplier_id: supplierMap['Demo Telekom AB'],
|
||||
arrival_number: 1,
|
||||
supplier_invoice_number: '4711-2026-03',
|
||||
invoice_date: toDateStr(thirtyDaysAgo),
|
||||
due_date: toDateStr(today),
|
||||
received_date: toDateStr(thirtyDaysAgo),
|
||||
status: 'paid',
|
||||
currency: 'SEK',
|
||||
subtotal: 480,
|
||||
vat_amount: 120,
|
||||
total: 600,
|
||||
payment_reference: '47112026031',
|
||||
paid_at: toDateStr(fifteenDaysAgo),
|
||||
paid_amount: 600,
|
||||
},
|
||||
{
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
supplier_id: supplierMap['Demokafé AB'],
|
||||
arrival_number: 2,
|
||||
supplier_invoice_number: '88245',
|
||||
invoice_date: toDateStr(fiveDaysAgo),
|
||||
due_date: toDateStr(sevenDaysFromNow),
|
||||
received_date: toDateStr(fiveDaysAgo),
|
||||
status: 'registered',
|
||||
currency: 'SEK',
|
||||
subtotal: 240,
|
||||
vat_amount: 28.80,
|
||||
total: 268.80,
|
||||
// Must be set explicitly: PostgREST normalizes columns across
|
||||
// rows in a bulk insert, so omitting paid_amount here while the
|
||||
// first row sets it sends null instead of falling through to the
|
||||
// schema default (0), violating the NOT NULL constraint.
|
||||
paid_amount: 0,
|
||||
},
|
||||
])
|
||||
.select('id, supplier_invoice_number')
|
||||
|
||||
if (supInvError) throw supInvError
|
||||
const supInvoiceMap = Object.fromEntries(
|
||||
supInvoices.map(s => [s.supplier_invoice_number, s.id])
|
||||
)
|
||||
|
||||
// Supplier invoice line items. Note: supplier_invoice_items.vat_rate is
|
||||
// stored as a decimal (0.25 = 25%); invoice_items.vat_rate above uses
|
||||
// integer percent (25). Two different conventions inherited from earlier
|
||||
// migrations — don't try to "fix" it here.
|
||||
const { error: supItemsError } = await supabase
|
||||
.from('supplier_invoice_items')
|
||||
.insert([
|
||||
{
|
||||
supplier_invoice_id: supInvoiceMap['4711-2026-03'],
|
||||
description: 'Mobil + bredband — mars',
|
||||
quantity: 1,
|
||||
unit_price: 480,
|
||||
line_total: 480,
|
||||
vat_rate: 0.25,
|
||||
vat_amount: 120,
|
||||
account_number: '6212',
|
||||
},
|
||||
{
|
||||
supplier_invoice_id: supInvoiceMap['88245'],
|
||||
description: 'Kundmöte Demokafé (representation)',
|
||||
quantity: 1,
|
||||
unit_price: 240,
|
||||
line_total: 240,
|
||||
vat_rate: 0.12,
|
||||
vat_amount: 28.80,
|
||||
account_number: '5810',
|
||||
},
|
||||
])
|
||||
|
||||
if (supItemsError) throw supItemsError
|
||||
|
||||
// 14. Add one fully-depreciable asset (laptop) so /assets shows
|
||||
// something other than a Package empty state. Acquired 18 months ago,
|
||||
// 60-month linear depreciation. Cost set above the 2026
|
||||
// förbrukningsinventarier threshold (half prisbasbelopp ≈ 29 600 SEK)
|
||||
// so the demo unambiguously illustrates capitalization rather than
|
||||
// direct expensing.
|
||||
const eighteenMonthsAgo = new Date(today)
|
||||
eighteenMonthsAgo.setMonth(today.getMonth() - 18)
|
||||
const { error: assetError } = await supabase
|
||||
.from('assets')
|
||||
.insert({
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
name: 'Demo-laptop',
|
||||
category: 'computer',
|
||||
acquisition_date: toDateStr(eighteenMonthsAgo),
|
||||
acquisition_cost: 35000,
|
||||
salvage_value: 0,
|
||||
useful_life_months: 60,
|
||||
depreciation_method: 'linear',
|
||||
bas_asset_account: '1250',
|
||||
bas_accumulated_account: '1259',
|
||||
bas_expense_account: '7831',
|
||||
notes: 'Demo-tillgång — visar planenlig avskrivning över 5 år.',
|
||||
})
|
||||
|
||||
if (assetError) throw assetError
|
||||
|
||||
// 15. Pre-built, verified agent_profile so the assistant chrome (FAB,
|
||||
// /chat surface, agent identity in nav) renders without firing a
|
||||
// composer run. The chat itself is server-gated by guardSandbox().
|
||||
// Delegated to ensureSandboxAgentProfile so the persona lives in one
|
||||
// place (this seed, the dashboard/chat layout backfill, and the seed
|
||||
// top-up path all use the same helper).
|
||||
await ensureSandboxAgentProfile(supabase, companyId)
|
||||
|
||||
// 16. Pre-staged pending_operations so /pending isn't empty.
|
||||
// These are the kind of operation the AI agent would stage; pre-seeded
|
||||
// here so the user can see the approval queue UI (preview, period
|
||||
// status, risk level) without having to invoke the disabled AI.
|
||||
// actor_type='agent_chat' + risk_level on the row itself is required by
|
||||
// pending_operations_chat_insert (the only RLS policy that lets a
|
||||
// user-scoped client INSERT into this table).
|
||||
const { error: pendOpsError } = await supabase
|
||||
.from('pending_operations')
|
||||
.insert([
|
||||
{
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
operation_type: 'create_supplier_invoice_from_inbox',
|
||||
status: 'pending',
|
||||
actor_type: 'agent_chat',
|
||||
risk_level: 'low',
|
||||
// Uses a distinct supplier_invoice_number so approving this
|
||||
// pending operation creates a NEW supplier_invoices row instead
|
||||
// of colliding with the Demokafé '88245' already booked above
|
||||
// (BFL 5 kap — each affärshändelse must be recorded exactly once).
|
||||
title: 'Registrera leverantörsfaktura — Demokafé (representation, nytt underlag)',
|
||||
params: {
|
||||
supplier_id: supplierMap['Demokafé AB'],
|
||||
supplier_invoice_number: 'INKOMMANDE-2026-001',
|
||||
invoice_date: toDateStr(fiveDaysAgo),
|
||||
due_date: toDateStr(sevenDaysFromNow),
|
||||
total: 268.80,
|
||||
vat_amount: 28.80,
|
||||
account_number: '5810',
|
||||
},
|
||||
preview_data: {
|
||||
// Representation @ 12% VAT (café meal), 240 SEK excl. VAT for
|
||||
// a single attendee. The avdragsrätt cap is 25% × 300 SEK ×
|
||||
// antal_personer = 75 SEK / person (ML 8 kap. 9 §); since the
|
||||
// VAT here is 28.80 SEK the full amount is deductible and the
|
||||
// cost lands in 5810 — no split needed.
|
||||
preview_lines: [
|
||||
{ account: '5810', description: 'Representation (12% moms, ≤ 75 SEK moms/pers)', debit: 240, credit: 0 },
|
||||
{ account: '2641', description: 'Ingående moms', debit: 28.80, credit: 0 },
|
||||
{ account: '2440', description: 'Leverantörsskulder', debit: 0, credit: 268.80 },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
user_id: userId,
|
||||
company_id: companyId,
|
||||
operation_type: 'categorize_transaction',
|
||||
status: 'pending',
|
||||
actor_type: 'agent_chat',
|
||||
risk_level: 'low',
|
||||
title: 'Bokför insättning — bankgiro',
|
||||
params: {
|
||||
account_number: '3001',
|
||||
is_business: true,
|
||||
vat_treatment: 'standard_25',
|
||||
},
|
||||
preview_data: {
|
||||
preview_lines: [
|
||||
{ account: '1930', description: 'Företagskonto', debit: 1200, credit: 0 },
|
||||
{ account: '2611', description: 'Utgående moms 25%', debit: 0, credit: 240 },
|
||||
{ account: '3001', description: 'Försäljning 25% moms', debit: 0, credit: 960 },
|
||||
],
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
if (pendOpsError) throw pendOpsError
|
||||
|
||||
return NextResponse.json({ seeded: true })
|
||||
} catch (err) {
|
||||
log.error('failed to seed sandbox data', { error: err, userId: user.id, companyId })
|
||||
@@ -590,3 +842,17 @@ export async function POST(request: Request) {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotent top-up for sandboxes that pre-date the agent_profile addition
|
||||
* to the seed. Re-running the seed on those older sandboxes short-circuits
|
||||
* at the company_settings idempotency check above, so they never get the
|
||||
* agent_profile without this hook. Delegates to ensureSandboxAgentProfile
|
||||
* so the profile data stays in exactly one place.
|
||||
*/
|
||||
async function topUpSandboxAdditions(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<void> {
|
||||
await ensureSandboxAgentProfile(supabase, companyId)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import type { Currency, Transaction } from '@/types'
|
||||
|
||||
export const POST = withRouteContext(
|
||||
@@ -10,6 +11,9 @@ export const POST = withRouteContext(
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const { data: transaction, error: fetchError } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
|
||||
@@ -73,6 +73,15 @@ vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue({}),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
|
||||
// The sandbox guard reads company_settings.is_sandbox at the top of the
|
||||
// route; the per-table mock supabase below has no row for that lookup so
|
||||
// short-circuit the guard in tests.
|
||||
vi.mock('@/lib/sandbox/guard', () => ({
|
||||
guardSandbox: vi.fn().mockResolvedValue(null),
|
||||
isSandboxCompany: vi.fn().mockResolvedValue(false),
|
||||
sandboxBlockedResponse: vi.fn(),
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
|
||||
@@ -54,6 +54,7 @@ import { createInvoiceJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import type { CompanySettings, Customer, EntityType, Invoice, InvoiceItem } from '@/types'
|
||||
|
||||
const INVOICE_SEND_RESPONSE_COLUMNS =
|
||||
@@ -136,6 +137,11 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
|
||||
// Sandbox demo never sends a real email — guard the whole pipeline
|
||||
// before any number is allocated or PDF is rendered.
|
||||
const blocked = await guardSandbox(ctx.supabase, ctx.companyId!)
|
||||
if (blocked) return blocked
|
||||
|
||||
// Step 1: email service configured?
|
||||
const emailService = getEmailService()
|
||||
if (!emailService.isConfigured()) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { validateBody } from '@/lib/api/validate'
|
||||
import { ValidateVatNumberSchema } from '@/lib/api/schemas'
|
||||
import { validateVatNumber } from '@/lib/vat/vies-client'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
@@ -16,6 +17,11 @@ export async function POST(request: Request) {
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
// VIES is a live external call to the EU Commission — block in the sandbox
|
||||
// so the demo can't generate background traffic against it.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const result = await validateBody(request, ValidateVatNumberSchema)
|
||||
if (!result.success) return result.response
|
||||
const { vat_number, customer_id } = result.data
|
||||
|
||||
Reference in New Issue
Block a user