* feat(salary): recurring payroll lines per employee (#2042) A standing per-employee payslip row derived into every salary run inside its validity window, e.g. a benefit-bike bruttolöneavdrag of -670 kr/month. Mirrors the employee_benefits pattern end to end: - employee_recurring_lines table with RLS, audit + updated_at triggers, and a salary_line_items.source_recurring_line_id back-link; amount sign and account format enforced by CHECKs - run-calculation step 8d3 derives rows with flags computed from the item type (gross deductions reduce tax + AGA bases, net deductions post-tax); derived rows are excluded from the manual-line set like benefit rows - CRUD routes under /api/salary/employees/[id]/recurring-lines with the same 401/403/404/400 contract as the benefits routes - EmployeeRecurringLinesPanel on the employee page, sv/en strings - registered in the BFL full-archive export Closes #2042 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): address #2044 review: feed recurring rows to the engine, guard deletes - Derived recurring rows are now appended to the calculateSalary lineItems set: they were inserted into salary_line_items but excluded from the in-memory calculation, so a recurring deduction never affected the payslip math (CodeRabbit, major). - DELETE deactivates a line that has derived rows instead of hard-deleting: ON DELETE SET NULL would turn a draft run's derived row into an apparent manual row that recalculation keeps forever; deactivation preserves the provenance link and lets the next recalculation drop the draft rows (CodeRabbit, major). The panel hides inactive lines. - POST employee lookup uses maybeSingle and answers 500 on lookup failure, 404 only on zero rows. - Panel: try/finally releases loading/submitting on network failure, and a request sequence guard stops a stale load from overwriting a newer list. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): move employee_recurring_lines off 20260830140000, which upstream now occupies Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): bind employee_id to company_id with a composite FK (review) The dimensions pattern: UNIQUE (id, company_id) on employees plus a composite FK, so RLS company scoping cannot be sidestepped by pointing a recurring line at another company's employee (IDOR, CWE-639). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): address review: deductions only, race-free delete, engine and pg tests Review round on #2044: - Blocker: recurring 'other' additions removed from the whitelist, the migration CHECK and the panel. calculateSalary only treats ADDITION_TYPES as additions, so a recurring taxable addition rendered on the payslip without entering gross, tax, AGA or AGI. Re-add only together with engine support (recorded in DECISIONS.md). - Delete race: salary_line_items.source_recurring_line_id is now NO ACTION instead of SET NULL; the DELETE route deletes first and falls back to deactivation on 23503, so a deletion racing a concurrent derivation can never orphan a derived row into an apparent manual row. NO ACTION defers to statement end, so company-deletion cascades are unaffected. - Correction runs copy source_benefit_id / source_recurring_line_id, so recalculating a correction no longer derives the copied rows a second time (pre-existing for benefits, now pinned). - Engine tests: gross_deduction_other through calculateSalary asserts gross, taxable income and avgifterBasis drop while the semester base stays; net_deduction_union only moves the paid-out net. - pg-real tests for the new table: RLS membership, composite FK cross-company refusal, deduction-only CHECKs, and the NO ACTION back-link blocking deletes of derived-into lines. - Nice-to-haves: POST rounds the stored amount to ore, the redundant single-column employees FK is dropped (composite carries the cascade), the schemas.ts comment references the real migration version, and the panel explains the validity-window semantics (payment date, bounds inclusive, no proration). - Rebased onto main; the phantom-columns ceiling re-measured at 395 on the merged tree. - DECISIONS.md records the vacation-basis judgment call (semester base not reduced by recurring gross deductions). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(salary): gate recurring-line writes on the writer role, 404 unmatched deletes Two findings from the 2026-09-02 review round: - Superagent P1: the write policies were membership-only, so a read-only viewer could write recurring payroll deductions straight through PostgREST, bypassing the route's requireWrite. The table now carries aa_enforce_company_writer_role, the same gate 20260902093000 attaches to every company-scoped table (it also fires inside SECURITY DEFINER bodies, where RLS does not apply). The migration is re-versioned to 20260902140000 so the function exists when a fresh database replays the folder in order. - CodeRabbit: a filtered DELETE reports no error when nothing matches, so an unknown or cross-company line answered 200 deleted: true. The delete now selects the removed row and answers 404 when it is null. Tests: pg-real asserts a viewer is refused insert, update and delete with 42501 while the row survives unchanged, plus a non-member case; the route tests pin the 404. 896 salary tests green, rebased on main. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * test(salary): pin the recurring-line payload column sets Answers the phantom-column ceiling finding with scoped assertions rather than a bare ceiling raise: the PATCH route test now asserts the exact writable column set, and the comment records that the pg-real test covers the derived-row shape against the real table. Making the PATCH payload a literal would turn a partial update into last-write-wins, which is why the shape stays unresolved. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(salary): round recurring line amounts with roundOre check:guards naive-ore-round ratchet: the derived recurring row used Math.round(x * 100) / 100 (baseline 615, +1); roundOre is already imported in run-calculation.ts. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(migrations): guard the employees unique-key add against #2145 merge order #2145 (expense claims) also adds employees_id_company_id_key. Wrap this migration's ADD CONSTRAINT in an idempotent DO block so whichever of the two PRs merges second does not fail on a duplicate constraint. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
50b6299699
commit
4eb1626129
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Auth-wiring tests for /api/salary/employees/[id]/recurring-lines/[lineId]
|
||||
* (PATCH update, DELETE remove). Runs the routes through the real
|
||||
* withRouteContext wrapper; mocks auth/company/write and injects a queued
|
||||
* Supabase mock via requireAuth.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset, findCall } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { PATCH, DELETE } from '../route'
|
||||
|
||||
const params = { params: Promise.resolve({ id: 'emp-1', lineId: 'line-1' }) } as never
|
||||
|
||||
function patch(body: unknown) {
|
||||
return createMockRequest('/api/salary/employees/emp-1/recurring-lines/line-1', {
|
||||
method: 'PATCH',
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
const storedLine = {
|
||||
item_type: 'gross_deduction_other',
|
||||
valid_from: '2026-01-01',
|
||||
valid_to: null,
|
||||
}
|
||||
|
||||
describe('PATCH /api/salary/employees/[id]/recurring-lines/[lineId]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await PATCH(patch({ amount: -700 }), params)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer (no write permission)', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const response = await PATCH(patch({ amount: -700 }), params)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('updates the amount (happy path)', async () => {
|
||||
enqueue({ data: storedLine }) // fetch existing
|
||||
enqueue({ data: { id: 'line-1', amount: -700 } }) // update
|
||||
|
||||
const response = await PATCH(patch({ amount: -700 }), params)
|
||||
const { status, body } = await parseJsonResponse<{ data: { amount: number } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.amount).toBe(-700)
|
||||
})
|
||||
|
||||
it('writes exactly the patchable columns and nothing else', async () => {
|
||||
// Scoped assertion for the merged-updates payload: it is assembled
|
||||
// conditionally, so the phantom-column scanner cannot resolve it. This
|
||||
// pins the column set the route can ever write.
|
||||
enqueue({ data: storedLine }) // fetch existing
|
||||
enqueue({ data: { id: 'line-1' } }) // update
|
||||
|
||||
await PATCH(
|
||||
patch({
|
||||
description: 'Förmånscykel',
|
||||
amount: -700,
|
||||
account_number: '7399',
|
||||
valid_from: '2026-02-01',
|
||||
valid_to: '2026-12-31',
|
||||
metadata: { source: 'test' },
|
||||
is_active: false,
|
||||
}),
|
||||
params,
|
||||
)
|
||||
|
||||
const update = findCall('employee_recurring_lines', 'update')
|
||||
expect(Object.keys(update?.[0] as Record<string, unknown>).sort()).toEqual([
|
||||
'account_number',
|
||||
'amount',
|
||||
'description',
|
||||
'is_active',
|
||||
'metadata',
|
||||
'valid_from',
|
||||
'valid_to',
|
||||
])
|
||||
})
|
||||
|
||||
it('returns 404 when the line does not exist', async () => {
|
||||
enqueue({ data: null, error: { code: 'PGRST116', message: 'zero rows' } })
|
||||
|
||||
const response = await PATCH(patch({ amount: -700 }), params)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('rejects an amount whose sign contradicts the stored item_type', async () => {
|
||||
enqueue({ data: storedLine }) // fetch existing: a gross deduction
|
||||
|
||||
const response = await PATCH(patch({ amount: 700 }), params)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects a merged period where the patched valid_to lands before the stored valid_from', async () => {
|
||||
enqueue({ data: { ...storedLine, valid_from: '2026-06-01' } })
|
||||
|
||||
const response = await PATCH(patch({ valid_to: '2026-05-31' }), params)
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Gäller till')
|
||||
})
|
||||
|
||||
it('maps a check_violation on the write to 400, not 404', async () => {
|
||||
enqueue({ data: storedLine })
|
||||
enqueue({ data: null, error: { code: '23514', message: 'violates check constraint' } })
|
||||
|
||||
const response = await PATCH(patch({ valid_from: '2026-02-01' }), params)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('reports a transport failure on the fetch as 500, not 404', async () => {
|
||||
enqueue({ data: null, error: { code: '08006', message: 'connection failure' } })
|
||||
|
||||
const response = await PATCH(patch({ amount: -700 }), params)
|
||||
expect(response.status).toBe(500)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/salary/employees/[id]/recurring-lines/[lineId]', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/salary/employees/emp-1/recurring-lines/line-1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
const response = await DELETE(request, params)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('hard-deletes a line that has never been derived into a run', async () => {
|
||||
enqueue({ data: { id: 'line-1' } }) // delete returns the removed row
|
||||
|
||||
const request = createMockRequest('/api/salary/employees/emp-1/recurring-lines/line-1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
const response = await DELETE(request, params)
|
||||
const { status, body } = await parseJsonResponse<{ data: { deleted: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.deleted).toBe(true)
|
||||
})
|
||||
|
||||
it('returns 404 when the delete matches no row', async () => {
|
||||
// Unknown id, or a line belonging to another company: the filtered
|
||||
// delete reports no error and no row.
|
||||
enqueue({ data: null })
|
||||
|
||||
const request = createMockRequest('/api/salary/employees/emp-1/recurring-lines/nope', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
const response = await DELETE(request, {
|
||||
params: Promise.resolve({ id: 'emp-1', lineId: 'nope' }),
|
||||
} as never)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('deactivates instead of deleting when derived rows reference the line', async () => {
|
||||
// The FK is NO ACTION: the delete itself fails with 23503 and the route
|
||||
// falls back to deactivation, race-free by construction.
|
||||
enqueue({ error: { code: '23503', message: 'violates foreign key constraint' } })
|
||||
enqueue({ data: null }) // is_active=false update resolves
|
||||
|
||||
const request = createMockRequest('/api/salary/employees/emp-1/recurring-lines/line-1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
const response = await DELETE(request, params)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { deleted: boolean; deactivated?: boolean }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.deleted).toBe(false)
|
||||
expect(body.data.deactivated).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,164 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import {
|
||||
UpdateEmployeeRecurringLineSchema,
|
||||
RECURRING_LINE_PERIOD_ORDER_MESSAGE,
|
||||
} from '@/lib/api/schemas'
|
||||
import {
|
||||
validateRecurringLineAmount,
|
||||
type RecurringLineItemType,
|
||||
} from '@/lib/salary/recurring-lines'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export const PATCH = withRouteContext<{ params: Promise<{ id: string; lineId: string }> }>(
|
||||
'salary.employees.recurring_lines.update',
|
||||
async (request, { supabase, companyId }, { params }) => {
|
||||
const { id, lineId } = await params
|
||||
|
||||
const validation = await validateBody(request, UpdateEmployeeRecurringLineSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const { data: existing, error: fetchError } = await supabase
|
||||
.from('employee_recurring_lines')
|
||||
.select('item_type, valid_from, valid_to')
|
||||
.eq('id', lineId)
|
||||
.eq('employee_id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
// Only zero rows (PGRST116) means the line really isn't there. A
|
||||
// transport/DB failure is not a missing record and must not be reported as
|
||||
// one.
|
||||
if (fetchError && fetchError.code !== 'PGRST116') {
|
||||
return NextResponse.json({ error: getUserErrorMessage(fetchError) }, { status: 500 })
|
||||
}
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: 'Raden hittades inte' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Amount sign against the stored item_type: the partial schema cannot
|
||||
// check this because item_type is not patchable and never in the body.
|
||||
if (body.amount !== undefined) {
|
||||
const signError = validateRecurringLineAmount(
|
||||
existing.item_type as RecurringLineItemType,
|
||||
body.amount,
|
||||
)
|
||||
if (signError) {
|
||||
return NextResponse.json({ error: signError }, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
// Validity period against the MERGED state: the partial schema can only
|
||||
// compare the two dates when the body carries both; when only one is
|
||||
// patched, the other half lives on the row we just fetched. Inclusive
|
||||
// bound, and a null/cleared valid_to stays legal.
|
||||
const mergedValidFrom = (body.valid_from ?? existing.valid_from ?? null) as string | null
|
||||
const mergedValidTo = (
|
||||
body.valid_to !== undefined ? body.valid_to : existing.valid_to ?? null
|
||||
) as string | null
|
||||
if (mergedValidFrom !== null && mergedValidTo !== null && mergedValidTo < mergedValidFrom) {
|
||||
return NextResponse.json({ error: RECURRING_LINE_PERIOD_ORDER_MESSAGE }, { status: 400 })
|
||||
}
|
||||
|
||||
// Explicit literal keys (not a body spread) so the phantom-column
|
||||
// scanner can verify every column this update can touch.
|
||||
const updates: Record<string, unknown> = {}
|
||||
if (body.description !== undefined) updates.description = body.description
|
||||
if (body.amount !== undefined) updates.amount = body.amount
|
||||
if (body.account_number !== undefined) updates.account_number = body.account_number
|
||||
if (body.valid_from !== undefined) updates.valid_from = body.valid_from
|
||||
if (body.valid_to !== undefined) updates.valid_to = body.valid_to
|
||||
if (body.metadata !== undefined) updates.metadata = body.metadata
|
||||
if (body.is_active !== undefined) updates.is_active = body.is_active
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('employee_recurring_lines')
|
||||
.update(updates)
|
||||
.eq('id', lineId)
|
||||
.eq('employee_id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
// The row's existence was already established above, so `error` here is
|
||||
// a write failure, not a lookup miss. PGRST116 (zero rows) is the only
|
||||
// shape that still means not-found: the row was deleted or moved out of
|
||||
// the company between fetch and update.
|
||||
if (error.code === 'PGRST116') {
|
||||
return NextResponse.json({ error: 'Raden hittades inte' }, { status: 404 })
|
||||
}
|
||||
// Both the amount sign and the merged period were validated above, so a
|
||||
// check_violation on UPDATE is a concurrent write that moved the other
|
||||
// half of a constraint after our check. The period is the plausible one;
|
||||
// answer 400 with the same copy the schema uses.
|
||||
if (error.code === '23514') {
|
||||
return NextResponse.json({ error: RECURRING_LINE_PERIOD_ORDER_MESSAGE }, { status: 400 })
|
||||
}
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
return NextResponse.json({ error: 'Raden hittades inte' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
export const DELETE = withRouteContext<{ params: Promise<{ id: string; lineId: string }> }>(
|
||||
'salary.employees.recurring_lines.delete',
|
||||
async (_request, { supabase, companyId }, { params }) => {
|
||||
const { id, lineId } = await params
|
||||
|
||||
// Delete-first, no pre-check: the FK from salary_line_items is NO
|
||||
// ACTION, so the database itself refuses (23503) whenever any derived
|
||||
// row references the line, including one inserted by a calculation
|
||||
// racing this request. A referenced line is deactivated instead: the
|
||||
// provenance link stays intact, the next recalculation drops draft
|
||||
// derived rows and never re-derives.
|
||||
// Selecting the deleted row separates "deleted" from "matched nothing":
|
||||
// a filtered DELETE reports no error when the id is unknown or belongs to
|
||||
// another company, which would otherwise answer 200 deleted: true.
|
||||
const { data: deleted, error } = await supabase
|
||||
.from('employee_recurring_lines')
|
||||
.delete()
|
||||
.eq('id', lineId)
|
||||
.eq('employee_id', id)
|
||||
.eq('company_id', companyId)
|
||||
.select('id')
|
||||
.maybeSingle()
|
||||
|
||||
if (error && error.code !== '23503') {
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
}
|
||||
|
||||
if (error) {
|
||||
const { error: deactivateError } = await supabase
|
||||
.from('employee_recurring_lines')
|
||||
.update({ is_active: false })
|
||||
.eq('id', lineId)
|
||||
.eq('employee_id', id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (deactivateError) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(deactivateError) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { id: lineId, deleted: false, deactivated: true } })
|
||||
}
|
||||
|
||||
if (!deleted) {
|
||||
return NextResponse.json({ error: 'Raden hittades inte' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { id: lineId, deleted: true } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Auth-wiring tests for /api/salary/employees/[id]/recurring-lines (POST
|
||||
* create). Runs the route through the real withRouteContext wrapper; mocks
|
||||
* auth/company/write and injects a queued Supabase mock via requireAuth.
|
||||
* Covers 401, 403 (viewer), the POST happy path, and the schema mirrors of
|
||||
* the table CHECKs (amount sign, validity period).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const params = { params: Promise.resolve({ id: 'emp-1' }) } as never
|
||||
|
||||
function post(body: unknown) {
|
||||
return createMockRequest('/api/salary/employees/emp-1/recurring-lines', { method: 'POST', body })
|
||||
}
|
||||
|
||||
const validLine = {
|
||||
item_type: 'gross_deduction_other',
|
||||
description: 'Förmånscykel bruttolöneavdrag',
|
||||
amount: -670.17,
|
||||
valid_from: '2026-01-01',
|
||||
}
|
||||
|
||||
describe('POST /api/salary/employees/[id]/recurring-lines', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a viewer (no write permission)', async () => {
|
||||
requireWriteMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
||||
})
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('creates a recurring line (happy path)', async () => {
|
||||
enqueue({ data: { id: 'emp-1' } }) // employee ownership check
|
||||
enqueue({ data: { id: 'line-1', item_type: 'gross_deduction_other', amount: -670.17 } }) // insert
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(response)
|
||||
|
||||
expect(status).toBe(201)
|
||||
expect(body.data.id).toBe('line-1')
|
||||
})
|
||||
|
||||
it('returns 404 when the employee is not in the company', async () => {
|
||||
enqueue({ data: null }) // employee ownership check → zero rows, no error
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('reports an employee-lookup failure as 500, not 404', async () => {
|
||||
enqueue({ data: null, error: { code: '08006', message: 'connection failure' } })
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
expect(response.status).toBe(500)
|
||||
})
|
||||
|
||||
// Amount sign: mirrors the employee_recurring_lines_amount_sign CHECK.
|
||||
describe('amount sign', () => {
|
||||
it('rejects a positive amount on a deduction type with a field-level 400', async () => {
|
||||
const response = await POST(post({ ...validLine, amount: 670.17 }), params)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
errors: { field: string }[]
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.errors).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ field: 'amount' })]),
|
||||
)
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("rejects the removed 'other' addition type", async () => {
|
||||
const response = await POST(
|
||||
post({ ...validLine, item_type: 'other', amount: 500 }),
|
||||
params,
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects zero for every item type', async () => {
|
||||
const response = await POST(post({ ...validLine, amount: 0 }), params)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
})
|
||||
|
||||
// Validity period: mirrors CHECK (valid_to IS NULL OR valid_to >= valid_from).
|
||||
describe('valid_from / valid_to ordering', () => {
|
||||
it('rejects valid_to before valid_from with an actionable 400', async () => {
|
||||
const response = await POST(
|
||||
post({ ...validLine, valid_from: '2026-06-01', valid_to: '2026-05-31' }),
|
||||
params,
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: string
|
||||
errors: { field: string; message: string }[]
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.errors).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ field: 'valid_to' })]),
|
||||
)
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('accepts valid_to equal to valid_from (the bound is inclusive)', async () => {
|
||||
enqueue({ data: { id: 'emp-1' } })
|
||||
enqueue({ data: { id: 'line-1' } })
|
||||
|
||||
const response = await POST(
|
||||
post({ ...validLine, valid_from: '2026-06-01', valid_to: '2026-06-01' }),
|
||||
params,
|
||||
)
|
||||
expect(response.status).toBe(201)
|
||||
})
|
||||
|
||||
it('accepts an omitted valid_to (open-ended line stays legal)', async () => {
|
||||
enqueue({ data: { id: 'emp-1' } })
|
||||
enqueue({ data: { id: 'line-1' } })
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
expect(response.status).toBe(201)
|
||||
})
|
||||
})
|
||||
|
||||
it('maps a check_violation from the insert to 400, not 500', async () => {
|
||||
enqueue({ data: { id: 'emp-1' } })
|
||||
enqueue({ data: null, error: { code: '23514', message: 'violates check constraint' } })
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('still reports a genuine DB failure as 500', async () => {
|
||||
enqueue({ data: { id: 'emp-1' } })
|
||||
enqueue({ data: null, error: { code: '08006', message: 'connection failure' } })
|
||||
|
||||
const response = await POST(post(validLine), params)
|
||||
expect(response.status).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { CreateEmployeeRecurringLineSchema } from '@/lib/api/schemas'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { roundOre } from '@/lib/money'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'salary.employees.recurring_lines.list',
|
||||
async (_request, { supabase, companyId }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('employee_recurring_lines')
|
||||
.select('*')
|
||||
.eq('employee_id', id)
|
||||
.eq('company_id', companyId)
|
||||
.order('valid_from', { ascending: false })
|
||||
|
||||
if (error) return NextResponse.json({ error: getUserErrorMessage(error) }, { status: 500 })
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
)
|
||||
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'salary.employees.recurring_lines.create',
|
||||
async (request, { supabase, companyId, user }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const validation = await validateBody(request, CreateEmployeeRecurringLineSchema)
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// Confirm employee belongs to the company. maybeSingle separates the two
|
||||
// empty outcomes: a lookup failure is a 500, only zero rows is a 404.
|
||||
const { data: emp, error: empError } = await supabase
|
||||
.from('employees')
|
||||
.select('id')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (empError) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(empError) }, { status: 500 })
|
||||
}
|
||||
if (!emp) return NextResponse.json({ error: 'Anställd hittades inte' }, { status: 404 })
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('employee_recurring_lines')
|
||||
.insert({
|
||||
employee_id: id,
|
||||
company_id: companyId,
|
||||
user_id: user.id,
|
||||
item_type: body.item_type,
|
||||
description: body.description,
|
||||
amount: roundOre(body.amount),
|
||||
account_number: body.account_number ?? null,
|
||||
valid_from: body.valid_from,
|
||||
valid_to: body.valid_to ?? null,
|
||||
metadata: body.metadata ?? {},
|
||||
is_active: body.is_active ?? true,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
// The create schema mirrors every CHECK on the table (item_type
|
||||
// whitelist, amount sign, account format, valid_to >= valid_from), so a
|
||||
// check_violation here is only the backstop for non-schema callers: bad
|
||||
// input, not a server fault.
|
||||
const status = error.code === '23514' ? 400 : 500
|
||||
return NextResponse.json({ error: getUserErrorMessage(error) }, { status })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data }, { status: 201 })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -155,6 +155,11 @@ export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
is_net_deduction: li.is_net_deduction,
|
||||
account_number: li.account_number,
|
||||
sort_order: li.sort_order,
|
||||
// Provenance must survive the copy: without these back-links a
|
||||
// recalculation of the correction run treats the copied derived
|
||||
// rows as manual and step 8d/8d3 derives them a second time.
|
||||
source_benefit_id: li.source_benefit_id ?? null,
|
||||
source_recurring_line_id: li.source_recurring_line_id ?? null,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user