* feat(mileage): körjournal with milersättning booking, MCP tools and CSV export New mileage_trips table (RLS, booked-delete trigger per BFL retention), lib/mileage service reusing the payroll schablon rates, /api/mileage routes (trips CRUD, period booking to 7331, salary-run push, körjournal CSV), Körjournal dashboard page + nav, and three staged MCP tools (search-only catalog). Trips book as one verifikat per period via the engine; salary path inserts mileage_taxfree line items. mileage_trips classified in the full-archive export. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * refactor(mileage): use shared roundOre helper per tightened ratchet baseline Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mileage): pending_operations op-type migration + Swedish review findings - New migration pair adds log_mileage_trip/book_mileage_period to the pending_operations operation_type CHECK (pg-real audit). - bookMileagePeriod refuses a period spanning several employees and names the employee in the verifikationstext when scoped (BFL motpart). - vehicle_registration required for förmånsbil trips (schema, service, MCP staging, UI surfaces the field). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mileage): claim-first booking, CSV injection guard and driver column - bookMileagePeriod claims trips (draft to booked CAS) before creating the verifikat, so a concurrent second booking loses the race instead of double-booking; claim reverts if verifikat creation fails. - Körjournal CSV neutralizes formula-injection triggers (OWASP) and adds a Förare column naming the employee per trip. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mileage): resolve CodeRabbit + Swedish review round: race, drift and hardening - Copying a round trip no longer re-doubles the stored distance. - pushMileageToSalaryRun claims trips before inserting line items (retry can no longer double-pay); CLAIM_LOST replaces misleading NO_TRIPS on lost races. - Booked trips are DB-immutable via a BEFORE UPDATE trigger (new migration 20260807113215): only claim/link/revert transitions and notes edits pass. - Cross-year periods rejected (schablon rates are per calendar year); payroll config year read from the date string, not TZ-dependent getFullYear(). - MCP staged bookings freeze the previewed trip set (trip_ids in params) and the commit fails on drift; validation errors return 400, not 500. - PATCH enforces the förmånsbil regnr rule on the effective row; export validates dates before they reach the Content-Disposition header; employee_id is verified company-scoped on trip creation; stale orphaned claims released. - UI: fetch flags reset in finally; ICU plural for draft summary; distance stored at the column's 1-decimal precision. - Tests: [id] route suite, pushMileageToSalaryRun suite, claim-race, drift, cross-year and update-trigger pg cases. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mileage): revert-to-draft must clear salary_run_id at the trigger level New migration 20260807114924 replaces the booked-immutability function: a booked -> draft revert now rejects rows keeping salary_run_id, closing the DB-level double-pay path CodeRabbit flagged. pg test pins both directions; the CLAIM_LOST unit test now asserts the revert. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(mileage): company-scope employee_id on PATCH (Superagent P2) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(mileage): valid v4 uuid in cross-company employee PATCH test Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
132 lines
3.8 KiB
TypeScript
132 lines
3.8 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
import { NextResponse } from 'next/server'
|
|
|
|
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
|
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: vi.fn() }))
|
|
vi.mock('@/lib/company/context', () => ({
|
|
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
}))
|
|
vi.mock('@/lib/auth/require-write', () => ({
|
|
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
|
}))
|
|
vi.mock('@/lib/mileage/mileage-service', () => ({
|
|
listTrips: vi.fn(),
|
|
createTrip: vi.fn(),
|
|
}))
|
|
|
|
import { GET, POST } from '../route'
|
|
import { requireAuth } from '@/lib/auth/require-auth'
|
|
import { createTrip, listTrips } from '@/lib/mileage/mileage-service'
|
|
|
|
const params = { params: Promise.resolve({}) } as never
|
|
|
|
function authed() {
|
|
vi.mocked(requireAuth).mockResolvedValue({
|
|
user: { id: 'user-1' } as never,
|
|
supabase: {} as never,
|
|
error: null,
|
|
} as never)
|
|
}
|
|
|
|
function unauthed() {
|
|
vi.mocked(requireAuth).mockResolvedValue({
|
|
user: null,
|
|
supabase: null,
|
|
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
|
} as never)
|
|
}
|
|
|
|
const VALID_TRIP = {
|
|
trip_date: '2026-05-10',
|
|
distance_km: 32,
|
|
from_location: 'Kontoret',
|
|
to_location: 'Kunden',
|
|
purpose: 'Kundbesök',
|
|
}
|
|
|
|
function postReq(body: unknown) {
|
|
return new Request('https://x.test/api/mileage/trips', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
})
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
})
|
|
|
|
describe('GET /api/mileage/trips', () => {
|
|
it('returns 401 when unauthenticated', async () => {
|
|
unauthed()
|
|
const res = await GET(new Request('https://x.test/api/mileage/trips'), params)
|
|
expect(res.status).toBe(401)
|
|
})
|
|
|
|
it('returns the trip list and forwards filters', async () => {
|
|
authed()
|
|
vi.mocked(listTrips).mockResolvedValue([{ id: 't1' }] as never)
|
|
const res = await GET(
|
|
new Request('https://x.test/api/mileage/trips?from=2026-05-01&to=2026-05-31&status=draft'),
|
|
params
|
|
)
|
|
expect(res.status).toBe(200)
|
|
const body = await res.json()
|
|
expect(body.data).toHaveLength(1)
|
|
expect(vi.mocked(listTrips).mock.calls[0][2]).toMatchObject({
|
|
from: '2026-05-01',
|
|
to: '2026-05-31',
|
|
status: 'draft',
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('POST /api/mileage/trips', () => {
|
|
it('returns 401 when unauthenticated', async () => {
|
|
unauthed()
|
|
const res = await POST(postReq(VALID_TRIP), params)
|
|
expect(res.status).toBe(401)
|
|
})
|
|
|
|
it('returns 400 on invalid body (missing purpose, negative km)', async () => {
|
|
authed()
|
|
const res = await POST(
|
|
postReq({ trip_date: '2026-05-10', distance_km: -5, from_location: 'A', to_location: 'B' }),
|
|
params
|
|
)
|
|
expect(res.status).toBe(400)
|
|
expect(createTrip).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('rejects a förmånsbil trip without vehicle_registration', async () => {
|
|
authed()
|
|
const res = await POST(
|
|
postReq({ ...VALID_TRIP, vehicle_type: 'company_car_fossil' }),
|
|
params
|
|
)
|
|
expect(res.status).toBe(400)
|
|
expect(createTrip).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('rejects odometer_end <= odometer_start', async () => {
|
|
authed()
|
|
const res = await POST(
|
|
postReq({ ...VALID_TRIP, odometer_start: 1032, odometer_end: 1000 }),
|
|
params
|
|
)
|
|
expect(res.status).toBe(400)
|
|
})
|
|
|
|
it('creates the trip and returns 201', async () => {
|
|
authed()
|
|
vi.mocked(createTrip).mockResolvedValue({ id: 't1', status: 'draft' } as never)
|
|
const res = await POST(postReq(VALID_TRIP), params)
|
|
expect(res.status).toBe(201)
|
|
const body = await res.json()
|
|
expect(body.data.id).toBe('t1')
|
|
expect(vi.mocked(createTrip).mock.calls[0][1]).toBe('company-1')
|
|
expect(vi.mocked(createTrip).mock.calls[0][2]).toBe('user-1')
|
|
})
|
|
})
|