chore: repo-wide bloat sweep, remove dead code and fold duplicate helpers (#2150)
* chore: repo-wide bloat sweep, remove dead code and fold duplicate helpers Remove 33 dead files, ~270 unreferenced exports/types, 13 dead i18n namespaces and 4 unused dependencies; fold byte-identical helper copies into one canonical home each (lib/utils chunk/sleep/utcDateStamp, lib/dates/iso, lib/invariants/uuid, lib/xml/escape, lib/reports/sru/format, lib/pdf/number-text, lib/browser/panel-request, lib/api/v1/body + v1ValidationError rolled out to ~55 v1 routes, booking-template schemas). No behaviour change: v1 bodies and status codes, MCP tool schemas, DB writes and money math are untouched. Naive ore rounding was deliberately not swapped for roundOre; see DECISIONS.md 2026-09-02 for the full list of things left alone on purpose. tsc, lint, 19588 unit tests and check:guards green; antipattern baseline ratcheted (naive-ore-round 622 -> 620, hand-rolled-invariant 115 -> 113). Co-Authored-By: Claude Fable 5.1 <[email protected]> * test(transactions): import RawTransaction from @/types after the ingest re-export removal CI's type ratchet (check:types, full tsconfig) caught the one test file that still imported the type through lib/transactions/ingest. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Jakob Wennberg <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.1
Jakob Wennberg
parent
18cbc4c30a
commit
f266c386f3
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { UUID_RE } from '@/lib/invariants/uuid'
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
import dynamic from 'next/dynamic'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
@@ -44,7 +45,6 @@ interface NextVoucher {
|
||||
series: string
|
||||
}
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
export default function BookkeepingPage() {
|
||||
const { toast } = useToast()
|
||||
|
||||
@@ -58,7 +58,7 @@ import { decodeFileContent } from '@/lib/import/shared/encoding'
|
||||
import type { BankFileParseResult, BankFileFormatId, BankFileDuplicateInfo, GenericCSVColumnMapping } from '@/lib/import/bank-file/types'
|
||||
import type { SkattekontoFileParseResult } from '@/lib/import/skattekonto-file/types'
|
||||
import type { SkattekontoFileImportResult } from '@/components/import/SkattekontoFileResultStep'
|
||||
import type { IngestResult } from '@/lib/transactions/ingest'
|
||||
import type { IngestResult } from '@/types'
|
||||
import type {
|
||||
ImportWizardStep,
|
||||
ParsedSIEFile,
|
||||
|
||||
@@ -22,15 +22,11 @@ import { useCompany, useCapability } from '@/contexts/CompanyContext'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { getCreditNoteSendMode } from '@/lib/invoices/credit-note-send-mode'
|
||||
import { creditConfirmNumber } from '@/lib/invoices/display'
|
||||
import type { Invoice, InvoiceItem, Customer } from '@/types'
|
||||
import type { InvoiceItem } from '@/types'
|
||||
import type { InvoiceWithRelations } from '@/components/invoices/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { InvoiceEditorSkeleton } from '@/components/common/DetailPageSkeleton'
|
||||
|
||||
interface InvoiceWithRelations extends Invoice {
|
||||
customer: Customer
|
||||
items: InvoiceItem[]
|
||||
}
|
||||
|
||||
export default function CreateCreditNotePage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { isSandbox } = useCompany()
|
||||
|
||||
@@ -80,7 +80,8 @@ import {
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import type { Invoice, InvoiceItem, Customer, InvoiceStatus, InvoiceReminder, InvoiceDocumentType } from '@/types'
|
||||
import type { Invoice, InvoiceItem, InvoiceStatus, InvoiceReminder, InvoiceDocumentType } from '@/types'
|
||||
import type { InvoiceWithRelations } from '@/components/invoices/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { useBranding } from '@/lib/branding/brand-context'
|
||||
import { DetailPageSkeleton } from '@/components/common/DetailPageSkeleton'
|
||||
@@ -136,15 +137,6 @@ function daysOverdue(dueDateStr: string): number {
|
||||
return Math.round((today.getTime() - dueDate.getTime()) / (1000 * 60 * 60 * 24))
|
||||
}
|
||||
|
||||
interface InvoiceWithRelations extends Invoice {
|
||||
customer: Customer
|
||||
items: InvoiceItem[]
|
||||
// Optional reference to the issuance verifikation. Populated by the
|
||||
// backend when the invoice flow auto-books an entry on send; absent on
|
||||
// older invoices and on companies where issuance is not auto-booked.
|
||||
journal_entry_id?: string | null
|
||||
}
|
||||
|
||||
export default function InvoiceDetailPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { canWrite } = useCanWrite()
|
||||
const { company, isSandbox } = useCompany()
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
CheckCircle2,
|
||||
Loader2,
|
||||
} from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatAmount, formatDate } from '@/lib/utils'
|
||||
import { downloadFile } from '@/lib/browser/download-file'
|
||||
import { failureDescription } from '@/lib/browser/action-failure'
|
||||
import type { KassaflodesanalysReport } from '@/lib/reports/kassaflodesanalys'
|
||||
@@ -32,13 +32,6 @@ import {
|
||||
type ErrorLocale,
|
||||
} from '@/lib/errors/get-error-message'
|
||||
|
||||
function formatAmount(n: number): string {
|
||||
return n.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})
|
||||
}
|
||||
|
||||
interface CashRowProps {
|
||||
label: string
|
||||
amount: number
|
||||
|
||||
@@ -13,17 +13,13 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { ArrowLeft, Lock } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { formatAmount, formatDate } from '@/lib/utils'
|
||||
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'
|
||||
import { DetailPageSkeleton } from '@/components/common/DetailPageSkeleton'
|
||||
|
||||
function formatAmount(amount: number): string {
|
||||
return amount.toLocaleString('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||
}
|
||||
|
||||
// Supplier invoices carry their own currency; "kr" is only correct for SEK.
|
||||
function amountWithCurrency(amount: number, currency?: string | null): string {
|
||||
return `${formatAmount(amount)} ${!currency || currency === 'SEK' ? 'kr' : currency}`
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import { UUID_RE } from '@/lib/invariants/uuid'
|
||||
import { useState, useEffect, useMemo, useRef, useCallback } from 'react'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import dynamic from 'next/dynamic'
|
||||
@@ -145,7 +146,6 @@ const PERIOD_FILTER_STORAGE_PREFIX = 'Accounted:transactions-fy-scope:v1:'
|
||||
// string in the underlag-badge effect below. They come from journal_entries.id
|
||||
// (DB-sourced), but this guard keeps the interpolated list UUID-only, matching
|
||||
// /api/documents/counts.
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
// A skattekonto row qualifies for bulk booking when the outcome is fully
|
||||
// deterministic: a rule matched (booking_suggestion), it is not a likely
|
||||
@@ -381,8 +381,6 @@ export default function TransactionsPage() {
|
||||
// voucher (salary, Fortnox import, manual entry) with no new bokföring.
|
||||
const [matchVoucherTx, setMatchVoucherTx] = useState<TransactionWithInvoice | null>(null)
|
||||
const [bulkBookOpen, setBulkBookOpen] = useState(false)
|
||||
const [isMatchingSupplierFromPicker, setIsMatchingSupplierFromPicker] = useState(false)
|
||||
const [isMatchingFromPicker, setIsMatchingFromPicker] = useState(false)
|
||||
|
||||
// Quick review dialog (suggestion review before booking)
|
||||
const [quickReviewOpen, setQuickReviewOpen] = useState(false)
|
||||
@@ -2394,46 +2392,6 @@ export default function TransactionsPage() {
|
||||
}
|
||||
}, [refreshTransactions, t, toast])
|
||||
|
||||
async function handleMatchInvoice(transactionId: string, invoiceId: string): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`/api/transactions/${transactionId}/match-invoice`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ invoice_id: invoiceId }),
|
||||
})
|
||||
const result = await response.json()
|
||||
if (!response.ok) {
|
||||
toast({ title: 'Fakturamatchning misslyckades', description: getErrorMessage(result, { context: 'transaction' }), variant: 'destructive' })
|
||||
return false
|
||||
}
|
||||
|
||||
const transaction = transactions.find((t) => t.id === transactionId)
|
||||
const invoiceNumber = transaction?.potential_invoice?.invoice_number || ''
|
||||
|
||||
setTransactions((prev) =>
|
||||
prev.map((t) =>
|
||||
t.id === transactionId
|
||||
? {
|
||||
...t,
|
||||
invoice_id: invoiceId,
|
||||
potential_invoice_id: null,
|
||||
potential_invoice: undefined,
|
||||
is_business: true,
|
||||
category: 'income_services' as TransactionCategory,
|
||||
journal_entry_id: result.journal_entry_id,
|
||||
}
|
||||
: t
|
||||
)
|
||||
)
|
||||
|
||||
toast({ title: 'Faktura matchad', description: `Faktura ${invoiceNumber} markerad som betald` })
|
||||
return true
|
||||
} catch {
|
||||
toast({ title: t('match_failed_title'), description: t('match_failed_with_invoice'), variant: 'destructive' })
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function handleSelectInvoiceFromPicker(invoice: Invoice & { customer?: Customer }) {
|
||||
if (!invoicePickerTransaction) return
|
||||
// Don't POST directly from the picker. Route through the confirm dialog
|
||||
@@ -4264,7 +4222,6 @@ export default function TransactionsPage() {
|
||||
{invoicePickerOpen && <Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (isMatchingFromPicker) return
|
||||
setInvoicePickerOpen(open)
|
||||
if (!open) setInvoicePickerTransaction(null)
|
||||
}}
|
||||
@@ -4284,7 +4241,6 @@ export default function TransactionsPage() {
|
||||
<InvoicePicker
|
||||
transaction={invoicePickerTransaction}
|
||||
onSelect={handleSelectInvoiceFromPicker}
|
||||
isProcessing={isMatchingFromPicker}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
@@ -4294,7 +4250,6 @@ export default function TransactionsPage() {
|
||||
{supplierInvoicePickerOpen && <Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (isMatchingSupplierFromPicker) return
|
||||
setSupplierInvoicePickerOpen(open)
|
||||
if (!open) setSupplierInvoicePickerTransaction(null)
|
||||
}}
|
||||
@@ -4314,7 +4269,6 @@ export default function TransactionsPage() {
|
||||
<SupplierInvoicePicker
|
||||
transaction={supplierInvoicePickerTransaction}
|
||||
onSelect={handleSelectSupplierInvoiceFromPicker}
|
||||
isProcessing={isMatchingSupplierFromPicker}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
|
||||
import { NextResponse } from 'next/server'
|
||||
import { skills } from '@/extensions/general/mcp-server/skills'
|
||||
import { workflowSkills as skills } from '@/extensions/general/mcp-server/skills'
|
||||
import { API_V1_VERSION } from '@/lib/api/v1/version'
|
||||
import { withPublicSecurityHeaders } from '@/lib/api/v1/security-headers'
|
||||
import { getCanonicalBaseUrl } from '@/lib/api/v1/base-url'
|
||||
|
||||
+6
-12
@@ -4,6 +4,8 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { markSignatureSigned } from '@/lib/bokslut/arsredovisning/signature-service'
|
||||
import { getSwedishLocalDate } from '@/lib/bookkeeping/engine'
|
||||
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
|
||||
// PATCH transitions: pending → signed (manual entry for the paper / outside-
|
||||
@@ -34,19 +36,11 @@ const PatchSchema = z.discriminatedUnion('status', [
|
||||
z.object({ status: z.literal('declined') }).strict(),
|
||||
])
|
||||
|
||||
function stockholmDate(instant: string | Date): string {
|
||||
return new Intl.DateTimeFormat('sv-SE', {
|
||||
timeZone: 'Europe/Stockholm',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
}).format(typeof instant === 'string' ? new Date(instant) : instant)
|
||||
}
|
||||
|
||||
function isSignatureDateAllowed(signedAt: string, finalizedAt: string): boolean {
|
||||
const signedDate = stockholmDate(signedAt)
|
||||
const finalizedDate = stockholmDate(finalizedAt)
|
||||
const today = stockholmDate(new Date())
|
||||
const signedDate = getSwedishLocalDate(new Date(signedAt))
|
||||
const finalizedDate = getSwedishLocalDate(new Date(finalizedAt))
|
||||
const today = getSwedishLocalDate()
|
||||
|
||||
return signedDate >= finalizedDate && signedDate <= today
|
||||
}
|
||||
|
||||
|
||||
@@ -4,24 +4,13 @@ import { generateCalendarFeed } from '@/lib/calendar/ics-generator'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { Deadline, Invoice } from '@/types'
|
||||
import { createTokenRateLimiter } from '@/lib/api/token-rate-limit'
|
||||
import { UUID_RE } from '@/lib/invariants/uuid'
|
||||
|
||||
const log = createLogger('api/calendar/feed-token')
|
||||
|
||||
// In-memory rate limiting: token -> { count, resetAt }
|
||||
const rateLimitMap = new Map<string, { count: number; resetAt: number }>()
|
||||
const RATE_LIMIT_WINDOW_MS = 60_000 // 1 minute
|
||||
const RATE_LIMIT_MAX = 60 // 60 requests per minute per token
|
||||
|
||||
// Periodic cleanup to prevent memory leaks (every 5 minutes)
|
||||
let lastCleanup = Date.now()
|
||||
function cleanupRateLimitMap() {
|
||||
const now = Date.now()
|
||||
if (now - lastCleanup < 5 * 60_000) return
|
||||
lastCleanup = now
|
||||
for (const [key, value] of rateLimitMap) {
|
||||
if (now > value.resetAt) rateLimitMap.delete(key)
|
||||
}
|
||||
}
|
||||
// 60 requests per minute per token, process-local.
|
||||
const rateLimiter = createTokenRateLimiter({ max: 60, windowMs: 60_000 })
|
||||
|
||||
/**
|
||||
* GET /api/calendar/feed/[token]
|
||||
@@ -35,22 +24,13 @@ export async function GET(
|
||||
const { token } = await params
|
||||
|
||||
// Validate token format (UUID)
|
||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
if (!uuidRegex.test(token)) {
|
||||
if (!UUID_RE.test(token)) {
|
||||
return new NextResponse('Invalid token', { status: 400 })
|
||||
}
|
||||
|
||||
// Rate limiting per token
|
||||
cleanupRateLimitMap()
|
||||
const nowMs = Date.now()
|
||||
const rateEntry = rateLimitMap.get(token)
|
||||
if (rateEntry && nowMs < rateEntry.resetAt) {
|
||||
if (rateEntry.count >= RATE_LIMIT_MAX) {
|
||||
return new NextResponse('Too many requests', { status: 429 })
|
||||
}
|
||||
rateEntry.count++
|
||||
} else {
|
||||
rateLimitMap.set(token, { count: 1, resetAt: nowMs + RATE_LIMIT_WINDOW_MS })
|
||||
if (!rateLimiter.allow(token)) {
|
||||
return new NextResponse('Too many requests', { status: 429 })
|
||||
}
|
||||
|
||||
// Create service client (no user auth required)
|
||||
|
||||
@@ -6,8 +6,9 @@ import { listForCompany } from '@/lib/cash-accounts/service'
|
||||
* GET /api/cash-accounts
|
||||
*
|
||||
* Returns the active company's cash accounts (cash_accounts table). Used by the
|
||||
* reconciliation CashAccountSelector (Item 5) and any other surface that needs
|
||||
* the canonical list of routable cash accounts. UI panels that just display PSD2
|
||||
* reconciliation surfaces (via useCashAccounts) and any other surface that needs
|
||||
* the canonical list of routable cash accounts.
|
||||
UI panels that just display PSD2
|
||||
* connection state may still read bank_connections.accounts_data until that
|
||||
* column is dropped in a follow-up migration.
|
||||
*
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { privateNoStore } from '@/lib/api/private-no-store'
|
||||
import { utcDateStamp } from '@/lib/utils'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import {
|
||||
estimateArchiveSize,
|
||||
@@ -19,11 +21,6 @@ interface ResetArchiveRow {
|
||||
created_at: string
|
||||
}
|
||||
|
||||
function privateNoStore(response: NextResponse): NextResponse {
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/company/[id]/migration-reset/archive
|
||||
*
|
||||
@@ -159,7 +156,7 @@ export const GET = withRouteContext<Params>(
|
||||
const zipBuffer = await generateBaseDataArchive(archiveClient, reset.source_company_id, {
|
||||
include_documents: includeDocuments,
|
||||
})
|
||||
const filename = `migration_reset_archive_${formatDateStamp(new Date())}.zip`
|
||||
const filename = `migration_reset_archive_${utcDateStamp(new Date())}.zip`
|
||||
|
||||
log.info('migration reset source archive generated', {
|
||||
userId: user.id,
|
||||
@@ -190,10 +187,3 @@ export const GET = withRouteContext<Params>(
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
function formatDateStamp(date: Date): string {
|
||||
const year = date.getUTCFullYear()
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, '0')
|
||||
const day = String(date.getUTCDate()).padStart(2, '0')
|
||||
return `${year}${month}${day}`
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { privateNoStore } from '@/lib/api/private-no-store'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CompanyMigrationResetSchema } from '@/lib/api/schemas'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
@@ -30,11 +31,6 @@ function rpcFailure(
|
||||
})
|
||||
}
|
||||
|
||||
function privateNoStore(response: NextResponse): NextResponse {
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/company/[id]/migration-reset
|
||||
*
|
||||
|
||||
@@ -27,14 +27,7 @@
|
||||
* the nonce is blocked on this response.
|
||||
*/
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
import { escapeHtml } from '@/lib/email/user-text'
|
||||
|
||||
/**
|
||||
* Opening chunk: full document head, styles, spinner and heading, plus a
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { UUID_RE } from '@/lib/invariants/uuid'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
@@ -71,7 +72,7 @@ export async function POST(request: Request) {
|
||||
// the DB (the column is typed uuid and would error opaquely).
|
||||
const isUuid =
|
||||
state !== null &&
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(state)
|
||||
UUID_RE.test(state)
|
||||
if (!isUuid || !consumerKey || !consumerSecret) {
|
||||
return NextResponse.json({ error: 'Missing parameters' }, { status: 400 })
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { normalizeNameKey as nameKey } from '@/lib/import/shared/column-utils'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { eventBus } from '@/lib/events'
|
||||
@@ -20,11 +21,6 @@ interface ExistingArticle {
|
||||
article_number: string | null
|
||||
}
|
||||
|
||||
function nameKey(value: string | null): string | null {
|
||||
if (!value) return null
|
||||
return value.trim().toLowerCase() || null
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/import/articles/execute
|
||||
*
|
||||
|
||||
@@ -10,16 +10,11 @@ import type {
|
||||
DetectedArticleColumns,
|
||||
} from '@/lib/import/articles/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { normalizeNameKey as nameKey } from '@/lib/import/shared/column-utils'
|
||||
|
||||
const ALLOWED_EXTENSIONS = ['.xlsx', '.xls', '.csv', '.ods']
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
|
||||
|
||||
/** Lowercased dedup key for matching an article by name. */
|
||||
function nameKey(value: string | null): string | null {
|
||||
if (!value) return null
|
||||
return value.trim().toLowerCase() || null
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/import/articles/parse
|
||||
*
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { ingestTransactions, type RawTransaction } from '@/lib/transactions/ingest'
|
||||
import { ingestTransactions } from '@/lib/transactions/ingest'
|
||||
import type { RawTransaction } from '@/types'
|
||||
import { generateExternalId } from '@/lib/import/bank-file/parser'
|
||||
import type { IngestOptions } from '@/types'
|
||||
import { getCompanyRole } from '@/lib/auth/require-write'
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { PRIVATE_NO_STORE_HEADERS, privateNoStore } from '@/lib/api/private-no-store'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { invoicePdfFilename, paymentConfirmationPdfFilename } from '@/lib/invoices/pdf-filename'
|
||||
@@ -14,8 +15,6 @@ import {
|
||||
invoiceRequiresPaymentAccount,
|
||||
} from '@/lib/invoices/payment-accounts'
|
||||
|
||||
const PRIVATE_NO_STORE_HEADERS = { 'Cache-Control': 'private, no-store' }
|
||||
|
||||
/**
|
||||
* `?disposition=inline` serves the PDF for in-browser review instead of forcing
|
||||
* a download (#1190): reviewing an invoice should not mean opening a file from
|
||||
@@ -38,11 +37,6 @@ function resolveVariant(request: Request): 'invoice' | 'paid' {
|
||||
return requested === 'paid' ? 'paid' : 'invoice'
|
||||
}
|
||||
|
||||
function privateNoStore(response: NextResponse): NextResponse {
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}
|
||||
|
||||
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'invoice.pdf',
|
||||
async (request, { supabase, companyId, log, requestId }, { params }) => {
|
||||
|
||||
@@ -6,8 +6,7 @@ import { roundOre } from '@/lib/money'
|
||||
import { resolvePeriodStatusForDate } from '@/lib/core/bookkeeping/period-service'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import type { Currency, Invoice } from '@/types'
|
||||
|
||||
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
import { UUID_RE } from '@/lib/invariants/uuid'
|
||||
|
||||
/**
|
||||
* POST /api/invoices/[id]/refresh-exchange-rate
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { PRIVATE_NO_STORE_HEADERS, privateNoStore } from '@/lib/api/private-no-store'
|
||||
import { InvoicePDF, type InvoicePdfInvoice } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getVatRules } from '@/lib/invoices/vat-rules'
|
||||
@@ -18,13 +19,6 @@ import {
|
||||
invoiceRequiresPaymentAccount,
|
||||
} from '@/lib/invoices/payment-accounts'
|
||||
|
||||
const PRIVATE_NO_STORE_HEADERS = { 'Cache-Control': 'private, no-store' }
|
||||
|
||||
function privateNoStore(response: NextResponse): NextResponse {
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}
|
||||
|
||||
/** The per-line ROT/RUT fields the editor posts alongside the amounts. */
|
||||
interface PreviewItemInput {
|
||||
description: string
|
||||
|
||||
@@ -5,21 +5,10 @@ import { resolvePayslipToken, isValidPayslipTokenFormat } from '@/lib/salary/pay
|
||||
import { buildPayslipData, payslipFileName } from '@/lib/salary/payslips/build-payslip-data'
|
||||
import { PayslipPDF } from '@/lib/salary/pdf/payslip-template'
|
||||
import { contentDisposition } from '@/lib/api/content-disposition'
|
||||
import { createTokenRateLimiter } from '@/lib/api/token-rate-limit'
|
||||
|
||||
// In-memory rate limiting per token (pattern from /api/calendar/feed).
|
||||
const rateLimitMap = new Map<string, { count: number; resetAt: number }>()
|
||||
const RATE_LIMIT_WINDOW_MS = 60_000
|
||||
const RATE_LIMIT_MAX = 20
|
||||
|
||||
let lastCleanup = Date.now()
|
||||
function cleanupRateLimitMap() {
|
||||
const now = Date.now()
|
||||
if (now - lastCleanup < 5 * 60_000) return
|
||||
lastCleanup = now
|
||||
for (const [key, value] of rateLimitMap) {
|
||||
if (now > value.resetAt) rateLimitMap.delete(key)
|
||||
}
|
||||
}
|
||||
// 20 requests per minute per token, process-local (same limiter as /api/calendar/feed).
|
||||
const rateLimiter = createTokenRateLimiter({ max: 20, windowMs: 60_000 })
|
||||
|
||||
/**
|
||||
* GET /api/payslip/[token]/pdf
|
||||
@@ -39,16 +28,8 @@ export async function GET(
|
||||
return new NextResponse('Invalid token', { status: 400 })
|
||||
}
|
||||
|
||||
cleanupRateLimitMap()
|
||||
const nowMs = Date.now()
|
||||
const rateEntry = rateLimitMap.get(token)
|
||||
if (rateEntry && nowMs < rateEntry.resetAt) {
|
||||
if (rateEntry.count >= RATE_LIMIT_MAX) {
|
||||
return new NextResponse('Too many requests', { status: 429 })
|
||||
}
|
||||
rateEntry.count++
|
||||
} else {
|
||||
rateLimitMap.set(token, { count: 1, resetAt: nowMs + RATE_LIMIT_WINDOW_MS })
|
||||
if (!rateLimiter.allow(token)) {
|
||||
return new NextResponse('Too many requests', { status: 429 })
|
||||
}
|
||||
|
||||
const serviceClient = createServiceClientNoCookies()
|
||||
|
||||
@@ -2,31 +2,19 @@ import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { AccountKeySchema } from '@/lib/reconciliation/schemas'
|
||||
import {
|
||||
AccountKeySchema,
|
||||
reconciliationLinksBodyFields,
|
||||
reconciliationLinksBodyRefinement,
|
||||
} from '@/lib/reconciliation/schemas'
|
||||
import { matchPairs } from '@/lib/reconciliation/actions'
|
||||
|
||||
const PairSchema = z.object({
|
||||
external_ids: z.array(z.string().uuid()).min(1).max(50),
|
||||
journal_entry_ids: z.array(z.string().uuid()).min(1).max(50),
|
||||
// Bank 1:N only: the signed slice per verifikat (transaction sign
|
||||
// convention). Omitted: each slice defaults to the voucher's bank line.
|
||||
allocations: z
|
||||
.array(z.object({ journal_entry_id: z.string().uuid(), amount: z.number() }))
|
||||
.min(2)
|
||||
.max(50)
|
||||
.optional(),
|
||||
})
|
||||
|
||||
const ReconciliationLinksBodySchema = z
|
||||
.object({
|
||||
pairs: z.array(PairSchema).max(200).optional(),
|
||||
use_proposals: z.boolean().optional(),
|
||||
confidence_threshold: z.number().min(0).max(1).optional(),
|
||||
...reconciliationLinksBodyFields,
|
||||
dry_run: z.boolean().optional(),
|
||||
})
|
||||
.refine((b) => (b.pairs && b.pairs.length > 0) || b.use_proposals === true, {
|
||||
message: 'Ange pairs eller use_proposals: true.',
|
||||
})
|
||||
.refine(...reconciliationLinksBodyRefinement)
|
||||
|
||||
/**
|
||||
* POST /api/reconciliation/accounts/{accountKey}/links
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
dateColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
parseCellDate,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
@@ -35,12 +36,6 @@ interface InvoiceRow {
|
||||
currency: string
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
export const GET = withRouteContext('report.ar_ledger.xlsx', async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const asOfDate = searchParams.get('as_of_date') || undefined
|
||||
@@ -70,8 +65,8 @@ export const GET = withRouteContext('report.ar_ledger.xlsx', async (request, { s
|
||||
invoiceRows.push({
|
||||
customer_name: e.customer_name,
|
||||
invoice_number: inv.invoice_number,
|
||||
invoice_date: toDate(inv.invoice_date) ?? inv.invoice_date,
|
||||
due_date: toDate(inv.due_date) ?? inv.due_date,
|
||||
invoice_date: parseCellDate(inv.invoice_date) ?? inv.invoice_date,
|
||||
due_date: parseCellDate(inv.due_date) ?? inv.due_date,
|
||||
total: inv.total,
|
||||
paid_amount: inv.paid_amount,
|
||||
outstanding: inv.outstanding,
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
type ArchiveScope,
|
||||
} from '@/lib/reports/full-archive-export'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { PRIVATE_NO_STORE_HEADERS, privateNoStore } from '@/lib/api/private-no-store'
|
||||
import { utcDateStamp } from '@/lib/utils'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
@@ -13,12 +15,6 @@ export const runtime = 'nodejs'
|
||||
export const maxDuration = 300
|
||||
|
||||
const SIZE_LIMIT_BYTES = 80 * 1024 * 1024
|
||||
const PRIVATE_NO_STORE_HEADERS = { 'Cache-Control': 'private, no-store' }
|
||||
|
||||
function privateNoStore(response: NextResponse): NextResponse {
|
||||
response.headers.set('Cache-Control', 'private, no-store')
|
||||
return response
|
||||
}
|
||||
|
||||
export const GET = withRouteContext('report.full_archive', async (request, ctx) => {
|
||||
const { supabase, companyId, user, log, requestId } = ctx
|
||||
@@ -138,7 +134,7 @@ export const GET = withRouteContext('report.full_archive', async (request, ctx)
|
||||
const filename =
|
||||
scope === 'period'
|
||||
? `arkiv_${periodId}.zip`
|
||||
: `arkiv_full_${companyId}_${formatDateStamp(new Date())}.zip`
|
||||
: `arkiv_full_${companyId}_${utcDateStamp(new Date())}.zip`
|
||||
|
||||
log.info('full archive generated', {
|
||||
userId: user.id,
|
||||
@@ -172,10 +168,3 @@ export const GET = withRouteContext('report.full_archive', async (request, ctx)
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
function formatDateStamp(d: Date): string {
|
||||
const y = d.getUTCFullYear()
|
||||
const m = String(d.getUTCMonth() + 1).padStart(2, '0')
|
||||
const day = String(d.getUTCDate()).padStart(2, '0')
|
||||
return `${y}${m}${day}`
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
xlsxFilename,
|
||||
parseCellDate,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
@@ -24,13 +25,6 @@ interface FlatRow {
|
||||
balance: number
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | string {
|
||||
// Preserve original ISO string in the cell if parsing fails (avoids NaN
|
||||
// dates polluting the workbook).
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? s : d
|
||||
}
|
||||
|
||||
export const GET = withRouteContext('report.general_ledger.xlsx', async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
@@ -96,7 +90,9 @@ export const GET = withRouteContext('report.general_ledger.xlsx', async (request
|
||||
rows.push({
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
date: toDate(line.date),
|
||||
// Preserve the original ISO string in the cell if parsing fails (avoids
|
||||
// NaN dates polluting the workbook).
|
||||
date: parseCellDate(line.date) ?? line.date,
|
||||
voucher: `${line.voucher_series}${line.voucher_number}`,
|
||||
description: line.description,
|
||||
source_type: line.source_type,
|
||||
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
parseCellDate,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
interface FlatRow {
|
||||
@@ -22,11 +24,6 @@ interface FlatRow {
|
||||
credit: number
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
export const GET = withRouteContext('report.journal_register.xlsx', async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
@@ -53,7 +50,8 @@ export const GET = withRouteContext('report.journal_register.xlsx', async (reque
|
||||
for (const line of entry.lines) {
|
||||
rows.push({
|
||||
voucher: voucherLabel,
|
||||
date: toDate(entry.date),
|
||||
date: parseCellDate(entry.date),
|
||||
|
||||
description: entry.description,
|
||||
source_type: entry.source_type,
|
||||
status: entry.status,
|
||||
|
||||
@@ -8,15 +8,10 @@ import {
|
||||
dateColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
parseCellDate,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
export const GET = withRouteContext('report.salary_journal.xlsx', async (request, { supabase, companyId }) => {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const year = parseInt(searchParams.get('year') || new Date().getFullYear().toString())
|
||||
@@ -62,7 +57,7 @@ export const GET = withRouteContext('report.salary_journal.xlsx', async (request
|
||||
r.employmentType,
|
||||
r.periodYear,
|
||||
r.periodMonth,
|
||||
toDate(r.paymentDate),
|
||||
parseCellDate(r.paymentDate),
|
||||
r.grossSalary,
|
||||
r.taxWithheld,
|
||||
r.netSalary,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user