Merge remote-tracking branch 'origin/main' into logger
This commit is contained in:
@@ -23,7 +23,9 @@
|
||||
"Bash(npx tsc:*)",
|
||||
"Bash(findstr:*)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(git commit:*)"
|
||||
"Bash(git commit:*)",
|
||||
"WebFetch(domain:raw.githubusercontent.com)",
|
||||
"WebFetch(domain:support.fortnox.se)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ erp-base is a Swedish-focused accounting SaaS for sole traders (enskild firma) a
|
||||
|
||||
**Tech stack**: Next.js 16 (App Router), React 19, TypeScript (strict), Supabase (PostgreSQL + RLS + magic link auth), Tailwind CSS 4 + shadcn/ui, Vercel hosting.
|
||||
|
||||
**Integrations**: Enable Banking (PSD2), Anthropic SDK, OpenAI (embeddings), Resend (email), web-push (VAPID).
|
||||
**Integrations**: Enable Banking (PSD2), Anthropic SDK, LangChain, OpenAI (embeddings), Resend (email), web-push (VAPID).
|
||||
|
||||
**Path alias**: `@/*` maps to the project root (tsconfig.json).
|
||||
|
||||
@@ -34,7 +34,8 @@ app/
|
||||
(onboarding)/ 6-step setup wizard
|
||||
(dashboard)/ Authenticated routes (invoices, customers, transactions,
|
||||
bookkeeping, reports, suppliers, supplier-invoices,
|
||||
receipts, settings, calendar, help, import)
|
||||
receipts, settings, calendar, help, import,
|
||||
extensions, e/[sector]/[slug])
|
||||
(public)/ Public invoice action links (no auth)
|
||||
api/ API routes organized by domain
|
||||
|
||||
@@ -43,22 +44,52 @@ components/
|
||||
bookkeeping/ Chart of accounts manager, account combobox, add/edit dialogs
|
||||
calendar/ Calendar views, deadline cards, payment summary, todo widgets
|
||||
chat/ ChatWidget, ChatPanel, ChatInput, ChatMessage
|
||||
customers/ CustomerForm
|
||||
dashboard/ DashboardContent, DashboardNav, FSkattWarningCard
|
||||
extensions/ Extension marketplace UI (ExtensionCard, SectorCard,
|
||||
ExtensionToggleButton, workspace components,
|
||||
per-sector subdirectories)
|
||||
import/ Bank file import workflow components
|
||||
invoices/ InvoiceReviewContent
|
||||
onboarding/ NewUserChecklist, setup step components
|
||||
reports/ Report views (including BankReconciliationView)
|
||||
settings/ CalendarFeedSettings
|
||||
[feature]/ Feature-organized components (invoices, suppliers, import, etc.)
|
||||
suppliers/ Supplier-related components
|
||||
transactions/ Transaction list, categorization, booking components
|
||||
|
||||
extensions/ First-party extension implementations
|
||||
ai-categorization/ AI-powered transaction categorization
|
||||
ai-chat/ Claude-based chat assistant
|
||||
enable-banking/ PSD2 bank integration via Enable Banking (JWT auth, sync)
|
||||
ne-bilaga/ NE tax form attachment generation
|
||||
push-notifications/ Web push notification system
|
||||
receipt-ocr/ Receipt image OCR processing
|
||||
sru-export/ SRU file export
|
||||
example-logger/ Minimal reference extension (not loaded by default)
|
||||
extensions/ Sector-based extension hierarchy
|
||||
general/ General-purpose extensions (all businesses)
|
||||
ai-categorization/ AI-powered transaction categorization
|
||||
ai-chat/ Claude-based chat assistant (LangChain RAG)
|
||||
enable-banking/ PSD2 bank integration (opt-in, commented out in loader)
|
||||
example-logger/ Minimal reference extension (not loaded)
|
||||
invoice-inbox/ Supplier invoice intake via email/upload with AI extraction
|
||||
push-notifications/ Web push notification system
|
||||
receipt-ocr/ Receipt image OCR processing (includes components/pages)
|
||||
restaurant/ Restaurant & cafe sector
|
||||
food-cost/ Food cost percentage calculator
|
||||
earnings-per-liter/ Revenue per liter of alcohol
|
||||
pos-import/ POS Z-report import
|
||||
tip-tracking/ Tip tracking per shift/employee
|
||||
construction/ Construction & trades sector
|
||||
rot-calculator/ ROT tax deduction calculator
|
||||
project-cost/ Project cost tracking
|
||||
hotel/ Hotel & lodging sector
|
||||
revpar/ Revenue Per Available Room
|
||||
occupancy/ Occupancy rate tracking
|
||||
tech/ IT & consulting sector
|
||||
billable-hours/ Billable hours & utilization rate
|
||||
project-billing/ Project billing analysis
|
||||
ecommerce/ E-commerce sector
|
||||
shopify-import/ Shopify order import
|
||||
multichannel-revenue/ Multi-channel revenue analysis
|
||||
ne-bilaga/ NE tax form attachment generation (top-level)
|
||||
sru-export/ SRU file export (top-level)
|
||||
|
||||
lib/
|
||||
api/ Zod validation schemas and utilities for API routes
|
||||
schemas.ts Zod schemas for all API request bodies and query params
|
||||
validate.ts validateBody() and validateQuery() helpers
|
||||
bookkeeping/ Core journal entry engine and all entry generators
|
||||
engine.ts Draft/commit workflow, balance validation, voucher numbering
|
||||
invoice-entries.ts Sales invoice journal entries (supports per-line VAT rates)
|
||||
@@ -70,23 +101,34 @@ lib/
|
||||
bas-reference.ts BAS account catalog (~180 accounts with metadata, SRU codes)
|
||||
account-descriptions.ts Human-readable account name lookup
|
||||
validate-period-duration.ts Fiscal period duration validation (BFL 3 kap.)
|
||||
handlers/ Booking handler functions (supplier-invoice-handler.ts)
|
||||
core/
|
||||
bookkeeping/ Period service, storno reversal, year-end closing
|
||||
documents/ Document archive (upload, versioning, SHA-256 integrity)
|
||||
audit/ Audit trail service
|
||||
tax/ Tax code service
|
||||
calendar/ Calendar and scheduling utilities
|
||||
calendar/ Calendar utilities, ICS feed generation
|
||||
currency/ Riksbanken exchange rates
|
||||
customers/ Customer management helpers
|
||||
deadlines/ Tax deadline tracking
|
||||
email/ Email service (Resend integration)
|
||||
deadlines/ Tax deadline tracking, status engine
|
||||
email/ Email service (Resend), invoice/reminder templates
|
||||
events/ Event bus (bus.ts, types.ts)
|
||||
extensions/ Extension registry, loader, types
|
||||
import/ SIE and bank file parser
|
||||
extensions/ Extension system
|
||||
loader.ts FIRST_PARTY_EXTENSIONS array, static imports
|
||||
registry.ts Runtime extension registry
|
||||
types.ts Extension, Sector, ExtensionDefinition, toggle types
|
||||
sectors.ts Sector & extension metadata registry (pure data)
|
||||
hooks.ts React hooks for extension state
|
||||
context-factory.ts Extension context builder
|
||||
toggle-check.ts Extension enable/disable logic
|
||||
validation.ts Extension data validation
|
||||
workspace-registry.tsx Extension workspace component registry
|
||||
icon-resolver.tsx Dynamic icon lookup for extensions
|
||||
use-account-totals.ts Hook for account balance queries
|
||||
use-extension-data.ts Hook for extension-specific data
|
||||
import/ SIE parser, SIE import orchestrator, bank file parser
|
||||
bank-file/ Bank file parser with format modules
|
||||
formats/ camt053, generic-csv, handelsbanken, nordea, seb, swedbank
|
||||
invoice/ VAT rules, invoice matching (vat-rules.ts, invoice-matching.ts)
|
||||
invoices/ Invoice business logic (reminder-processor)
|
||||
invoices/ VAT rules, invoice matching, PDF template, reminder processor
|
||||
reconciliation/ Bank reconciliation engine (4-pass matching algorithm)
|
||||
reports/ Financial reports (trial-balance, income-statement,
|
||||
balance-sheet, vat-declaration, sie-export,
|
||||
@@ -94,18 +136,22 @@ lib/
|
||||
general-ledger, journal-register,
|
||||
ar-ledger, ar-reconciliation, monthly-breakdown)
|
||||
supabase/ Client setup (client.ts = browser, server.ts = server/admin,
|
||||
fetch-all.ts = pagination helper for large queries)
|
||||
tax/ Tax calculations, deadlines, Swedish holidays
|
||||
transactions/ Transaction processing helpers
|
||||
fetch-all.ts = pagination helper, middleware.ts)
|
||||
tax/ Tax calculations, deadlines, Swedish holidays, expense warnings
|
||||
transactions/ Transaction processing, category suggestions
|
||||
init.ts Extension loader (idempotent, called by API routes)
|
||||
utils.ts Shared utility functions
|
||||
|
||||
types/index.ts Canonical type definitions (120+ types, single source of truth)
|
||||
types/index.ts Canonical type definitions (single source of truth)
|
||||
types/chat.ts Chat-specific type definitions
|
||||
tests/helpers.ts Mock factories and fixture builders
|
||||
supabase/migrations/ SQL migration files
|
||||
scripts/ Utility scripts (clear-user-data.sql)
|
||||
dev_docs/ Extensive project documentation (PRD, architecture, BAS guide, etc.)
|
||||
scripts/ Utility scripts (clear-user-data.sql, copy-extensions.mjs,
|
||||
move-extensions.js, setup-phase8.js)
|
||||
dev_docs/ Project documentation (BAS account guides, gap analysis,
|
||||
Enable Banking docs, Bokio reference screenshots)
|
||||
extensions.md Extension system design document (architecture, data patterns,
|
||||
sector model, workspace pattern, migration plan)
|
||||
```
|
||||
|
||||
### Key Relationships
|
||||
@@ -114,6 +160,7 @@ dev_docs/ Extensive project documentation (PRD, architecture, BA
|
||||
- **API routes** that emit events must call `ensureInitialized()` (from `lib/init.ts`) at module level to load extensions.
|
||||
- **Event bus** (`lib/events/bus.ts`) is a module-level singleton. Core services emit, extensions subscribe.
|
||||
- **Supabase clients**: browser (`lib/supabase/client.ts`), server with user cookies (`createClient()` from `lib/supabase/server.ts`), and service role (`createServiceClient()`).
|
||||
- **Extension sector system**: Extensions are organized by business sector (`lib/extensions/sectors.ts`). Users can browse/toggle extensions via the marketplace UI (`app/(dashboard)/extensions/`). Sector-specific extension workspaces are rendered at `app/(dashboard)/e/[sector]/[slug]/`.
|
||||
|
||||
---
|
||||
|
||||
@@ -163,7 +210,7 @@ The bookkeeping engine (`lib/bookkeeping/engine.ts`) is the most critical system
|
||||
|
||||
### Per-Line VAT
|
||||
|
||||
Invoice items support individual `vat_rate` values, enabling mixed-rate invoices. The helper `generatePerRateLines()` in `invoice-entries.ts` groups items by VAT rate and creates separate revenue + VAT account lines per rate group. Available rates depend on customer type — use `getAvailableVatRates(customerType, vatNumberValidated)` from `lib/invoice/vat-rules.ts`.
|
||||
Invoice items support individual `vat_rate` values, enabling mixed-rate invoices. The helper `generatePerRateLines()` in `invoice-entries.ts` groups items by VAT rate and creates separate revenue + VAT account lines per rate group. Available rates depend on customer type — use `getAvailableVatRates(customerType, vatNumberValidated)` from `lib/invoices/vat-rules.ts`.
|
||||
|
||||
### Bank Reconciliation
|
||||
|
||||
@@ -199,14 +246,39 @@ These rules exist for legal compliance and are enforced by database triggers. **
|
||||
|
||||
## Extension Development
|
||||
|
||||
Extensions are first-party plugins in the `/extensions/` directory, loaded statically at startup.
|
||||
Extensions are first-party plugins organized by business sector in the `/extensions/` directory, loaded statically at startup.
|
||||
|
||||
### Sector System
|
||||
|
||||
Extensions are grouped into sectors defined in `lib/extensions/sectors.ts`. Each sector targets a specific industry (restaurant, construction, hotel, tech, ecommerce) or serves all businesses (general). The sector registry provides metadata used by the extension marketplace UI.
|
||||
|
||||
Key types (from `lib/extensions/types.ts`):
|
||||
- `SectorSlug` — `'general' | 'restaurant' | 'construction' | 'hotel' | 'tech' | 'ecommerce'`
|
||||
- `ExtensionDefinition` — Marketplace metadata (slug, name, sector, category, icon, dataPattern, description)
|
||||
- `ExtensionCategory` — `'import' | 'operations' | 'reports' | 'accounting'`
|
||||
- `ExtensionDataPattern` — `'core' | 'manual' | 'both'` (how extension accesses data)
|
||||
- `ExtensionToggle` — Per-user enable/disable state for extensions
|
||||
|
||||
### Creating a New Extension
|
||||
|
||||
1. Create `extensions/<name>/index.ts`
|
||||
1. Create `extensions/<sector>/<name>/index.ts`
|
||||
2. Export an object implementing the `Extension` interface from `lib/extensions/types.ts`
|
||||
3. Add a static import to the `FIRST_PARTY_EXTENSIONS` array in `lib/extensions/loader.ts`
|
||||
4. Extensions **cannot** use dynamic imports (Next.js bundling constraint)
|
||||
4. Add metadata to the appropriate sector in `lib/extensions/sectors.ts`
|
||||
5. Extensions **cannot** use dynamic imports (Next.js bundling constraint)
|
||||
|
||||
### Currently Loaded Extensions (FIRST_PARTY_EXTENSIONS)
|
||||
|
||||
```
|
||||
receiptOcrExtension @/extensions/general/receipt-ocr
|
||||
aiCategorizationExtension @/extensions/general/ai-categorization
|
||||
pushNotificationsExtension @/extensions/general/push-notifications
|
||||
sruExportExtension @/extensions/sru-export
|
||||
neBilagaExtension @/extensions/ne-bilaga
|
||||
aiChatExtension @/extensions/general/ai-chat
|
||||
invoiceInboxExtension @/extensions/general/invoice-inbox
|
||||
# enableBankingExtension @/extensions/general/enable-banking (commented out, opt-in)
|
||||
```
|
||||
|
||||
### Extension Interface
|
||||
|
||||
@@ -235,7 +307,7 @@ interface Extension {
|
||||
|
||||
### Minimal Example
|
||||
|
||||
See `extensions/example-logger/index.ts`:
|
||||
See `extensions/general/example-logger/index.ts`:
|
||||
|
||||
```typescript
|
||||
import type { Extension } from '@/lib/extensions/types'
|
||||
@@ -273,6 +345,7 @@ All defined in `lib/events/types.ts`:
|
||||
| `credit_note.created` | `{ creditNote, userId }` |
|
||||
| `transaction.synced` | `{ transactions[], userId }` |
|
||||
| `transaction.categorized` | `{ transaction, account, taxCode, userId }` |
|
||||
| `transaction.reconciled` | `{ transaction, journalEntryId, method, userId }` |
|
||||
| `bank.statement_received` | `{ statement, userId }` |
|
||||
| `bank.payment_notification` | `{ notification, userId }` |
|
||||
| `period.locked` | `{ period, userId }` |
|
||||
@@ -282,7 +355,9 @@ All defined in `lib/events/types.ts`:
|
||||
| `receipt.extracted` | `{ receipt, documentId, confidence, userId }` |
|
||||
| `receipt.matched` | `{ receipt, transaction, confidence, autoMatched, userId }` |
|
||||
| `receipt.confirmed` | `{ receipt, businessTotal, privateTotal, userId }` |
|
||||
| `transaction.reconciled` | `{ transaction, journalEntryId, method, userId }` |
|
||||
| `supplier_invoice.received` | `{ inboxItem, userId }` |
|
||||
| `supplier_invoice.extracted` | `{ inboxItem, confidence, userId }` |
|
||||
| `supplier_invoice.confirmed` | `{ inboxItem, supplierInvoice, userId }` |
|
||||
| `audit.security_event` | `{ event, userId }` |
|
||||
|
||||
### Event Bus Behavior
|
||||
@@ -325,6 +400,13 @@ mockResult({ data: makeTransaction(), error: null })
|
||||
- `makeJournalEntryLine()` — Line with account number, zero amounts
|
||||
- `makeDocumentAttachment()` — Document with hash, storage path
|
||||
- `makeTaxCode()` — TaxCode with default output VAT 25%
|
||||
- `makeInvoice()` — Invoice with default customer, amounts, dates
|
||||
- `makeCustomer()` — Customer with default name, address
|
||||
- `makeSupplier()` — Supplier with default details
|
||||
- `makeSupplierInvoice()` — Supplier invoice with default amounts
|
||||
- `makeCompanySettings()` — Company settings with defaults
|
||||
- `makeInvoiceInboxItem()` — Invoice inbox item for supplier invoice intake
|
||||
- `makeExtensionToggle()` — Extension toggle state
|
||||
|
||||
### Patterns
|
||||
|
||||
@@ -344,6 +426,8 @@ mockResult({ data: makeTransaction(), error: null })
|
||||
|
||||
### Reference Tests
|
||||
|
||||
- `lib/api/__tests__/schemas.test.ts` — Zod schema validation
|
||||
- `lib/api/__tests__/validate.test.ts` — Body/query validation helpers
|
||||
- `lib/bookkeeping/__tests__/engine.test.ts` — Balance validation
|
||||
- `lib/bookkeeping/__tests__/invoice-entries.test.ts` — Per-line VAT, mixed-rate invoices, credit notes
|
||||
- `lib/core/bookkeeping/__tests__/storno-service.test.ts` — Complex mock queues
|
||||
@@ -363,11 +447,11 @@ mockResult({ data: makeTransaction(), error: null })
|
||||
|
||||
### Location
|
||||
|
||||
`supabase/migrations/` — currently 32 files numbered `20240101000001` through `20240101000032`.
|
||||
`supabase/migrations/` — currently 39 files numbered `20240101000001` through `20240101000038` (note: two files share number `000033`).
|
||||
|
||||
### Naming Convention
|
||||
|
||||
`YYYYMMDD00NNNN_descriptive_name.sql` — next migration: `20240101000033_*.sql`
|
||||
`YYYYMMDD00NNNN_descriptive_name.sql` — next migration: `20240101000039_*.sql`
|
||||
|
||||
### Migration Rules
|
||||
|
||||
@@ -406,6 +490,13 @@ mockResult({ data: makeTransaction(), error: null })
|
||||
- **Migration 030 (`bank_reconciliation`)** — Adds `reconciliation_method` column to `transactions` (CHECK constraint for method types), indexes for unmatched transaction lookup, and RPC `get_unlinked_1930_lines()` for finding unreconciled GL lines.
|
||||
- **Migration 031 (`invoice_document_type`)** — Adds `document_type` column to `invoices` (CHECK: invoice/proforma/delivery_note, default 'invoice') and `converted_from_id` FK for tracking proforma-to-invoice conversions.
|
||||
- **Migration 032 (`add_accounting_method`)** — Adds `accounting_method` column to `company_settings` (CHECK: accrual/cash, default 'accrual') to support kontantmetoden vs faktureringsmetoden.
|
||||
- **Migration 033 (`ai_chat_schema`)** — AI chat conversation and message storage.
|
||||
- **Migration 033 (`invoice_inbox`)** — Invoice inbox table for supplier invoice intake. (Note: shares number with ai_chat_schema.)
|
||||
- **Migration 034 (`fix_extension_data_trigger`)** — Fixes extension data trigger.
|
||||
- **Migration 035 (`fix_push_notifications`)** — Push notifications schema fix.
|
||||
- **Migration 036 (`fix_enable_banking`)** — Enable Banking schema fix.
|
||||
- **Migration 037 (`extension_toggles`)** — Extension toggle table for per-user enable/disable.
|
||||
- **Migration 038 (`fix_match_documents_search_path`)** — Fixes search path for document matching function.
|
||||
|
||||
---
|
||||
|
||||
@@ -426,6 +517,8 @@ Standard pattern for new API routes:
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateInvoiceSchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized() // Module-level — loads extensions for event emission
|
||||
|
||||
@@ -437,7 +530,12 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
// Business logic...
|
||||
// Validate request body with Zod schema
|
||||
const result = await validateBody(request, CreateInvoiceSchema)
|
||||
if (!result.success) return result.response
|
||||
const { data } = result
|
||||
|
||||
// Business logic using validated `data`...
|
||||
// Always filter by user_id (defense in depth alongside RLS)
|
||||
// Wrap journal entry creation in try/catch (non-blocking side effect)
|
||||
// Emit events after successful operations
|
||||
@@ -448,6 +546,7 @@ export async function POST(request: Request) {
|
||||
|
||||
**Key conventions**:
|
||||
- Call `ensureInitialized()` at module level in any route that emits events
|
||||
- **Validate all input** with `validateBody()` / `validateQuery()` from `lib/api/validate.ts` using schemas from `lib/api/schemas.ts`
|
||||
- Dynamic route params use `{ params }: { params: Promise<{ id: string }> }` (Next.js 16)
|
||||
- Response shapes: `{ data }` for success, `{ error }` for failures
|
||||
- Journal entry creation is non-blocking: catch errors and continue
|
||||
@@ -498,13 +597,19 @@ Hosted on **Vercel** with cron jobs defined in `vercel.json`:
|
||||
NEXT_PUBLIC_SUPABASE_URL # Supabase project URL
|
||||
NEXT_PUBLIC_SUPABASE_ANON_KEY # Supabase anonymous key
|
||||
SUPABASE_SERVICE_ROLE_KEY # Supabase service role key
|
||||
RESEND_API_KEY # Resend email service API key
|
||||
RESEND_FROM_EMAIL # Sender email for transactional mail
|
||||
RESEND_WEBHOOK_SECRET # Webhook auth for Resend
|
||||
ENABLE_BANKING_APP_ID # Enable Banking app ID
|
||||
ENABLE_BANKING_PRIVATE_KEY # Enable Banking private key (base64-encoded)
|
||||
ENABLE_BANKING_SANDBOX # Enable Banking sandbox mode flag
|
||||
ANTHROPIC_API_KEY # Claude API key (ai-chat)
|
||||
OPENAI_API_KEY # OpenAI API key (embeddings)
|
||||
NEXT_PUBLIC_APP_URL # App base URL
|
||||
CRON_SECRET # Auth secret for Vercel cron jobs
|
||||
NEXT_PUBLIC_VAPID_PUBLIC_KEY # Web push public key
|
||||
VAPID_PRIVATE_KEY # Web push private key
|
||||
VAPID_SUBJECT # VAPID subject (mailto: URI) for web push
|
||||
```
|
||||
|
||||
## Other
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Label } from '@/components/ui/label'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, Mail, Sparkles } from 'lucide-react'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
export default function LoginPage() {
|
||||
const [email, setEmail] = useState('')
|
||||
@@ -30,8 +31,8 @@ export default function LoginPage() {
|
||||
|
||||
if (error) {
|
||||
toast({
|
||||
title: 'Fel',
|
||||
description: error.message,
|
||||
title: 'Inloggning misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
@@ -42,10 +43,10 @@ export default function LoginPage() {
|
||||
title: 'E-post skickad!',
|
||||
description: 'Kolla din inkorg för att logga in.',
|
||||
})
|
||||
} catch {
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Fel',
|
||||
description: 'Något gick fel. Försök igen.',
|
||||
title: 'Inloggning misslyckades',
|
||||
description: getErrorMessage(error, { context: 'auth' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import CustomerForm from '@/components/customers/CustomerForm'
|
||||
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Building,
|
||||
@@ -66,6 +67,7 @@ export default function CustomerDetailPage({
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isEditOpen, setIsEditOpen] = useState(false)
|
||||
const [isUpdating, setIsUpdating] = useState(false)
|
||||
const { dialogProps: confirmDialogProps, confirm: confirmAction } = useDestructiveConfirm()
|
||||
|
||||
useEffect(() => {
|
||||
fetchCustomer()
|
||||
@@ -124,7 +126,13 @@ export default function CustomerDetailPage({
|
||||
|
||||
async function handleDelete() {
|
||||
if (!customer) return
|
||||
if (!confirm(`Ta bort "${customer.name}"? Detta kan inte angras.`)) return
|
||||
const ok = await confirmAction({
|
||||
title: `Ta bort ${customer.name}`,
|
||||
description: 'Kunden och tillhörande data tas bort permanent. Denna åtgärd kan inte ångras.',
|
||||
confirmLabel: 'Ta bort',
|
||||
variant: 'destructive',
|
||||
})
|
||||
if (!ok) return
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/customers/${id}`, {
|
||||
@@ -352,6 +360,8 @@ export default function CustomerDetailPage({
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<DestructiveConfirmDialog {...confirmDialogProps} />
|
||||
|
||||
{/* Edit dialog */}
|
||||
<Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
|
||||
@@ -515,7 +515,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
{(() => {
|
||||
const vatByRate = new Map<number, number>()
|
||||
for (const item of invoice.items) {
|
||||
const rate = item.vat_rate ?? 25
|
||||
const rate = item.vat_rate ?? 0
|
||||
const lineVat = Math.round(item.line_total * (rate / 100) * 100) / 100
|
||||
vatByRate.set(rate, (vatByRate.get(rate) || 0) + lineVat)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, Di
|
||||
import { Loader2, Plus, Trash2, ArrowLeft, Send, Eye } from 'lucide-react'
|
||||
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
import { InvoiceReviewContent } from '@/components/invoices/InvoiceReviewContent'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
|
||||
import type { Customer, Currency, CreateInvoiceInput, InvoiceDocumentType } from '@/types'
|
||||
|
||||
const itemSchema = z.object({
|
||||
@@ -73,7 +75,7 @@ export default function NewInvoicePage() {
|
||||
handleSubmit,
|
||||
watch,
|
||||
setValue,
|
||||
formState: { errors },
|
||||
formState: { errors, isDirty },
|
||||
} = useForm<FormData>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
@@ -86,6 +88,8 @@ export default function NewInvoicePage() {
|
||||
},
|
||||
})
|
||||
|
||||
useUnsavedChanges(isDirty)
|
||||
|
||||
// Set date defaults on client only to avoid hydration mismatch
|
||||
useEffect(() => {
|
||||
setValue('invoice_date', format(new Date(), 'yyyy-MM-dd'))
|
||||
@@ -209,7 +213,7 @@ export default function NewInvoicePage() {
|
||||
const result = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.error || 'Kunde inte skapa faktura')
|
||||
throw new Error(getErrorMessage(result, { context: 'invoice', statusCode: response.status }))
|
||||
}
|
||||
|
||||
const docLabel = watchDocumentType === 'proforma' ? 'Proformafaktura' : watchDocumentType === 'delivery_note' ? 'Följesedel' : 'Faktura'
|
||||
@@ -229,8 +233,8 @@ export default function NewInvoicePage() {
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Fel',
|
||||
description: error instanceof Error ? error.message : 'Något gick fel',
|
||||
title: 'Kunde inte skapa faktura',
|
||||
description: getErrorMessage(error, { context: 'invoice' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -249,7 +253,7 @@ export default function NewInvoicePage() {
|
||||
|
||||
if (!response.ok) {
|
||||
const result = await response.json()
|
||||
throw new Error(result.error || 'Kunde inte skicka faktura')
|
||||
throw new Error(getErrorMessage(result, { context: 'invoice', statusCode: response.status }))
|
||||
}
|
||||
|
||||
toast({
|
||||
@@ -258,8 +262,8 @@ export default function NewInvoicePage() {
|
||||
})
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Fel vid skickning',
|
||||
description: error instanceof Error ? error.message : 'Något gick fel',
|
||||
title: 'Kunde inte skicka faktura',
|
||||
description: getErrorMessage(error, { context: 'invoice' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
@@ -292,7 +296,7 @@ export default function NewInvoicePage() {
|
||||
|
||||
if (!response.ok) {
|
||||
const result = await response.json()
|
||||
throw new Error(result.error || 'Kunde inte generera förhandsgranskning')
|
||||
throw new Error(getErrorMessage(result, { context: 'invoice', statusCode: response.status }))
|
||||
}
|
||||
|
||||
const blob = await response.blob()
|
||||
@@ -300,8 +304,8 @@ export default function NewInvoicePage() {
|
||||
window.open(url, '_blank')
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: 'Fel',
|
||||
description: error instanceof Error ? error.message : 'Kunde inte generera PDF',
|
||||
title: 'Kunde inte generera PDF',
|
||||
description: getErrorMessage(error, { context: 'invoice' }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
|
||||
@@ -170,6 +170,37 @@ export default async function DashboardPage() {
|
||||
.lt('amount', 0)
|
||||
.is('receipt_id', null)
|
||||
|
||||
// Count journal entries missing underlag (documents)
|
||||
// Source types that require supporting documents
|
||||
const needsDocSourceTypes = [
|
||||
'manual',
|
||||
'bank_transaction',
|
||||
'supplier_invoice_registered',
|
||||
'supplier_invoice_paid',
|
||||
'supplier_invoice_cash_payment',
|
||||
'import',
|
||||
]
|
||||
|
||||
const { count: postedEntriesCount } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'posted')
|
||||
.in('source_type', needsDocSourceTypes)
|
||||
|
||||
const { data: entriesWithDocs } = await supabase
|
||||
.from('document_attachments')
|
||||
.select('journal_entry_id')
|
||||
.eq('user_id', user.id)
|
||||
.eq('is_current_version', true)
|
||||
.not('journal_entry_id', 'is', null)
|
||||
|
||||
const uniqueEntriesWithDocs = new Set(
|
||||
(entriesWithDocs || []).map((d) => d.journal_entry_id)
|
||||
).size
|
||||
|
||||
const missingUnderlagCount = Math.max(0, (postedEntriesCount || 0) - uniqueEntriesWithDocs)
|
||||
|
||||
// Calculate receipt streak
|
||||
const { data: recentReceiptActivity } = await supabase
|
||||
.from('receipts')
|
||||
@@ -219,6 +250,7 @@ export default async function DashboardPage() {
|
||||
bankBalance,
|
||||
deadlines: (deadlines || []) as Deadline[],
|
||||
receiptQueue,
|
||||
missingUnderlagCount,
|
||||
}}
|
||||
onboardingProgress={onboardingProgress}
|
||||
/>
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { ArrowLeft, CheckCircle, CreditCard, FileText, Trash2 } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { AccountNumber } from '@/components/ui/account-number'
|
||||
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
||||
import type { SupplierInvoice, SupplierInvoiceItem, SupplierInvoicePayment } from '@/types'
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
@@ -47,6 +48,7 @@ export default function SupplierInvoiceDetailPage() {
|
||||
const [isPayDialogOpen, setIsPayDialogOpen] = useState(false)
|
||||
const [payAmount, setPayAmount] = useState('')
|
||||
const [isProcessing, setIsProcessing] = useState(false)
|
||||
const { dialogProps: confirmDialogProps, confirm: confirmAction } = useDestructiveConfirm()
|
||||
|
||||
useEffect(() => {
|
||||
fetchInvoice()
|
||||
@@ -100,7 +102,13 @@ export default function SupplierInvoiceDetailPage() {
|
||||
}
|
||||
|
||||
async function handleCredit() {
|
||||
if (!confirm('Vill du registrera en kreditfaktura för denna faktura?')) return
|
||||
const ok = await confirmAction({
|
||||
title: 'Registrera kreditfaktura',
|
||||
description: 'En kreditfaktura skapas som reverserar den ursprungliga fakturan. Denna åtgärd kan inte ångras.',
|
||||
confirmLabel: 'Registrera kreditfaktura',
|
||||
variant: 'warning',
|
||||
})
|
||||
if (!ok) return
|
||||
setIsProcessing(true)
|
||||
const res = await fetch(`/api/supplier-invoices/${params.id}/credit`, { method: 'POST' })
|
||||
const result = await res.json()
|
||||
@@ -114,7 +122,13 @@ export default function SupplierInvoiceDetailPage() {
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!confirm('Vill du ta bort denna faktura?')) return
|
||||
const ok = await confirmAction({
|
||||
title: 'Ta bort faktura',
|
||||
description: 'Fakturan och tillhörande data tas bort permanent. Denna åtgärd kan inte ångras.',
|
||||
confirmLabel: 'Ta bort',
|
||||
variant: 'destructive',
|
||||
})
|
||||
if (!ok) return
|
||||
const res = await fetch(`/api/supplier-invoices/${params.id}`, { method: 'DELETE' })
|
||||
const result = await res.json()
|
||||
if (!res.ok) {
|
||||
@@ -410,6 +424,8 @@ export default function SupplierInvoiceDetailPage() {
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<DestructiveConfirmDialog {...confirmDialogProps} />
|
||||
|
||||
{/* Pay Dialog */}
|
||||
<Dialog open={isPayDialogOpen} onOpenChange={setIsPayDialogOpen}>
|
||||
<DialogContent>
|
||||
|
||||
@@ -16,6 +16,8 @@ import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
|
||||
import { SupplierInvoiceReviewContent } from '@/components/suppliers/SupplierInvoiceReviewContent'
|
||||
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
|
||||
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
|
||||
import type { Supplier, BASAccount, VatTreatment } from '@/types'
|
||||
|
||||
interface LineItem {
|
||||
@@ -67,7 +69,7 @@ export default function NewSupplierInvoicePage() {
|
||||
const [showReview, setShowReview] = useState(false)
|
||||
const [pendingData, setPendingData] = useState<FormData | null>(null)
|
||||
|
||||
const { register, control, handleSubmit, watch, setValue } = useForm<FormData>({
|
||||
const { register, control, handleSubmit, watch, setValue, formState: { isDirty } } = useForm<FormData>({
|
||||
defaultValues: {
|
||||
supplier_id: '',
|
||||
supplier_invoice_number: '',
|
||||
@@ -90,6 +92,8 @@ export default function NewSupplierInvoicePage() {
|
||||
},
|
||||
})
|
||||
|
||||
useUnsavedChanges(isDirty)
|
||||
|
||||
const { fields, append, remove } = useFieldArray({ control, name: 'items' })
|
||||
const watchedItems = watch('items')
|
||||
const watchedSupplierId = watch('supplier_id')
|
||||
@@ -208,7 +212,7 @@ export default function NewSupplierInvoicePage() {
|
||||
const result = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({ title: 'Fel', description: result.error || 'Kunde inte registrera faktura', variant: 'destructive' })
|
||||
toast({ title: 'Kunde inte registrera faktura', description: getErrorMessage(result, { context: 'supplier_invoice', statusCode: res.status }), variant: 'destructive' })
|
||||
} else {
|
||||
toast({ title: 'Faktura registrerad', description: `Ankomstnummer: ${result.data.arrival_number}` })
|
||||
setShowReview(false)
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { ArrowLeft, Edit, Trash2, FileText } from 'lucide-react'
|
||||
import SupplierForm from '@/components/suppliers/SupplierForm'
|
||||
import Link from 'next/link'
|
||||
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
|
||||
import type { Supplier, SupplierType, CreateSupplierInput, SupplierInvoice } from '@/types'
|
||||
|
||||
const supplierTypeLabels: Record<SupplierType, string> = {
|
||||
@@ -31,6 +32,7 @@ export default function SupplierDetailPage() {
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [isEditOpen, setIsEditOpen] = useState(false)
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const { dialogProps: confirmDialogProps, confirm: confirmAction } = useDestructiveConfirm()
|
||||
|
||||
useEffect(() => {
|
||||
fetchSupplier()
|
||||
@@ -76,7 +78,13 @@ export default function SupplierDetailPage() {
|
||||
}
|
||||
|
||||
async function handleDelete() {
|
||||
if (!confirm('Är du säker på att du vill ta bort denna leverantör?')) return
|
||||
const ok = await confirmAction({
|
||||
title: 'Ta bort leverantör',
|
||||
description: `"${supplier?.name}" och tillhörande data tas bort permanent. Denna åtgärd kan inte ångras.`,
|
||||
confirmLabel: 'Ta bort',
|
||||
variant: 'destructive',
|
||||
})
|
||||
if (!ok) return
|
||||
|
||||
const res = await fetch(`/api/suppliers/${params.id}`, { method: 'DELETE' })
|
||||
const result = await res.json()
|
||||
@@ -267,6 +275,8 @@ export default function SupplierDetailPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<DestructiveConfirmDialog {...confirmDialogProps} />
|
||||
|
||||
{/* Edit Dialog */}
|
||||
<Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
|
||||
@@ -18,6 +18,9 @@ import TransactionHistoryList from '@/components/transactions/TransactionHistory
|
||||
import InboxZeroState from '@/components/transactions/InboxZeroState'
|
||||
import InvoiceMatchDialog from '@/components/transactions/InvoiceMatchDialog'
|
||||
import TransactionBookingDialog from '@/components/transactions/TransactionBookingDialog'
|
||||
import QuickReviewDialog from '@/components/transactions/QuickReviewDialog'
|
||||
import { EXPENSE_CATEGORIES, INCOME_CATEGORIES } from '@/components/transactions/transaction-types'
|
||||
import { getDefaultAccountForCategory, getDefaultVatTreatmentForCategory } from '@/lib/bookkeeping/category-mapping'
|
||||
import type { TransactionWithInvoice, ViewMode, CategorizeHandler } from '@/components/transactions/transaction-types'
|
||||
import type { TransactionCategory, CreateTransactionInput, Invoice, Customer, VatTreatment } from '@/types'
|
||||
import type { SuggestedCategory } from '@/lib/transactions/category-suggestions'
|
||||
@@ -48,6 +51,15 @@ export default function TransactionsPage() {
|
||||
const [bookingDialogOpen, setBookingDialogOpen] = useState(false)
|
||||
const [bookingDialogTransaction, setBookingDialogTransaction] = useState<TransactionWithInvoice | null>(null)
|
||||
|
||||
// Quick review dialog (suggestion review before booking)
|
||||
const [quickReviewOpen, setQuickReviewOpen] = useState(false)
|
||||
const [quickReviewTransaction, setQuickReviewTransaction] = useState<TransactionWithInvoice | null>(null)
|
||||
const [quickReviewCategory, setQuickReviewCategory] = useState<TransactionCategory | null>(null)
|
||||
const [quickReviewLabel, setQuickReviewLabel] = useState('')
|
||||
|
||||
// Entity type for tooltip context
|
||||
const [entityType, setEntityType] = useState<string>('enskild_firma')
|
||||
|
||||
// Set of transaction IDs that are animating out (just categorized)
|
||||
const [exitingIds, setExitingIds] = useState<Set<string>>(new Set())
|
||||
|
||||
@@ -128,6 +140,22 @@ export default function TransactionsPage() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => { fetchTransactions() }, [])
|
||||
|
||||
// Fetch entity type for tooltip context
|
||||
useEffect(() => {
|
||||
async function fetchEntityType() {
|
||||
try {
|
||||
const res = await fetch('/api/settings')
|
||||
const data = await res.json()
|
||||
if (data?.entity_type) {
|
||||
setEntityType(data.entity_type)
|
||||
}
|
||||
} catch {
|
||||
// Non-critical, defaults to enskild_firma
|
||||
}
|
||||
}
|
||||
fetchEntityType()
|
||||
}, [])
|
||||
|
||||
// Auto-fetch suggestions when transactions load
|
||||
useEffect(() => {
|
||||
const uncatIds = transactions
|
||||
@@ -157,7 +185,7 @@ export default function TransactionsPage() {
|
||||
if (!response.ok) {
|
||||
toast({ title: 'Fel', description: result.error || 'Kunde inte uppdatera transaktion', variant: 'destructive' })
|
||||
setProcessingId(null)
|
||||
return false
|
||||
return null
|
||||
}
|
||||
|
||||
// Mark as exiting for animation, then update state
|
||||
@@ -189,11 +217,11 @@ export default function TransactionsPage() {
|
||||
setProcessingId(null)
|
||||
}, 350)
|
||||
|
||||
return true
|
||||
return result.journal_entry_id || null
|
||||
} catch {
|
||||
toast({ title: 'Fel', description: 'Något gick fel vid bokföring', variant: 'destructive' })
|
||||
setProcessingId(null)
|
||||
return false
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,6 +444,30 @@ export default function TransactionsPage() {
|
||||
setBookingDialogOpen(true)
|
||||
}
|
||||
|
||||
function handleOpenQuickReview(transaction: TransactionWithInvoice, suggestion: SuggestedCategory) {
|
||||
const allCategories = [...EXPENSE_CATEGORIES, ...INCOME_CATEGORIES]
|
||||
const label = allCategories.find((c) => c.value === suggestion.category)?.label || suggestion.label
|
||||
setQuickReviewTransaction(transaction)
|
||||
setQuickReviewCategory(suggestion.category)
|
||||
setQuickReviewLabel(label)
|
||||
setQuickReviewOpen(true)
|
||||
}
|
||||
|
||||
async function handleQuickReviewConfirm(
|
||||
id: string,
|
||||
category: TransactionCategory,
|
||||
vatTreatment: VatTreatment | undefined,
|
||||
accountOverride: string | undefined
|
||||
): Promise<string | null> {
|
||||
const journalEntryId = await handleCategorize(id, true, category, vatTreatment, accountOverride)
|
||||
if (journalEntryId) {
|
||||
setQuickReviewOpen(false)
|
||||
setQuickReviewTransaction(null)
|
||||
setQuickReviewCategory(null)
|
||||
}
|
||||
return journalEntryId
|
||||
}
|
||||
|
||||
// Swipe view
|
||||
if (showSwipeView && uncategorizedTransactions.length > 0) {
|
||||
return (
|
||||
@@ -478,10 +530,12 @@ export default function TransactionsPage() {
|
||||
processingId={processingId}
|
||||
isBatchMode={isBatchMode}
|
||||
isSelected={selectedIds.has(transaction.id)}
|
||||
entityType={entityType}
|
||||
onCategorize={handleCategorize}
|
||||
onMarkPrivate={handleMarkPrivate}
|
||||
onOpenMatchDialog={openMatchDialog}
|
||||
onOpenCategoryDialog={openCategoryDialog}
|
||||
onOpenQuickReview={handleOpenQuickReview}
|
||||
onToggleSelect={toggleBatchSelect}
|
||||
/>
|
||||
))}
|
||||
@@ -537,6 +591,18 @@ export default function TransactionsPage() {
|
||||
onBooked={handleTransactionBooked}
|
||||
/>
|
||||
|
||||
<QuickReviewDialog
|
||||
key={quickReviewTransaction?.id ?? '' + String(quickReviewCategory)}
|
||||
open={quickReviewOpen}
|
||||
onOpenChange={setQuickReviewOpen}
|
||||
transaction={quickReviewTransaction}
|
||||
category={quickReviewCategory}
|
||||
categoryLabel={quickReviewLabel}
|
||||
defaultAccount={quickReviewCategory ? getDefaultAccountForCategory(quickReviewCategory) : ''}
|
||||
defaultVat={quickReviewCategory ? (getDefaultVatTreatmentForCategory(quickReviewCategory) ?? 'none') : 'none'}
|
||||
onConfirm={handleQuickReviewConfirm}
|
||||
/>
|
||||
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { createClient } from '@/lib/supabase/client'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { validatePeriodDuration } from '@/lib/bookkeeping/validate-period-duration'
|
||||
import type { CompanySettings, EntityType, MomsPeriod } from '@/types'
|
||||
|
||||
import Step1EntityType from '@/components/onboarding/Step1EntityType'
|
||||
@@ -26,6 +27,14 @@ const STEP_TITLES = [
|
||||
'Tillägg',
|
||||
]
|
||||
|
||||
function translatePeriodError(msg: string): string {
|
||||
if (msg.includes('end must be after')) return 'Slutdatumet måste vara efter startdatumet.'
|
||||
if (msg.includes('start must be the 1st')) return 'Startdatumet måste vara den 1:a i en månad.'
|
||||
if (msg.includes('end must be the last day')) return 'Slutdatumet måste vara sista dagen i en månad.'
|
||||
if (msg.includes('exceeds maximum 18 months')) return 'Räkenskapsåret får inte överstiga 18 månader (BFL 3 kap.).'
|
||||
return 'Ogiltigt räkenskapsår. Kontrollera datumen och försök igen.'
|
||||
}
|
||||
|
||||
export default function OnboardingPage() {
|
||||
return (
|
||||
<Suspense fallback={<div className="flex items-center justify-center h-64"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div>}>
|
||||
@@ -210,26 +219,33 @@ function OnboardingPageContent() {
|
||||
: `Räkenskapsår ${currentYear}/${currentYear + 1}`
|
||||
}
|
||||
|
||||
// Validate period duration (max 18 months)
|
||||
const startDate = new Date(startStr)
|
||||
const endDate = new Date(endStr)
|
||||
const months = (endDate.getFullYear() - startDate.getFullYear()) * 12 +
|
||||
(endDate.getMonth() - startDate.getMonth()) + 1
|
||||
if (months > 18) {
|
||||
console.error(`Period duration ${months} months exceeds 18-month maximum`)
|
||||
} else {
|
||||
await supabase.from('fiscal_periods').upsert({
|
||||
user_id: user.id,
|
||||
name: periodName,
|
||||
period_start: startStr,
|
||||
period_end: endStr,
|
||||
}, {
|
||||
onConflict: 'user_id,period_start,period_end',
|
||||
// Validate period duration
|
||||
const validationError = validatePeriodDuration(startStr, endStr)
|
||||
if (validationError) {
|
||||
toast({
|
||||
title: 'Ogiltigt räkenskapsår',
|
||||
description: translatePeriodError(validationError),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setCurrentStep(3)
|
||||
return
|
||||
}
|
||||
|
||||
await supabase.from('fiscal_periods').upsert({
|
||||
user_id: user.id,
|
||||
name: periodName,
|
||||
period_start: startStr,
|
||||
period_end: endStr,
|
||||
}, {
|
||||
onConflict: 'user_id,period_start,period_end',
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to create fiscal period:', err)
|
||||
toast({
|
||||
title: 'Kunde inte skapa räkenskapsår',
|
||||
description: 'Ett fel uppstod när räkenskapsåret skulle skapas. Försök igen.',
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateAccountSchema } from '@/lib/api/schemas'
|
||||
|
||||
export async function DELETE(
|
||||
request: Request,
|
||||
@@ -70,19 +72,13 @@ export async function PUT(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
// Build update object with only provided fields
|
||||
const updates: Record<string, unknown> = {}
|
||||
if (body.account_name !== undefined) updates.account_name = body.account_name
|
||||
if (body.is_active !== undefined) updates.is_active = body.is_active
|
||||
if (body.description !== undefined) updates.description = body.description
|
||||
if (body.default_vat_code !== undefined) updates.default_vat_code = body.default_vat_code
|
||||
if (body.sru_code !== undefined) updates.sru_code = body.sru_code
|
||||
const validation = await validateBody(request, UpdateAccountSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.update(updates)
|
||||
.update(body)
|
||||
.eq('user_id', user.id)
|
||||
.eq('account_number', number)
|
||||
.select()
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateAccountSchema } from '@/lib/api/schemas'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
@@ -47,7 +49,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const validation = await validateBody(request, CreateAccountSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { CreateFiscalPeriodInput } from '@/types'
|
||||
import { validatePeriodDuration } from '@/lib/bookkeeping/validate-period-duration'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateFiscalPeriodSchema } from '@/lib/api/schemas'
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
@@ -32,7 +33,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json() as CreateFiscalPeriodInput
|
||||
const validation = await validateBody(request, CreateFiscalPeriodSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// Validate period duration (max 18 months per BFL 3 kap.)
|
||||
const durationError = validatePeriodDuration(body.period_start, body.period_end)
|
||||
|
||||
@@ -57,7 +57,7 @@ describe('POST /api/bookkeeping/journal-entries/[id]/correct', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Lines are required')
|
||||
expect(body.error).toBe('Validation failed')
|
||||
})
|
||||
|
||||
it('returns 400 when lines array is empty', async () => {
|
||||
@@ -69,7 +69,7 @@ describe('POST /api/bookkeeping/journal-entries/[id]/correct', () => {
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toBe('Lines are required')
|
||||
expect(body.error).toBe('Validation failed')
|
||||
})
|
||||
|
||||
it('returns reversal and corrected entries on success', async () => {
|
||||
|
||||
@@ -2,7 +2,8 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { correctEntry } from '@/lib/core/bookkeeping/storno-service'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { CreateJournalEntryLineInput } from '@/types'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CorrectJournalEntrySchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -18,16 +19,9 @@ export async function POST(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
let body: { lines: CreateJournalEntryLineInput[] }
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!body.lines || !Array.isArray(body.lines) || body.lines.length === 0) {
|
||||
return NextResponse.json({ error: 'Lines are required' }, { status: 400 })
|
||||
}
|
||||
const validation = await validateBody(request, CorrectJournalEntrySchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
try {
|
||||
const result = await correctEntry(user.id, id, body.lines)
|
||||
|
||||
@@ -88,6 +88,8 @@ describe('GET /api/bookkeeping/journal-entries', () => {
|
||||
})
|
||||
})
|
||||
|
||||
const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000'
|
||||
|
||||
describe('POST /api/bookkeeping/journal-entries', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
@@ -116,7 +118,7 @@ describe('POST /api/bookkeeping/journal-entries', () => {
|
||||
mockCreateJournalEntry.mockResolvedValue(entry)
|
||||
|
||||
const input = {
|
||||
fiscal_period_id: 'period-1',
|
||||
fiscal_period_id: VALID_UUID,
|
||||
entry_date: '2024-06-15',
|
||||
description: 'Test entry',
|
||||
source_type: 'manual',
|
||||
@@ -144,11 +146,14 @@ describe('POST /api/bookkeeping/journal-entries', () => {
|
||||
const request = createMockRequest('/api/bookkeeping/journal-entries', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
fiscal_period_id: 'period-1',
|
||||
fiscal_period_id: VALID_UUID,
|
||||
entry_date: '2024-06-15',
|
||||
description: 'Bad entry',
|
||||
source_type: 'manual',
|
||||
lines: [{ account_number: '1930', debit_amount: 1000, credit_amount: 0 }],
|
||||
lines: [
|
||||
{ account_number: '1930', debit_amount: 1000, credit_amount: 0 },
|
||||
{ account_number: '3001', debit_amount: 0, credit_amount: 500 },
|
||||
],
|
||||
},
|
||||
})
|
||||
const response = await POST(request)
|
||||
|
||||
@@ -2,7 +2,8 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createJournalEntry } from '@/lib/bookkeeping/engine'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { CreateJournalEntryInput } from '@/types'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateJournalEntrySchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -63,7 +64,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json() as CreateJournalEntryInput
|
||||
const validation = await validateBody(request, CreateJournalEntrySchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
try {
|
||||
const entry = await createJournalEntry(user.id, body)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { evaluateMappingRules } from '@/lib/bookkeeping/mapping-engine'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { EvaluateMappingRulesSchema } from '@/lib/api/schemas'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
@@ -11,12 +13,14 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const validation = await validateBody(request, EvaluateMappingRulesSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// Accept either a transaction ID or raw transaction data
|
||||
let transaction: Transaction
|
||||
|
||||
if (body.transaction_id) {
|
||||
if ('transaction_id' in body) {
|
||||
const { data, error } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
@@ -30,7 +34,7 @@ export async function POST(request: Request) {
|
||||
|
||||
transaction = data as Transaction
|
||||
} else {
|
||||
transaction = body as Transaction
|
||||
transaction = body as unknown as Transaction
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateMappingRuleSchema } from '@/lib/api/schemas'
|
||||
|
||||
export async function GET() {
|
||||
const supabase = await createClient()
|
||||
@@ -31,7 +33,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const result = await validateBody(request, CreateMappingRuleSchema)
|
||||
if (!result.success) return result.response
|
||||
const body = result.data
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('mapping_rules')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { CreateCustomerInput } from '@/types'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { UpdateCustomerSchema } from '@/lib/api/schemas'
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
@@ -62,7 +63,9 @@ export async function PATCH(
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body: Partial<CreateCustomerInput> = await request.json()
|
||||
const result = await validateBody(request, UpdateCustomerSchema)
|
||||
if (!result.success) return result.response
|
||||
const body = result.data
|
||||
|
||||
const updateData: Record<string, unknown> = {}
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { CreateCustomerInput, Customer } from '@/types'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateCustomerSchema } from '@/lib/api/schemas'
|
||||
import type { Customer } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -37,7 +39,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body: CreateCustomerInput = await request.json()
|
||||
const result = await validateBody(request, CreateCustomerSchema)
|
||||
if (!result.success) return result.response
|
||||
const body = result.data
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('customers')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { CreateDeadlineInput } from '@/types'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateDeadlineSchema } from '@/lib/api/schemas'
|
||||
|
||||
/**
|
||||
* GET /api/deadlines
|
||||
@@ -78,12 +79,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body: CreateDeadlineInput = await request.json()
|
||||
|
||||
// Validate required fields
|
||||
if (!body.title || !body.due_date || !body.deadline_type) {
|
||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 })
|
||||
}
|
||||
const validation = await validateBody(request, CreateDeadlineSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// Insert the deadline
|
||||
const { data, error } = await supabase
|
||||
|
||||
@@ -4,6 +4,7 @@ import { loadExtensions } from '@/lib/extensions/loader'
|
||||
import {
|
||||
sendTaxDeadlineNotifications,
|
||||
sendInvoiceNotifications,
|
||||
sendMissingUnderlagNotifications,
|
||||
} from '@/extensions/general/push-notifications/notification-scheduler'
|
||||
|
||||
/**
|
||||
@@ -40,13 +41,14 @@ export async function GET(request: Request) {
|
||||
|
||||
try {
|
||||
// Send all notification types in parallel
|
||||
const [taxResult, invoiceResult] = await Promise.all([
|
||||
const [taxResult, invoiceResult, underlagResult] = await Promise.all([
|
||||
sendTaxDeadlineNotifications(supabase),
|
||||
sendInvoiceNotifications(supabase),
|
||||
sendMissingUnderlagNotifications(supabase),
|
||||
])
|
||||
|
||||
const totalSent = taxResult.sent + invoiceResult.sent
|
||||
const totalSkipped = taxResult.skipped + invoiceResult.skipped
|
||||
const totalSent = taxResult.sent + invoiceResult.sent + underlagResult.sent
|
||||
const totalSkipped = taxResult.skipped + invoiceResult.skipped + underlagResult.skipped
|
||||
|
||||
console.log(
|
||||
`Push notification cron completed: ${totalSent} sent, ${totalSkipped} skipped`
|
||||
@@ -57,6 +59,9 @@ export async function GET(request: Request) {
|
||||
console.log(
|
||||
` Invoice: ${invoiceResult.sent} sent, ${invoiceResult.skipped} skipped`
|
||||
)
|
||||
console.log(
|
||||
` Missing underlag: ${underlagResult.sent} sent, ${underlagResult.skipped} skipped`
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
@@ -65,6 +70,7 @@ export async function GET(request: Request) {
|
||||
details: {
|
||||
taxDeadlines: taxResult,
|
||||
invoices: invoiceResult,
|
||||
missingUnderlag: underlagResult,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
generateInvoiceEmailSubject
|
||||
} from '@/lib/email/invoice-templates'
|
||||
import { createInvoiceJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -166,6 +167,7 @@ export async function POST(
|
||||
|
||||
// Only create journal entries for real invoices (not proformas or delivery notes)
|
||||
const isRealInvoice = !invoice.document_type || invoice.document_type === 'invoice'
|
||||
let createdJournalEntryId: string | undefined
|
||||
if (isRealInvoice && ((company as Record<string, unknown>).accounting_method === 'accrual' || !(company as Record<string, unknown>).accounting_method)) {
|
||||
try {
|
||||
const journalEntry = await createInvoiceJournalEntry(
|
||||
@@ -174,6 +176,7 @@ export async function POST(
|
||||
(company as CompanySettings).entity_type
|
||||
)
|
||||
if (journalEntry) {
|
||||
createdJournalEntryId = journalEntry.id
|
||||
await supabase
|
||||
.from('invoices')
|
||||
.update({ journal_entry_id: journalEntry.id })
|
||||
@@ -185,6 +188,24 @@ export async function POST(
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-store invoice PDF as underlag and link to journal entry
|
||||
if (isRealInvoice) {
|
||||
try {
|
||||
const pdfArrayBuffer = new Uint8Array(pdfBuffer).buffer as ArrayBuffer
|
||||
await uploadDocument(user.id, {
|
||||
name: filename,
|
||||
buffer: pdfArrayBuffer,
|
||||
type: 'application/pdf',
|
||||
}, {
|
||||
upload_source: 'system',
|
||||
journal_entry_id: createdJournalEntryId,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Failed to store invoice PDF as underlag:', err)
|
||||
// Non-blocking — don't fail the send
|
||||
}
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'invoice.sent',
|
||||
payload: { invoice: invoice as Invoice, userId: user.id },
|
||||
|
||||
@@ -111,6 +111,9 @@ describe('GET /api/invoices', () => {
|
||||
})
|
||||
})
|
||||
|
||||
const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000'
|
||||
const VALID_UUID_2 = '550e8400-e29b-41d4-a716-446655440001'
|
||||
|
||||
describe('POST /api/invoices (create invoice)', () => {
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
@@ -126,7 +129,7 @@ describe('POST /api/invoices (create invoice)', () => {
|
||||
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: { customer_id: 'cust-1', items: [] },
|
||||
body: { customer_id: VALID_UUID, items: [] },
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse(response)
|
||||
@@ -141,7 +144,7 @@ describe('POST /api/invoices (create invoice)', () => {
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
customer_id: 'cust-999',
|
||||
customer_id: VALID_UUID_2,
|
||||
invoice_date: '2024-06-15',
|
||||
due_date: '2024-07-15',
|
||||
currency: 'SEK',
|
||||
@@ -156,7 +159,7 @@ describe('POST /api/invoices (create invoice)', () => {
|
||||
})
|
||||
|
||||
it('creates invoice with items and emits event', async () => {
|
||||
const customer = makeCustomer({ id: 'cust-1' })
|
||||
const customer = makeCustomer({ id: VALID_UUID })
|
||||
const createdInvoice = makeInvoice({ id: 'inv-1' })
|
||||
|
||||
mockGetVatRules.mockReturnValue({
|
||||
@@ -189,7 +192,7 @@ describe('POST /api/invoices (create invoice)', () => {
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
customer_id: 'cust-1',
|
||||
customer_id: VALID_UUID,
|
||||
invoice_date: '2024-06-15',
|
||||
due_date: '2024-07-15',
|
||||
currency: 'SEK',
|
||||
@@ -207,7 +210,7 @@ describe('POST /api/invoices (create invoice)', () => {
|
||||
})
|
||||
|
||||
it('rolls back invoice when items insertion fails', async () => {
|
||||
const customer = makeCustomer({ id: 'cust-1' })
|
||||
const customer = makeCustomer({ id: VALID_UUID })
|
||||
const createdInvoice = makeInvoice({ id: 'inv-1' })
|
||||
|
||||
mockGetVatRules.mockReturnValue({
|
||||
@@ -235,7 +238,7 @@ describe('POST /api/invoices (create invoice)', () => {
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
customer_id: 'cust-1',
|
||||
customer_id: VALID_UUID,
|
||||
invoice_date: '2024-06-15',
|
||||
due_date: '2024-07-15',
|
||||
currency: 'SEK',
|
||||
@@ -265,7 +268,7 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: { credited_invoice_id: 'inv-999' },
|
||||
body: { credited_invoice_id: VALID_UUID_2 },
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
@@ -275,12 +278,12 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
})
|
||||
|
||||
it('returns 400 when invoice is already credited', async () => {
|
||||
const original = makeInvoice({ id: 'inv-1', status: 'credited' })
|
||||
const original = makeInvoice({ id: VALID_UUID, status: 'credited' })
|
||||
enqueue({ data: original, error: null })
|
||||
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: { credited_invoice_id: 'inv-1' },
|
||||
body: { credited_invoice_id: VALID_UUID },
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
@@ -290,12 +293,12 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
})
|
||||
|
||||
it('returns 400 when invoice is in draft status', async () => {
|
||||
const original = makeInvoice({ id: 'inv-1', status: 'draft' })
|
||||
const original = makeInvoice({ id: VALID_UUID, status: 'draft' })
|
||||
enqueue({ data: original, error: null })
|
||||
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: { credited_invoice_id: 'inv-1' },
|
||||
body: { credited_invoice_id: VALID_UUID },
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
@@ -319,7 +322,7 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
},
|
||||
]
|
||||
const original = makeInvoice({
|
||||
id: 'inv-1',
|
||||
id: VALID_UUID,
|
||||
status: 'sent',
|
||||
subtotal: 10000,
|
||||
vat_amount: 2500,
|
||||
@@ -328,7 +331,7 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
})
|
||||
const creditNote = makeInvoice({
|
||||
id: 'cn-1',
|
||||
credited_invoice_id: 'inv-1',
|
||||
credited_invoice_id: VALID_UUID,
|
||||
subtotal: -10000,
|
||||
vat_amount: -2500,
|
||||
total: -12500,
|
||||
@@ -356,7 +359,7 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: { credited_invoice_id: 'inv-1' },
|
||||
body: { credited_invoice_id: VALID_UUID },
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown }>(response)
|
||||
@@ -370,7 +373,7 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
|
||||
it('rolls back credit note when items insertion fails', async () => {
|
||||
const original = makeInvoice({
|
||||
id: 'inv-1',
|
||||
id: VALID_UUID,
|
||||
status: 'sent',
|
||||
items: [
|
||||
{
|
||||
@@ -397,7 +400,7 @@ describe('POST /api/invoices (create credit note)', () => {
|
||||
|
||||
const request = createMockRequest('/api/invoices', {
|
||||
method: 'POST',
|
||||
body: { credited_invoice_id: 'inv-1' },
|
||||
body: { credited_invoice_id: VALID_UUID },
|
||||
})
|
||||
const response = await POST(request)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
+41
-15
@@ -2,7 +2,8 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { CreateInvoiceInput, EntityType, AccountingMethod, Invoice, CreditNote, InvoiceDocumentType } from '@/types'
|
||||
import { CreateInvoiceSchema, CreateCreditNoteSchema } from '@/lib/api/schemas'
|
||||
import type { EntityType, AccountingMethod, Invoice, CreditNote, InvoiceDocumentType } from '@/types'
|
||||
import { getVatRules, calculateVat, calculateTotal, getAvailableVatRates, getVatTreatmentForRate } from '@/lib/invoices/vat-rules'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import {
|
||||
@@ -11,11 +12,6 @@ import {
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface CreateCreditNoteInput {
|
||||
credited_invoice_id: string
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
@@ -59,15 +55,45 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
// Check if this is a credit note creation request
|
||||
if (body.credited_invoice_id) {
|
||||
return createCreditNote(supabase, user.id, body as CreateCreditNoteInput)
|
||||
let rawBody: unknown
|
||||
try {
|
||||
rawBody = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid JSON in request body', type: 'validation_error' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const invoiceInput = body as CreateInvoiceInput
|
||||
const documentType: InvoiceDocumentType = body.document_type || 'invoice'
|
||||
// Check if this is a credit note creation request
|
||||
if (typeof rawBody === 'object' && rawBody !== null && 'credited_invoice_id' in rawBody) {
|
||||
const parsed = CreateCreditNoteSchema.safeParse(rawBody)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Validation failed',
|
||||
type: 'validation_error',
|
||||
errors: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message, code: i.code })),
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
return createCreditNote(supabase, user.id, parsed.data)
|
||||
}
|
||||
|
||||
const parsed = CreateInvoiceSchema.safeParse(rawBody)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Validation failed',
|
||||
type: 'validation_error',
|
||||
errors: parsed.error.issues.map((i) => ({ field: i.path.join('.'), message: i.message, code: i.code })),
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
const invoiceInput = parsed.data
|
||||
const documentType: InvoiceDocumentType = invoiceInput.document_type || 'invoice'
|
||||
|
||||
// Get customer for VAT calculation
|
||||
const { data: customer, error: customerError } = await supabase
|
||||
@@ -225,7 +251,7 @@ export async function POST(request: Request) {
|
||||
async function createCreditNote(
|
||||
supabase: Awaited<ReturnType<typeof createClient>>,
|
||||
userId: string,
|
||||
input: CreateCreditNoteInput
|
||||
input: { credited_invoice_id: string; reason?: string }
|
||||
) {
|
||||
// Fetch the original invoice with items
|
||||
const { data: originalInvoice, error: originalError } = await supabase
|
||||
@@ -310,7 +336,7 @@ async function createCreditNote(
|
||||
unit: item.unit,
|
||||
unit_price: item.unit_price,
|
||||
line_total: -Math.abs(item.line_total),
|
||||
vat_rate: item.vat_rate ?? 25,
|
||||
vat_rate: item.vat_rate ?? 0,
|
||||
vat_amount: -(item.vat_amount ? Math.abs(item.vat_amount) : 0),
|
||||
}))
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { manualLink } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { BankLinkSchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -13,15 +15,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { transaction_id, journal_entry_id } = body
|
||||
|
||||
if (!transaction_id || !journal_entry_id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'transaction_id and journal_entry_id are required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const validation = await validateBody(request, BankLinkSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { transaction_id, journal_entry_id } = validation.data
|
||||
|
||||
const result = await manualLink(supabase, user.id, transaction_id, journal_entry_id)
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { runReconciliation } from '@/lib/reconciliation/bank-reconciliation'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { RunReconciliationSchema } from '@/lib/api/schemas'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
@@ -13,8 +15,9 @@ export async function POST(request: Request) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await request.json()
|
||||
const { date_from, date_to, dry_run } = body
|
||||
const validation = await validateBody(request, RunReconciliationSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const { date_from, date_to, dry_run } = validation.data
|
||||
|
||||
const result = await runReconciliation(supabase, user.id, {
|
||||
dateFrom: date_from,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user