Files
accounted/lib/invoices/__tests__/vat-rules.test.ts
T
MattssonandClaude Opus 4.7 a9b43ebeb7 Bug/vat selection warning (#583)
* refactor: update VAT handling logic for non-registered sellers and improve related comments

* chore: gate automated email flows behind 503 responses

Disables user-facing access to invoice payment reminders and salary
payslip email sending. Underlying lib code (reminder-processor,
PDF templates, notification_settings) is preserved for easy re-enable.

- Invoice reminders cron route returns 503; settings UI section removed.
- Payslip send route returns 503; original implementation kept as
  _sendPayslipsImpl for future re-enable.
- Push notifications were already extension-disabled, no change needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: remove Recapt feedback widget

Strips the third-party Recapt SDK and its floating feedback bubble from
the app. The in-app contact form keeps working via the existing email
channel (/api/support/contact). Drops the Recapt entries from the CSP
and the subprocessor list in the privacy policy.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: reject meaningless rättelser in correctEntry

Guard against zero-economic-effect corrections in the storno engine:
- Reject when proposed lines net to zero on every account (e.g. 1930
  debit 100 / 1930 credit 100), which would erase the original posting
  without representing any affärshändelse (BFL 5 kap. 5 §).
- Reject when proposed lines are an exact multiset match of the original
  entry — a rättelse must actually change something.

New MeaninglessCorrectionError wired through bookkeepingErrorResponse
(HTTP 400) and the Swedish error translator.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: add date-range picker to resultat- and balansrapport

Adds optional from/to date filtering to the four operational financial
reports (resultatrapport, balansrapport, income-statement, balance-sheet)
so users can view a month, quarter, or custom range inside a fiscal year
without leaving the report. Defaults to YTD; "Hela året" preserves the
prior full-period behaviour (URL-identical, cache-stable).

- trial-balance engine accepts optional fromDate/toDate, rolling prior
  in-period activity into IB and clamping period activity to the window
- 12 API routes accept and validate from_date/to_date query params
- ReportDateRange chip picker persists preset per company, only renders
  on the four relevant tabs
- FiscalYearSelector now emits the period object so the range picker
  has bounds without an extra fetch
- PDF/XLSX filenames reflect the chosen range
- Resultatrapport drops the prior-year column when narrowed (full-year
  vs partial-year would mislead)
- 11 new tests (engine + parser); all existing report tests pass

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: add support for marking journal entries as "no document required"

- Introduced a new sidecar table `journal_entry_no_doc_required` to track entries that do not require separate documentation (e.g., bank fees, interest).
- Implemented API routes for creating and deleting exemptions, including validation and authorization checks.
- Added a toggle component in the UI to allow users to mark entries as exempt, with an optional reason.
- Updated relevant tests to cover the new functionality, including RLS checks and cascading deletes.
- Enhanced existing schemas and types to accommodate the new `vat_amount` field for supplier invoice items.

* fix: address PR review findings on no-doc-required + VAT changes

- pg-real cascade test wraps DELETE in gnubok.allow_delete='true' txn so the
  immutability trigger bypass fires (mirrors delete_last_voucher RPC).
- Clamp supplier-invoice item vat_amount to <= line_total * vat_rate via Zod
  refinement (with 1-öre rounding tolerance) so the manual override can't
  inflate the 2641 debit beyond the statutory ceiling.
- groupVatByRate falls back to line_total * rate when stored vat_amount is 0
  with a positive rate, so legacy/import paths leaving the column at its
  NOT NULL DEFAULT 0 don't silently understate ruta 48.
- ReportDateRange todayIso() and preset endpoints use local date components
  instead of toISOString() (UTC) — fixes the midnight-to-02:00 off-by-one
  that truncated a day from YTD / this-month / this-quarter for Swedish
  users.
- NoDocRequiredToggle restores the previous reason on failed POST/DELETE so
  the rolled-back toggle state stays consistent with the rendered reason.
- Document the company-scoped (not user-scoped) DELETE authorization policy
  on the no-document-required route.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 01:56:09 +02:00

302 lines
9.8 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import {
getAvailableVatRates,
getVatTreatmentForRate,
getVatRules,
calculateVat,
calculateTotal,
formatVatRate,
getVatTreatmentLabel,
getVatSummaryFromItems,
getMomsRutaDescription,
} from '../vat-rules'
// ============================================================
// getAvailableVatRates
// ============================================================
describe('getAvailableVatRates', () => {
it('returns all 4 Swedish rates for individual customer', () => {
const rates = getAvailableVatRates('individual')
expect(rates).toHaveLength(4)
expect(rates.map((r) => r.rate)).toEqual([25, 12, 6, 0])
expect(rates.map((r) => r.treatment)).toEqual([
'standard_25',
'reduced_12',
'reduced_6',
'exempt',
])
})
it('returns all 4 Swedish rates for swedish_business', () => {
const rates = getAvailableVatRates('swedish_business')
expect(rates).toHaveLength(4)
expect(rates.map((r) => r.rate)).toEqual([25, 12, 6, 0])
})
it('returns only reverse_charge 0% for eu_business with validated VAT', () => {
const rates = getAvailableVatRates('eu_business', true)
expect(rates).toHaveLength(1)
expect(rates[0]).toEqual({
rate: 0,
label: '0% (omvänd skattskyldighet)',
treatment: 'reverse_charge',
})
})
it('returns all 4 rates for eu_business WITHOUT validated VAT', () => {
// ML compliance: must charge Swedish VAT when VAT number not validated
const rates = getAvailableVatRates('eu_business', false)
expect(rates).toHaveLength(4)
expect(rates.map((r) => r.rate)).toEqual([25, 12, 6, 0])
})
it('returns only export 0% for non_eu_business', () => {
const rates = getAvailableVatRates('non_eu_business')
expect(rates).toHaveLength(1)
expect(rates[0]).toEqual({
rate: 0,
label: '0% (export)',
treatment: 'export',
})
})
it('defaults vatNumberValidated to false', () => {
// eu_business without explicit vatNumberValidated should get all rates
const rates = getAvailableVatRates('eu_business')
expect(rates).toHaveLength(4)
})
it('does not gate on seller VAT-registration status', () => {
// ML 16 kap. 23 § (faktureringsmoms): the picker offers the full
// customer-type-based rate set regardless of whether the seller is
// momsregistrerad. The invoice form surfaces a warning at submit time
// when a non-registered seller picks a non-zero rate.
const rates = getAvailableVatRates('swedish_business')
expect(rates).toHaveLength(4)
expect(rates.map((r) => r.rate)).toEqual([25, 12, 6, 0])
})
})
// ============================================================
// getVatTreatmentForRate
// ============================================================
describe('getVatTreatmentForRate', () => {
it('maps 25 → standard_25', () => {
expect(getVatTreatmentForRate(25)).toBe('standard_25')
})
it('maps 12 → reduced_12', () => {
expect(getVatTreatmentForRate(12)).toBe('reduced_12')
})
it('maps 6 → reduced_6', () => {
expect(getVatTreatmentForRate(6)).toBe('reduced_6')
})
it('maps 0 → exempt', () => {
expect(getVatTreatmentForRate(0)).toBe('exempt')
})
it('defaults unknown rates to standard_25', () => {
expect(getVatTreatmentForRate(15)).toBe('standard_25')
expect(getVatTreatmentForRate(99)).toBe('standard_25')
})
})
// ============================================================
// getVatRules
// ============================================================
describe('getVatRules', () => {
it('returns standard_25 / rate 25 / ruta 05 for individual', () => {
const rules = getVatRules('individual')
expect(rules).toEqual({
treatment: 'standard_25',
rate: 25,
momsRuta: '05',
})
})
it('returns standard_25 / rate 25 / ruta 05 for swedish_business', () => {
const rules = getVatRules('swedish_business')
expect(rules).toEqual({
treatment: 'standard_25',
rate: 25,
momsRuta: '05',
})
})
it('returns reverse_charge / rate 0 / ruta 39 for eu_business with validated VAT', () => {
const rules = getVatRules('eu_business', true)
expect(rules.treatment).toBe('reverse_charge')
expect(rules.rate).toBe(0)
expect(rules.momsRuta).toBe('39')
// Verify text references Article 196 of Council Directive 2006/112/EC
expect(rules.reverseChargeText).toContain('Article 196')
expect(rules.reverseChargeText).toContain('2006/112/EC')
})
it('returns standard_25 / rate 25 / ruta 05 for eu_business WITHOUT validated VAT', () => {
const rules = getVatRules('eu_business', false)
expect(rules).toEqual({
treatment: 'standard_25',
rate: 25,
momsRuta: '05',
})
})
it('returns export / rate 0 / ruta 40 for non_eu_business', () => {
const rules = getVatRules('non_eu_business')
expect(rules.treatment).toBe('export')
expect(rules.rate).toBe(0)
expect(rules.momsRuta).toBe('40')
// Verify text references ML 10 kap
expect(rules.reverseChargeText).toContain('ML 10 kap')
})
it('defaults to standard_25 for unknown customerType', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rules = getVatRules('unknown_type' as any)
expect(rules).toEqual({
treatment: 'standard_25',
rate: 25,
momsRuta: '05',
})
})
it('does not gate on seller VAT-registration status', () => {
// ML 16 kap. 23 § (faktureringsmoms): a non-registered seller who states
// VAT still owes it. The rule output reflects the customer-type rate so
// the booking is consistent with what the buyer sees on the invoice.
const rules = getVatRules('swedish_business')
expect(rules.rate).toBe(25)
expect(rules.treatment).toBe('standard_25')
expect(rules.momsRuta).toBe('05')
})
})
// ============================================================
// calculateVat
// Pin: vatRate is a whole number (25, not 0.25).
// Formula: Math.round(subtotal * vatRate) / 100
// ============================================================
describe('calculateVat', () => {
it('calculates 25% of 10000 → 2500', () => {
expect(calculateVat(10000, 25)).toBe(2500)
})
it('calculates 12% of 5000 → 600', () => {
expect(calculateVat(5000, 12)).toBe(600)
})
it('calculates 6% of 3000 → 180', () => {
expect(calculateVat(3000, 6)).toBe(180)
})
it('calculates 0% of 10000 → 0', () => {
expect(calculateVat(10000, 0)).toBe(0)
})
it('rounds correctly: 99.99 at 25% → 25', () => {
// Math.round(99.99 * 25) / 100 = Math.round(2499.75) / 100 = 2500 / 100 = 25
expect(calculateVat(99.99, 25)).toBe(25)
})
})
// ============================================================
// calculateTotal
// ============================================================
describe('calculateTotal', () => {
it('returns subtotal + VAT rounded: 10000 at 25% → 12500', () => {
expect(calculateTotal(10000, 25)).toBe(12500)
})
it('handles 0% VAT: total equals subtotal', () => {
expect(calculateTotal(5000, 0)).toBe(5000)
})
})
// ============================================================
// formatVatRate
// ============================================================
describe('formatVatRate', () => {
it('formats 25 as "25%"', () => {
expect(formatVatRate(25)).toBe('25%')
})
it('formats 0 as "0%"', () => {
expect(formatVatRate(0)).toBe('0%')
})
})
// ============================================================
// getVatTreatmentLabel
// ============================================================
describe('getVatTreatmentLabel', () => {
it('returns correct Swedish label for each treatment', () => {
expect(getVatTreatmentLabel('standard_25')).toBe('25% moms')
expect(getVatTreatmentLabel('reduced_12')).toBe('12% moms')
expect(getVatTreatmentLabel('reduced_6')).toBe('6% moms')
expect(getVatTreatmentLabel('reverse_charge')).toBe('Omvänd skattskyldighet (0%)')
expect(getVatTreatmentLabel('export')).toBe('Export (0%)')
expect(getVatTreatmentLabel('exempt')).toBe('Momsfritt')
})
})
// ============================================================
// getVatSummaryFromItems
// ============================================================
describe('getVatSummaryFromItems', () => {
it('returns single rate info when all items have same rate', () => {
const result = getVatSummaryFromItems([{ vat_rate: 25 }, { vat_rate: 25 }])
expect(result.isMixed).toBe(false)
expect(result.rate).toBe(25)
expect(result.treatment).toBe('standard_25')
expect(result.label).toBe('25% moms')
})
it('returns isMixed=true when items have different rates', () => {
const result = getVatSummaryFromItems([{ vat_rate: 25 }, { vat_rate: 12 }])
expect(result.isMixed).toBe(true)
expect(result.rate).toBeNull()
expect(result.treatment).toBeNull()
expect(result.label).toBe('Blandade momssatser')
})
it('treats null vat_rate as 0', () => {
const result = getVatSummaryFromItems([{ vat_rate: null }, { vat_rate: null }])
expect(result.isMixed).toBe(false)
expect(result.rate).toBe(0)
expect(result.treatment).toBe('exempt')
})
})
// ============================================================
// getMomsRutaDescription
// ============================================================
describe('getMomsRutaDescription', () => {
it('maps ruta 05 → "Utgående moms 25%"', () => {
expect(getMomsRutaDescription('05')).toBe('Utgående moms 25%')
})
it('maps ruta 39 → "Försäljning av tjänster till annat EU-land"', () => {
expect(getMomsRutaDescription('39')).toBe('Försäljning av tjänster till annat EU-land')
})
it('maps ruta 40 → "Export utanför EU"', () => {
expect(getMomsRutaDescription('40')).toBe('Export utanför EU')
})
it('returns the ruta string itself for unknown rutor', () => {
expect(getMomsRutaDescription('99')).toBe('99')
})
})