* feat(skatteverket): rewrite AGI flow against real Skatteverket RAML The previous AGI client posted JSON to URL paths that don't exist on Skatteverket's gateway and used invented field names. POST /underlag actually accepts application/xml, and the lock/kvittenser operations live on the separate hanteraredovisningsperiod API. Verified against dev_docs/arbetsgivardeklaration-inlamning(1.7.7) and arbetsgivardeklaration-hantera-redovisningsperiod(1.2.8) RAMLs. - Replace fictional types with real schemas (kontrollresultat, granskningsunderlag, kvittenser, error envelope) - Rewrite agi-client into 9 functions matching the documented flow: /underlag (XML) -> kontrollresultat -> spara -> skapaGranskningsunderlag -> kvittenser, plus las/lasUpp on the hantera API - Drop agi-mappers entirely; lib/salary/agi/xml-generator.ts already produces schema-valid XML, so the extension just feeds agi_declarations.xml_content to POST /underlag - Extend skvRequest with a contentType option so AGI can post XML - AGIPanel state machine: underlag_submitted -> awaiting_signing -> signed, with kontrollresultat polling and normalized findings - Add the agd OAuth scope (confirmed from SKV's Tjanstebeskrivning Arbetsgivardeklaration inlamning v1.7, section 4.1.2.2) - Add Skatteverket connect step to NewUserChecklist alongside the existing SIE/old-system import and bank steps; track hasSkatteverketConnected in OnboardingProgress - Update orchestrator route + tests to point at the new /agi/submit endpoint - Declare new optional base-URL env vars in the manifest Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(skatteverket): address PR review findings on AGI flow - Surface INCORRECT_DATA felrapport link in AGIPanel skapaGranskningsunderlag returns 409 with a felrapport URL when SKV rejects the underlag. The link was persisted as `signeringslank` with status `underlag_rejected`, but the render condition only fired for `awaiting_signing`, leaving the link unreachable. Add a distinct destructive-styled block so the user can open the felrapport in Mina Sidor. - /agi/underlag DELETE clears local submission state Add optional `period` query param. When supplied, clear `agi_submission_{period}` directly. When not, fall back to scanning recent agi_submission_* keys for the matching inlamningId. Without this, an aborted underlag left a stale `underlag_submitted` entry in extension_data and the UI couldn't progress. - Re-add salary-run status guard inside loadAGIXml The orchestrator at app/api/salary/runs/[id]/agi/submit/route.ts has this check, but the extension endpoint is also reachable directly from AGIPanel and must enforce it itself. Per BFL 5 kap and SFL 26 kap, AGI must reflect finalised payroll data; submitting from a draft/cancelled run would emit incorrect figures. - Move agi_declarations.status='exported' from /agi/submit to /agi/spara Setting status on underlag-ingest was wrong because a DONE_REJECTED kontrollresultat would leave the row falsely marked as exported. The transition now happens only after the spara call commits the underlag to Eget utrymme. /agi/spara accepts salaryRunId in the body for the fast path and falls back to scanning agi_submission_* state otherwise. - Move salary_runs.agi_submitted_at stamp to kvittenser observation The orchestrator was stamping at underlag-ingest, but no later code updated the column on signing. Removed the orchestrator stamp; the /agi/kvittenser handler now stamps salary_runs.agi_submitted_at to kvittens.signeradTid (mirroring SKV's own timestamp) when it pins the receipt to the matching agi_declarations row. - Tighten misleading JSDoc in agi-client.ts taBortSparadInlamning is on the inlämning API, not hantera; the old layout grouped it under a "hantera API" heading and tripped an automated reviewer. Restructured into separate "period management" and "cleanup" blocks. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(skatteverket): address Swedish compliance review on AGI flow Follow-up to review on https://github.com/erp-mafia/gnubok/pull/391. - Migration adds 'pending_signature' to agi_declarations.status Reusing 'exported' for the spara→kvittens interval misstated the filing outcome — Eget utrymme is a staging area, not a filing — which conflicts with BFNAR 2013:2 kap 8 / BFL 5 kap 5§ behandlingshistorik faithfulness. /agi/spara now sets 'pending_signature'; /agi/kvittenser later promotes to 'submitted' when a uuidKvittens is observed. - AGIPanel auto-polls /agi/kvittenser at 30s, 2 min and 5 min after the signing link is created Previously the kvittens (and therefore salary_runs.agi_submitted_at) was only stamped if the user manually returned to the panel and clicked "Hämta kvittens". Without that follow-up the audit trail showed a NULL submitted-at for an AGI that had actually been filed. Background polls capture the kvittens for the common case where the user signs in Mina Sidor and never returns to gnubok. Cleanup on unmount via useRef + useEffect. - Distinct MISSING_SCOPE error code on 403 invalid_scope Existing tokens lack the new 'agd' scope and surface as a generic ACCESS_DENIED today. The compliance reviewer pointed out that operators may interpret this as a data error and submit a corrected AGI with altered figures. New SkatteverketAuthError code maps SKV's invalid_scope body to a clear "reconnect via Inställningar → Skatteverket" message; routes to 401 (token-level remediation). - Refine deadline copy in AGIPanel The standard AGI deadline is the 12th regardless of company size; the 17th only applies in January and August for employers with turnover ≤ 40 MSEK. Surface that nuance instead of saying just "12:e". Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(skatteverket): server-side kvittens reconciliation cron Round 2 of compliance review on https://github.com/erp-mafia/gnubok/pull/391. - /api/extensions/skatteverket/agi/kvittenser/cron Walks every agi_declarations row in 'pending_signature' status, fetches kvittenser via the matching token, and on a hit promotes the row to 'submitted' + stamps salary_runs.agi_submitted_at. Authoritative source for the audit trail per BFNAR 2013:2 kap 8 / BFL 5 kap 5§ — the AGIPanel client-side timers from the previous round remain as the fast-path UX, but no longer carry the audit-trail responsibility on their own. Per-row errors are skipped, not abort-the-run. 50s budget. Scheduled every 2 hours in vercel.json. - AGIStatus union now includes 'pending_signature' Without this update, downstream code reading the union would have rejected the new status as unknown. The migration extending the DB CHECK constraint shipped in the previous commit; this brings the type layer into sync. - Stale comment update in AGIPanel.tsx Referred to status='exported' from before the rename. Now reads 'pending_signature', matching the actual handler behavior. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(skatteverket): close audit-trail gaps from compliance round 3 - Cron now writes submitted_by from the token-owning auth.users row Previously left NULL with a "system actor" comment. The token row was created when the operator authenticated with BankID, and the kvittens' signeradAv refers to the same person — so writing the user_id from skatteverket_tokens captures actor traceability without inventing a system identity. Closes the BFL 5 kap 6§ / BFNAR 2013:2 kap 8 gap on cron-reconciled rows. - /agi/spara monotonicity guard Adds .in('status', ['generated', 'exported']) to the row update so a delayed /agi/spara call after the cron (or interactive /agi/kvittenser) has already promoted the row to 'submitted'/'accepted' won't silently regress it back to 'pending_signature'. behandlingshistorik must advance only. - DONE_REJECTED / DONE_FAILED → status='rejected' /agi/kontrollresultat handler now flips the matching agi_declarations row to 'rejected' on a terminal SKV failure, using the same cached-submission-state lookup pattern /agi/spara already uses. Without this the row sat at 'generated' indefinitely even though SKV considered the underlag failed. Same monotonicity guard prevents regressing a successfully-filed row. - Deadline criterion: lönesumma, not omsättning AGIPanel pendingText. SFL 26 kap's relaxed-deadline criterion (17:e in Jan/Aug) is the employer's total taxable wages, not turnover. Internal reference (.claude/skills/swedish-payroll/references/agi-filing.md) used the colloquial "turnover"; statutory wording is "lönesumma". Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(skatteverket): close round-4 audit-trail and UX gaps - agi_submitted_at: NULL when signeradTid absent Both /agi/kvittenser handler and the kvittens cron previously fell back to new Date().toISOString() if SKV's kvittens lacked signeradTid. Substituting wall-clock now() falsifies the filing moment in behandlingshistorik (BFNAR 2013:2 kap 8 / BFL 5 kap 6§). Now leaves the column NULL and logs a warning. Status flip to 'submitted' still happens — the audit gap was timing only. - Proactive missing-agd-scope banner SkatteverketConnectPanel and AGIPanel now warn when the stored token lacks the agd scope. Tokens issued before the agd rollout would otherwise 403 with invalid_scope at submission time, often too close to the AGI deadline. SkatteverketConnectPanel mirrors the existing "skattekonto saknas" pattern; AGIPanel surfaces a banner in the connected state and links to /settings/skatteverket. - Granskningsunderlag isError keys on tillstand only Previous check mixed HTTP 409 with the INCORRECT_DATA tillstand string. A future SKV addition like RECEIVING returned with HTTP 200 would have slipped through as awaiting_signing. Now keys solely on tillstand: only LOCKED_FOR_SIGNING / UNLOCKED are treated as signable; everything else (INCORRECT_DATA, RECEIVING, CALCULATING, SIGNING) routes to underlag_rejected. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(skatteverket): close round-5 audit-trail and recovery gaps - agi_submitted_at: stamp with reconciliation time when signeradTid absent Round 4 left the column NULL on missing signeradTid to avoid falsifying the signing moment. Round 5 pointed out that NULL hides that the filing *occurred* — also a behandlingshistorik integrity violation. Resolution: presence of uuidKvittens proves SKV signed and accepted the AGI, so we stamp with signeradTid || now() and warn-log when fallback is used. Both /agi/kvittenser handler and the kvittens cron. - Persist signeradAv + full kvittens in agi_declarations.response_data submitted_by is the auth.users UUID we have on hand (the polling / reconciling user). The legally load-bearing signer identity is kvittens.signeradAv (a personnummer) — which the token user_id does NOT necessarily match (e.g. bookkeeper vs deklarationsombud). The existing response_data jsonb column now holds the full kvittens record, preserving signeradAv for the audit trail (BFL 5 kap 6§ / BFNAR 2013:2 kap 8) without a schema change. Cron path also marks reconciledBy='cron'. - /agi/spara monotonicity: allow recovery from 'rejected' Previously .in('status', ['generated', 'exported']) excluded rejected rows, so a successful re-submission after a prior rejection couldn't promote the row to pending_signature — it silently stayed rejected. The xml-route reuses the same agi_declarations row when re-generating XML, so this is the realistic recovery path. Added 'rejected' to the allowed-from list. 'submitted'/'accepted' still blocked (no regression from filed states). - Fix misleading agi-client.ts comment Claimed users could "fix the errors in Mina Sidor" after a DONE_REJECTED save. Mina Sidor doesn't expose in-place editing; the correct recovery is to regenerate XML and resubmit. Updated the agiSparaUnderlag JSDoc to describe the actual flow. - Deadline copy: "vars sammanlagda lönesumma understiger 40 MSEK" Reads more cleanly than "≤ 40 MSEK" and matches the phrasing the compliance reviewer suggested. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(skatteverket): tighten /agi/spara guard and clarify deadline copy (round 6) - Drop 'exported' from /agi/spara allowed-from states Audit confirmed no code path writes status='exported' today; the value is preserved in the schema (and union) for the legacy manual-download path that no longer has a writer. Allowing the spara handler to flip an 'exported' row to 'pending_signature' would conflate two distinct filing attempts on a single row, weakening the chain of custody (BFL 5 kap 6§). Tightened to .in(['generated', 'rejected']) — same recovery path for re-submission after rejection, no path for the dormant state. - Deadline copy: explicit "per år" qualifier The 40 MSEK threshold is annual lönesumma, not per-payment. Adding "per år" closes the (admittedly thin) misread the compliance reviewer flagged. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
358 lines
12 KiB
TypeScript
358 lines
12 KiB
TypeScript
import type { SupabaseClient } from '@supabase/supabase-js'
|
|
import { skvRequest } from './api-client'
|
|
import type {
|
|
SkatteverketAGIErrorBody,
|
|
SkatteverketAGIGranskningsunderlagResponse,
|
|
SkatteverketAGIKontrollresultat,
|
|
SkatteverketAGIKvittenserResponse,
|
|
SkatteverketAGIUnderlagResponse,
|
|
} from '../types'
|
|
|
|
/**
|
|
* Skatteverket AGI (Arbetsgivardeklaration) client.
|
|
*
|
|
* Two RAMLs back this surface:
|
|
* • inlamning v1.7.7 — XML ingest + JSON status reads
|
|
* base: /arbetsgivardeklaration/inlamning/v1
|
|
* • hanteraredovisningsperiod v1.2.8 — period lock + receipts
|
|
* base: /arbetsgivardeklaration/hanteraredovisningsperiod/v1
|
|
*
|
|
* Filing flow:
|
|
* 1. POST /underlag (XML body, returns inlamningId)
|
|
* 2. GET /underlag/{inlamningId}/kontrollresultat (poll until status != PROCESSING)
|
|
* 3a. POST /underlag/{inlamningId}/spara (move into Eget utrymme)
|
|
* 3b. DELETE /underlag/{inlamningId} (abort if user wants to retry)
|
|
* 4. POST /arbetsgivare/{x}/redovisningsperioder/{y}/skapaGranskningsunderlag?lasPeriod=true
|
|
* → returns Mina Sidor deep-link for BankID signing
|
|
* 5. GET /arbetsgivare/{x}/redovisningsperioder/{y}/kvittenser (after user signs)
|
|
*
|
|
* Optional period management on the hantera API:
|
|
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/las (lock)
|
|
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/lasUpp (unlock)
|
|
*
|
|
* Cleanup paths (both on the inlämning API, NOT hantera):
|
|
* DELETE /underlag/{inlamningId}
|
|
* — abort an unsaved underlag (use agiAvbrytUnderlag)
|
|
* DELETE /arbetsgivare/{x}/redovisningsperioder/{y}/inlamningar/{inlamningId}
|
|
* — remove a SAVED underlag from Eget utrymme (use agiTaBortSparadInlamning)
|
|
*
|
|
* Note: skvRequest already maps 401/403/429 to SkatteverketAuthError. AGI
|
|
* 400/404/409 carry the SkatteverketAGIErrorBody envelope, which we surface
|
|
* via Result.error so callers can render meddelandeTillAnvandare verbatim.
|
|
*/
|
|
|
|
const DEFAULT_INLAMNING_BASE_URL =
|
|
'https://api.test.skatteverket.se/arbetsgivardeklaration/inlamning/v1'
|
|
const DEFAULT_HANTERA_BASE_URL =
|
|
'https://api.test.skatteverket.se/arbetsgivardeklaration/hanteraredovisningsperiod/v1'
|
|
|
|
function getInlamningBaseUrl(): string {
|
|
return process.env.SKATTEVERKET_AGD_INLAMNING_API_BASE_URL || DEFAULT_INLAMNING_BASE_URL
|
|
}
|
|
|
|
function getHanteraBaseUrl(): string {
|
|
return process.env.SKATTEVERKET_AGD_PERIOD_API_BASE_URL || DEFAULT_HANTERA_BASE_URL
|
|
}
|
|
|
|
function periodPath(arbetsgivare: string, period: string): string {
|
|
return `/arbetsgivare/${arbetsgivare}/redovisningsperioder/${period}`
|
|
}
|
|
|
|
interface Ok<T> { ok: true; status: number; data: T }
|
|
interface Err { ok: false; status: number; error: string; body?: SkatteverketAGIErrorBody }
|
|
type Result<T> = Ok<T> | Err
|
|
|
|
async function readErrorBody(response: Response): Promise<{ error: string; body?: SkatteverketAGIErrorBody }> {
|
|
try {
|
|
const body = (await response.json()) as SkatteverketAGIErrorBody
|
|
if (body && typeof body.meddelandeTillAnvandare === 'string') {
|
|
return { error: body.meddelandeTillAnvandare, body }
|
|
}
|
|
return { error: JSON.stringify(body) }
|
|
} catch {
|
|
return { error: `Skatteverket svarade med ${response.status}` }
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST /underlag — XML body, returns the new inlämningsId.
|
|
*
|
|
* The xml is whatever generateAGIXml() produced. We don't validate it
|
|
* locally; Skatteverket replies 415 if the schema fails parsing, or 400
|
|
* with felkod 38 if required fields are missing.
|
|
*/
|
|
export async function agiPostUnderlag(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
xml: string,
|
|
): Promise<Result<SkatteverketAGIUnderlagResponse>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'POST',
|
|
'/underlag',
|
|
xml,
|
|
{
|
|
baseUrl: getInlamningBaseUrl(),
|
|
contentType: 'application/xml',
|
|
},
|
|
)
|
|
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
|
|
const data = (await response.json()) as SkatteverketAGIUnderlagResponse
|
|
return { ok: true, status: response.status, data }
|
|
}
|
|
|
|
/**
|
|
* GET /underlag/{inlamningId}/kontrollresultat.
|
|
*
|
|
* Returns immediately with the current status. Callers should poll while
|
|
* status === 'PROCESSING' (Skatteverket's typical processing time is sub-
|
|
* second but the spec doesn't guarantee it).
|
|
*/
|
|
export async function agiGetKontrollresultat(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
inlamningId: number,
|
|
): Promise<Result<SkatteverketAGIKontrollresultat>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'GET',
|
|
`/underlag/${inlamningId}/kontrollresultat`,
|
|
undefined,
|
|
{ baseUrl: getInlamningBaseUrl() },
|
|
)
|
|
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
|
|
const data = (await response.json()) as SkatteverketAGIKontrollresultat
|
|
return { ok: true, status: response.status, data }
|
|
}
|
|
|
|
/**
|
|
* POST /underlag/{inlamningId}/spara — commit the underlag to Eget utrymme.
|
|
*
|
|
* Allowed even when kontrollresultat reports DONE_REJECTED — SKV will keep
|
|
* the rejected underlag in Eget utrymme as a record. Mina Sidor does NOT
|
|
* expose in-place editing of saved underlag; correcting a rejected AGI
|
|
* means generating new XML (with the same FK570 specifikationsnummer per
|
|
* employee) and resubmitting it as a rättelse via the same /underlag flow.
|
|
* The current AGIPanel doesn't auto-spara on rejection; it surfaces the
|
|
* findings and leaves recovery (re-generate + re-submit) to the user.
|
|
*
|
|
* Returns 400 felkod 20 if the underlag was already saved or had no
|
|
* errors to fix.
|
|
*/
|
|
export async function agiSparaUnderlag(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
inlamningId: number,
|
|
): Promise<Result<unknown>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'POST',
|
|
`/underlag/${inlamningId}/spara`,
|
|
undefined,
|
|
{ baseUrl: getInlamningBaseUrl() },
|
|
)
|
|
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
|
|
const data = await response.json().catch(() => ({}))
|
|
return { ok: true, status: response.status, data }
|
|
}
|
|
|
|
/**
|
|
* DELETE /underlag/{inlamningId} — avbryt en inlämning som ännu inte sparats.
|
|
*
|
|
* Use this to discard an underlag whose kontrollresultat showed errors
|
|
* before the user has clicked "spara". For *saved* underlag use
|
|
* agiTaBortSparadInlamning() below.
|
|
*/
|
|
export async function agiAvbrytUnderlag(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
inlamningId: number,
|
|
): Promise<Result<unknown>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'DELETE',
|
|
`/underlag/${inlamningId}`,
|
|
undefined,
|
|
{ baseUrl: getInlamningBaseUrl() },
|
|
)
|
|
|
|
if (response.status === 204) return { ok: true, status: 204, data: {} }
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
|
|
const data = await response.json().catch(() => ({}))
|
|
return { ok: true, status: response.status, data }
|
|
}
|
|
|
|
/**
|
|
* DELETE a saved underlag for an arbetsgivare + period. Distinct from
|
|
* agiAvbrytUnderlag — this targets the saved copy in Eget utrymme.
|
|
*/
|
|
export async function agiTaBortSparadInlamning(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
arbetsgivare: string,
|
|
period: string,
|
|
inlamningId: number,
|
|
): Promise<Result<unknown>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'DELETE',
|
|
`${periodPath(arbetsgivare, period)}/inlamningar/${inlamningId}`,
|
|
undefined,
|
|
{ baseUrl: getInlamningBaseUrl() },
|
|
)
|
|
|
|
if (response.status === 204) return { ok: true, status: 204, data: {} }
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
return { ok: true, status: response.status, data: {} }
|
|
}
|
|
|
|
/**
|
|
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/skapaGranskningsunderlag.
|
|
*
|
|
* Returns a Mina Sidor deep-link the user opens in a new tab to sign with
|
|
* BankID. `lasPeriod=true` locks the period for changes during signing —
|
|
* recommended for the happy path. Caller can later POST .../las or .../lasUpp
|
|
* on the hantera API to flip the lock without regenerating the granskning.
|
|
*/
|
|
export async function agiSkapaGranskningsunderlag(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
arbetsgivare: string,
|
|
period: string,
|
|
options: { lasPeriod?: boolean } = {},
|
|
): Promise<Result<SkatteverketAGIGranskningsunderlagResponse>> {
|
|
const qs = options.lasPeriod ? '?lasPeriod=true' : ''
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'POST',
|
|
`${periodPath(arbetsgivare, period)}/skapaGranskningsunderlag${qs}`,
|
|
undefined,
|
|
{ baseUrl: getInlamningBaseUrl() },
|
|
)
|
|
|
|
// 409 INCORRECT_DATA returns the same shape as 200 (with a felrapport
|
|
// link) — surface it as data rather than an error so the UI can route the
|
|
// user to fix the rejected underlag.
|
|
if (response.status === 409) {
|
|
const data = (await response.json()) as SkatteverketAGIGranskningsunderlagResponse
|
|
return { ok: true, status: 409, data }
|
|
}
|
|
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
|
|
const data = (await response.json()) as SkatteverketAGIGranskningsunderlagResponse
|
|
return { ok: true, status: response.status, data }
|
|
}
|
|
|
|
/**
|
|
* GET /arbetsgivare/{x}/redovisningsperioder/{y}/kvittenser
|
|
* (hanteraredovisningsperiod API).
|
|
*
|
|
* Returns an empty kvittenser array until the user has signed in Mina Sidor.
|
|
* Once signed, each receipt carries uuidKvittens + signeradAv + signeradTid.
|
|
*/
|
|
export async function agiGetKvittenser(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
arbetsgivare: string,
|
|
period: string,
|
|
): Promise<Result<SkatteverketAGIKvittenserResponse>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'GET',
|
|
`${periodPath(arbetsgivare, period)}/kvittenser`,
|
|
undefined,
|
|
{ baseUrl: getHanteraBaseUrl() },
|
|
)
|
|
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
|
|
const data = (await response.json()) as SkatteverketAGIKvittenserResponse
|
|
return { ok: true, status: response.status, data }
|
|
}
|
|
|
|
/**
|
|
* POST /arbetsgivare/{x}/redovisningsperioder/{y}/las (hantera API).
|
|
* Locks the period for changes — typically called automatically by
|
|
* skapaGranskningsunderlag with lasPeriod=true.
|
|
*/
|
|
export async function agiLasPeriod(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
arbetsgivare: string,
|
|
period: string,
|
|
): Promise<Result<unknown>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'POST',
|
|
`${periodPath(arbetsgivare, period)}/las`,
|
|
undefined,
|
|
{ baseUrl: getHanteraBaseUrl() },
|
|
)
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
const data = await response.json().catch(() => ({}))
|
|
return { ok: true, status: response.status, data }
|
|
}
|
|
|
|
/** POST /arbetsgivare/{x}/redovisningsperioder/{y}/lasUpp (hantera API). */
|
|
export async function agiLasUppPeriod(
|
|
supabase: SupabaseClient,
|
|
userId: string,
|
|
arbetsgivare: string,
|
|
period: string,
|
|
): Promise<Result<unknown>> {
|
|
const response = await skvRequest(
|
|
supabase,
|
|
userId,
|
|
'POST',
|
|
`${periodPath(arbetsgivare, period)}/lasUpp`,
|
|
undefined,
|
|
{ baseUrl: getHanteraBaseUrl() },
|
|
)
|
|
if (!response.ok) {
|
|
const { error, body } = await readErrorBody(response)
|
|
return { ok: false, status: response.status, error, body }
|
|
}
|
|
const data = await response.json().catch(() => ({}))
|
|
return { ok: true, status: response.status, data }
|
|
}
|