fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { completeTaxDeadline } from '../complete-tax-deadline'
|
||||
|
||||
/**
|
||||
* Chain mock that records every builder call and resolves to the given
|
||||
* result when awaited (the helper ends the chain with .select('id')).
|
||||
*/
|
||||
function makeSupabase(result: { data?: unknown; error?: unknown }) {
|
||||
const calls: Array<{ method: string; args: unknown[] }> = []
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['update', 'eq', 'in', 'select']) {
|
||||
chain[method] = vi.fn((...args: unknown[]) => {
|
||||
calls.push({ method, args })
|
||||
return chain
|
||||
})
|
||||
}
|
||||
chain.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
|
||||
const from = vi.fn(() => chain)
|
||||
return { supabase: { from } as unknown as SupabaseClient, from, calls }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('completeTaxDeadline', () => {
|
||||
it('completes matching open deadlines and returns the count', async () => {
|
||||
const { supabase, from, calls } = makeSupabase({ data: [{ id: 'd1' }, { id: 'd2' }] })
|
||||
|
||||
const result = await completeTaxDeadline(
|
||||
supabase, 'company-1', ['moms_monthly', 'moms_quarterly'], '2026-06', 'submitted',
|
||||
)
|
||||
|
||||
expect(result).toEqual({ completed: 2 })
|
||||
expect(from).toHaveBeenCalledWith('deadlines')
|
||||
|
||||
const updateCall = calls.find((c) => c.method === 'update')
|
||||
expect(updateCall?.args[0]).toMatchObject({
|
||||
is_completed: true,
|
||||
status: 'submitted',
|
||||
})
|
||||
expect((updateCall?.args[0] as Record<string, unknown>).completed_at).toBeTruthy()
|
||||
|
||||
const eqArgs = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
||||
expect(eqArgs).toContainEqual(['company_id', 'company-1'])
|
||||
expect(eqArgs).toContainEqual(['tax_period', '2026-06'])
|
||||
expect(eqArgs).toContainEqual(['is_completed', false])
|
||||
|
||||
const inCall = calls.find((c) => c.method === 'in')
|
||||
expect(inCall?.args).toEqual(['tax_deadline_type', ['moms_monthly', 'moms_quarterly']])
|
||||
})
|
||||
|
||||
it('quarterly period string matches the generator format', async () => {
|
||||
const { supabase, calls } = makeSupabase({ data: [{ id: 'd1' }] })
|
||||
|
||||
await completeTaxDeadline(supabase, 'company-1', ['moms_quarterly'], '2026-Q2', 'confirmed')
|
||||
|
||||
const eqArgs = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
||||
expect(eqArgs).toContainEqual(['tax_period', '2026-Q2'])
|
||||
const updateCall = calls.find((c) => c.method === 'update')
|
||||
expect(updateCall?.args[0]).toMatchObject({ status: 'confirmed' })
|
||||
})
|
||||
|
||||
it('is a no-op returning 0 when nothing matches', async () => {
|
||||
const { supabase } = makeSupabase({ data: [] })
|
||||
const result = await completeTaxDeadline(
|
||||
supabase, 'company-1', ['arbetsgivardeklaration'], '2026-01', 'submitted',
|
||||
)
|
||||
expect(result).toEqual({ completed: 0 })
|
||||
})
|
||||
|
||||
it('swallows DB errors: logs and returns 0, never throws', async () => {
|
||||
const { supabase } = makeSupabase({ error: { message: 'permission denied' } })
|
||||
await expect(
|
||||
completeTaxDeadline(supabase, 'company-1', ['moms_monthly'], '2026-06', 'submitted'),
|
||||
).resolves.toEqual({ completed: 0 })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
|
||||
const log = createLogger('complete-tax-deadline')
|
||||
|
||||
/**
|
||||
* Mark a system-generated tax deadline as completed from an external signal
|
||||
* (a declaration was generated, filed, or decided).
|
||||
*
|
||||
* Deadline completion is a courtesy on top of the filing flow, never part of
|
||||
* it: this helper logs failures and returns instead of throwing, so a broken
|
||||
* deadline row can never block a submission to Skatteverket.
|
||||
*
|
||||
* `taxPeriod` must use the deadline generator's format
|
||||
* (lib/tax/deadline-generator.ts): `YYYY-MM` for monthly, `YYYY-QN` for
|
||||
* quarterly, `YYYY` for annual. Build it from the caller's own period params;
|
||||
* do not reverse-parse Skatteverket's redovisningsperiod strings.
|
||||
*
|
||||
* Pass every deadline type that can represent the filing (e.g. both
|
||||
* `moms_monthly` and `moms_quarterly` for a VAT filing): the company's
|
||||
* settings decide which one exists, and the `IN` filter makes the wrong one
|
||||
* a no-op.
|
||||
*/
|
||||
export async function completeTaxDeadline(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
taxDeadlineTypes: string[],
|
||||
taxPeriod: string,
|
||||
newStatus: 'submitted' | 'confirmed'
|
||||
): Promise<{ completed: number }> {
|
||||
const now = new Date().toISOString()
|
||||
const { data, error } = await supabase
|
||||
.from('deadlines')
|
||||
.update({
|
||||
is_completed: true,
|
||||
completed_at: now,
|
||||
status: newStatus,
|
||||
status_changed_at: now,
|
||||
})
|
||||
.eq('company_id', companyId)
|
||||
.in('tax_deadline_type', taxDeadlineTypes)
|
||||
.eq('tax_period', taxPeriod)
|
||||
.eq('is_completed', false)
|
||||
.select('id')
|
||||
|
||||
if (error) {
|
||||
log.warn('Failed to auto-complete tax deadline', {
|
||||
companyId,
|
||||
taxDeadlineTypes,
|
||||
taxPeriod,
|
||||
error: error.message,
|
||||
})
|
||||
return { completed: 0 }
|
||||
}
|
||||
|
||||
return { completed: data?.length ?? 0 }
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
/**
|
||||
* Status engine for deadline status transitions
|
||||
*
|
||||
* Status flow:
|
||||
* upcoming ──(14d före)──> action_needed ──(manuell)──> in_progress
|
||||
* │ │
|
||||
* │ ──(manuell)──> submitted ──> confirmed
|
||||
* │
|
||||
* (passerad)
|
||||
* │
|
||||
* v
|
||||
* overdue
|
||||
*/
|
||||
|
||||
import { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import type { DeadlineStatus } from '@/types'
|
||||
|
||||
const log = createLogger('deadline-status')
|
||||
|
||||
/**
|
||||
* Number of days before deadline when status changes to action_needed
|
||||
*/
|
||||
export const ACTION_NEEDED_THRESHOLD_DAYS = 14
|
||||
|
||||
/**
|
||||
* Valid manual status transitions
|
||||
*/
|
||||
export const MANUAL_TRANSITIONS: Record<DeadlineStatus, DeadlineStatus[]> = {
|
||||
upcoming: ['action_needed', 'in_progress'],
|
||||
action_needed: ['in_progress', 'submitted'],
|
||||
in_progress: ['submitted', 'action_needed'],
|
||||
submitted: ['confirmed', 'in_progress'],
|
||||
confirmed: [], // Terminal state
|
||||
overdue: ['in_progress', 'submitted'], // Can recover from overdue
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a manual status transition is valid
|
||||
*/
|
||||
export function isValidTransition(
|
||||
currentStatus: DeadlineStatus,
|
||||
newStatus: DeadlineStatus
|
||||
): boolean {
|
||||
return MANUAL_TRANSITIONS[currentStatus].includes(newStatus)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate days until a deadline
|
||||
*/
|
||||
export function daysUntilDeadline(dueDate: string): number {
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const deadline = new Date(dueDate)
|
||||
deadline.setHours(0, 0, 0, 0)
|
||||
return Math.ceil((deadline.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
||||
}
|
||||
|
||||
/**
|
||||
* Update deadline statuses automatically (called by daily cron)
|
||||
*/
|
||||
export async function updateDeadlineStatuses(
|
||||
supabase: SupabaseClient
|
||||
): Promise<{ updated: number; newlyOverdue: number; newlyActionNeeded: number }> {
|
||||
const today = new Date()
|
||||
today.setHours(0, 0, 0, 0)
|
||||
const todayStr = today.toISOString().split('T')[0]
|
||||
|
||||
// Calculate the action_needed threshold date
|
||||
const thresholdDate = new Date(today)
|
||||
thresholdDate.setDate(thresholdDate.getDate() + ACTION_NEEDED_THRESHOLD_DAYS)
|
||||
const thresholdStr = thresholdDate.toISOString().split('T')[0]
|
||||
|
||||
let updated = 0
|
||||
let newlyOverdue = 0
|
||||
let newlyActionNeeded = 0
|
||||
|
||||
// 1. Mark overdue: past deadline, not completed, not submitted/confirmed
|
||||
const { data: overdueDeadlines, error: overdueError } = await supabase
|
||||
.from('deadlines')
|
||||
.update({
|
||||
status: 'overdue',
|
||||
status_changed_at: new Date().toISOString(),
|
||||
})
|
||||
.lt('due_date', todayStr)
|
||||
.eq('is_completed', false)
|
||||
.is('dismissed_at', null)
|
||||
.in('status', ['upcoming', 'action_needed'])
|
||||
.select('id')
|
||||
|
||||
if (overdueError) {
|
||||
log.error('Error updating overdue deadlines:', overdueError)
|
||||
} else {
|
||||
newlyOverdue = overdueDeadlines?.length || 0
|
||||
updated += newlyOverdue
|
||||
}
|
||||
|
||||
// 2. Mark action_needed: within threshold, currently upcoming
|
||||
const { data: actionNeededDeadlines, error: actionNeededError } = await supabase
|
||||
.from('deadlines')
|
||||
.update({
|
||||
status: 'action_needed',
|
||||
status_changed_at: new Date().toISOString(),
|
||||
})
|
||||
.gte('due_date', todayStr)
|
||||
.lte('due_date', thresholdStr)
|
||||
.eq('status', 'upcoming')
|
||||
.eq('is_completed', false)
|
||||
.is('dismissed_at', null)
|
||||
.select('id')
|
||||
|
||||
if (actionNeededError) {
|
||||
log.error('Error updating action_needed deadlines:', actionNeededError)
|
||||
} else {
|
||||
newlyActionNeeded = actionNeededDeadlines?.length || 0
|
||||
updated += newlyActionNeeded
|
||||
}
|
||||
|
||||
return { updated, newlyOverdue, newlyActionNeeded }
|
||||
}
|
||||
|
||||
/**
|
||||
* Manually update a deadline's status
|
||||
*/
|
||||
export async function updateDeadlineStatus(
|
||||
supabase: SupabaseClient,
|
||||
deadlineId: string,
|
||||
companyId: string,
|
||||
newStatus: DeadlineStatus
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
// Fetch current deadline
|
||||
const { data: deadline, error: fetchError } = await supabase
|
||||
.from('deadlines')
|
||||
.select('status, is_completed')
|
||||
.eq('id', deadlineId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (fetchError || !deadline) {
|
||||
return { success: false, error: 'Deadline not found' }
|
||||
}
|
||||
|
||||
// Check if transition is valid
|
||||
if (!isValidTransition(deadline.status, newStatus)) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Invalid transition from ${deadline.status} to ${newStatus}`,
|
||||
}
|
||||
}
|
||||
|
||||
// Update the status
|
||||
const updates: Record<string, unknown> = {
|
||||
status: newStatus,
|
||||
status_changed_at: new Date().toISOString(),
|
||||
}
|
||||
|
||||
// If marking as confirmed, also mark as completed
|
||||
if (newStatus === 'confirmed') {
|
||||
updates.is_completed = true
|
||||
updates.completed_at = new Date().toISOString()
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('deadlines')
|
||||
.update(updates)
|
||||
.eq('id', deadlineId)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (updateError) {
|
||||
return { success: false, error: updateError.message }
|
||||
}
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Get deadlines that need attention (action_needed or overdue)
|
||||
*/
|
||||
export async function getDeadlinesNeedingAttention(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string
|
||||
): Promise<{
|
||||
actionNeeded: Array<{ id: string; title: string; due_date: string; tax_deadline_type: string | null }>
|
||||
overdue: Array<{ id: string; title: string; due_date: string; tax_deadline_type: string | null }>
|
||||
}> {
|
||||
const { data: deadlines, error } = await supabase
|
||||
.from('deadlines')
|
||||
.select('id, title, due_date, tax_deadline_type, status')
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_completed', false)
|
||||
.is('dismissed_at', null)
|
||||
.in('status', ['action_needed', 'overdue'])
|
||||
.order('due_date', { ascending: true })
|
||||
|
||||
if (error) {
|
||||
log.error('Error fetching deadlines needing attention:', error)
|
||||
return { actionNeeded: [], overdue: [] }
|
||||
}
|
||||
|
||||
const actionNeeded = deadlines?.filter((d) => d.status === 'action_needed') || []
|
||||
const overdue = deadlines?.filter((d) => d.status === 'overdue') || []
|
||||
|
||||
return { actionNeeded, overdue }
|
||||
}
|
||||
Reference in New Issue
Block a user