Fix/skv connection flow (#1015)
* feat(salary): one-click AGI submission with filing state machine and success feedback The AGI panel required users to know that "Ladda ner AGI-fil" was the generate step, then click submit, signing link, and kvittens manually. A nollkorning filing stalled on "AGI-XML saknas" pointing at a UI path that does not exist. - New primary button "Lamna in till Skatteverket" chains the existing endpoints client-side: generate XML if missing, POST underlag, poll kontrollresultat, create signing link, open Mina Sidor in a tab opened synchronously at click (popup-blocker safe). Inline stepper shows each step; the four old buttons become collapsed advanced/recovery actions, auto-expanded in stale-draft and rejected states. XML download stays visible and free for manual filing. - deriveAgiFilingState() + useAgiSubmission() lift the per-period submission record to the run page: the progress rail and salary hero now render the real state machine (generated, underlag inskickat, vantar pa BankID-signatur, inlamnad med kvittensnummer) instead of telling users to "lamna in" an already-submitted declaration. - Success card with kvittensnummer and signature metadata once signed, plus a toast when a poll flips the state while the page is open. - AGI kvittens cron every 15 min instead of every 2 h so filings signed on another device get stamped and emailed promptly. - Advanced submit also auto-generates, and the stale "Lon -> AGI -> Generera" error text now points at the real buttons. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(enable-banking): instant OAuth callback feedback and dead-attempt cleanup The bank redirect landed on a blank page for the several seconds the callback spent exchanging the PSD2 session and mirroring accounts, and every failed connect attempt left a status='error' row that rendered forever as an "Atgard kravs" card next to a successful retry, showing duplicate connections to the same bank. - Stream a branded "Slutfor bankanslutningen" progress page from the callback: the shell flushes before the session exchange starts and a script/meta redirect follows when the work completes, with a 30s slow-work escape hatch. Fast outcomes (denial, bad params, unknown state) keep their plain redirects. - Delete never-activated connection rows (no session_id, no accounts_data) on denial or exchange failure, and sweep leftovers for the same bank on the next connect. Established connections keep their "Atgard krävs" card via the accounts_data guard; FKs are ON DELETE SET NULL so deletion has no dependents. - Show "Banken ar ansluten: hamtar dina konton" while the settings panel loads after the callback instead of an anonymous spinner. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(invoices): reject re-send of issued invoices and gate bookkeeping on the sent flip A direct POST to /api/invoices/[id]/send against an already-issued invoice re-emailed the customer and posted a second revenue verifikat (createInvoiceJournalEntry has no dedup), overwriting journal_entry_id and orphaning the first entry. Only the UI hid the button; the v1 route and the MCP commit executor already rejected non-drafts. - Non-draft invoices now return 409 INVOICE_ALREADY_SENT. - The draft to sent status flip is an optimistic lock (status guard plus row-count check); journal entry, accrual schedules, PDF archival and the invoice.sent event only run for the request that won the flip. - On a flip failure the journal entry is deferred: the row stays draft and a retry re-runs the pipeline, ending with exactly one verifikat. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(invoices): payment links, failure visibility and sandbox guard for recurring auto-send - sendInvoiceFromSchedule now auto-creates an online payment link via applyPaymentLinkToInvoice before rendering and passes the payment link QR to the PDF: parity with the dashboard and v1 send routes, which recurring invoices silently lacked. - The recurring cron persists last_run_warning both when a claimed run throws (hourly retries stay visible on the schedule) and when a stale schedule is rolled forward, so a deterministic failure can no longer skip a month silently. - Auto-send is blocked for sandbox companies at the email chokepoint (freeze-and-retain: the invoice is still generated as a draft), covering both the cron and the run-now route with one guard. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(salary): close the Fortnox payroll API gaps (phases 1-4) Payroll now runs end-to-end through the open API, including onboarding a client from another payroll system, with every write staged for approval. - v1: per-employee payslips (list/detail/PDF), payslip line writes, run roster attach/remove, absence ranges (per-day storage), jamkning fields, cutover opening balances (single + atomic bulk PUT), vacation balance + vacation-year-close. PUT added to the wrapper's idempotency/ test-key set (test keys could otherwise write through PUT). - MCP: 10 new tools (get_employee/get_payslip/list_absence/ get_vacation_balance reads + staged update_payslip_line, register_absence, create_employee, update_employee, set_employee_opening_balances, close_vacation_year), executors, risk tiers, op-type CHECK expansions. create_employee encrypts personnummer at staging: pending_operations never holds plaintext. - Scope-map audit retrofit: 11 formerly unmapped tools now scoped; BREAKING for keys that relied on the 4 default-allow writes. - Cutover: employee_opening_balances (derived lock trigger, self-unlocks on run correction), engine YTD/karens/liability integration, Ingaende saldon section in the employee editor. - Arbetsschema-lite: employees.hours_per_week/workdays_per_week drive the hourly/daily divisors; legacy 173/21 preserved exactly at defaults so existing pay math is byte-identical. - Vacation ledger + semesterberedning/arsavslut: recomputed per-year day balances (synced on book/correct, non-fatal), year-close with the min-20 floor, 5-year sparade-dagar expiry to forced payout, and a 2920/2940 drift adjustment via the bookkeeping engine; Semester dashboard card with preview-then-confirm dialog. - Fix: Zod 4 defaults leak through .partial(), which made every sparse employee PATCH fail validation and reset defaulted columns. Migrations 20260713100000/101000/110000/121000/122000 (applied to staging with version rows; prod via merge). vacation_ledger renamed from 20260713120000 to avoid colliding with vat_declaration_totals_rpc. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * perf: cut dashboard page-load latency (region, round trips, caching, VAT RPC) The dominant cost was infrastructure: Vercel functions ran in iad1 (Washington D.C.) while Supabase (DB + auth) lives in eu-north-1 (Stockholm), so every request paid 4-5 transatlantic round trips of auth + company resolution before doing any real work (measured 530-1900ms for single-query GETs in prod logs). Pin functions to arn1 and cut the redundant work on top: - vercel.json: functions to arn1, same city as the database - getActiveCompanyId: preference + first-membership queries run in parallel; the fallback result doubles as validation in the common single-company case (one round trip instead of two sequential) - withRouteContext: Server-Timing header and authMs/companyMs/handlerMs in the op-completed log, so latency is attributable per phase - dashboard layout: nav badge counts off the critical path; DashboardNav loads them client-side via the new use-worklist-badges SWR hook with debounced realtime revalidation - swr (new dependency, approved): global provider; useCompanySettings shares one cache entry across consumers and renders from cache on back-navigation instead of re-showing skeletons - /pending: realtime refetch debounced; bulk operations previously fired 4 requests per row-change event - VAT declaration: new get_vat_declaration_totals RPC returns per-account totals, settlement-shape detection (#984) and source_type counts in ONE round trip instead of paging every entry+line through PostgREST. Account lists stay TS-side parameters so ACCOUNT_RUTA remains the single source of truth. Shape-exclusion coverage moved to tests/pg/vat-declaration-totals-rpc.pg.test.ts; DDL already applied to staging. - bundle: CommandPalette lazy-mounts on first Ctrl/Cmd+K, AgentChat dynamic-imports the markdown parser, @vercel/speed-insights (new dependency, approved) added for real-user timings The /salary fetch-waterfall fix from the same effort already landed inside 2084a756. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(invoices): settle öre-rounded payments from the mark-paid flow An invoice with öresavrundning shows a rounded "Att betala" on the PDF; the customer pays that amount (up to 50 öre off the stored öre total) and the invoice-page mark-paid flow rejected it with MATCH_AMOUNT_EXCEEDS_REMAINING: a dead end, while the bank-transaction match flow already absorbed the residual to 3740. - PaymentBookingDialog now proposes the rounded bank leg plus the 3740 residual line (credit when rounded up, debit when rounded down), resolved via getDisplayTotal from the per-invoice override and company_settings.ore_rounding. - settleInvoicePayment and the v1 mark-paid route absorb the sub-krona residual, gated by planInvoicePaymentForLines: absorption applies ONLY when the caller lines carry the exact residual on 3740; otherwise the strict plan applies (sub-krona partials stay partial, no-3740 overshoots keep the 400), so the GL can never diverge from the AR sub-ledger. - planInvoicePayment absorb-band boundary tightened to >= 1 kr: an exactly-1-kr overshoot used to slip past both the guard and the absorb branch and silently over-record paid_amount (pre-existing on the bank-match path). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(security): resolve all 7 PR compliance findings - ASVS V3.3: per-request CSP nonce on the enable-banking finalize page (mirrors the mcp-oauth consent page); inline scripts are nonce-bound - ASVS V16: decouple callback finalize work from the response stream (eager promise + next/server after()) so a client disconnect cannot drop session persistence or the consent_granted audit emit - ISO 27001 A.8.15: failed audit-event emits log through the structured logger with a stable message for log-based alerting - ASVS V2.3: recurring-invoice cron and run-now routes resolve isSandboxCompany themselves and pass an explicit suppressAutoSend flag (defence in depth around the email chokepoint, freeze-and-retain kept) - ISO 27001 A.8.11: stagePendingOperation rejects plaintext personnummer-bearing keys in params/preview_data (key-based guard; EF org numbers make value-matching unsafe) - ASVS V4.5: employee PATCH body is truly sparse; cleared number fields are omitted instead of resetting DB values to hardcoded fallbacks - ASVS V8.2.1: route-level tests pin the v1 cross-company deny (404 by convention, not 403) on the payslip PDF endpoint Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat: implement vacation-year basis change validation and error handling - Added tests to block vacation-year basis changes when open balances exist. - Implemented error handling for open-balances guard query failures in the settings route. - Enhanced absence route to reject reversed date ranges with a validation error. - Updated absence handling to use atomic upserts instead of delete+insert for better performance and reliability. - Refactored salary calculation logic to correctly handle age-based avgifter rates according to Skatteverket's rules. - Improved error messaging for vacation year closure adjustments. - Adjusted employee opening balances handling to preserve audit information during upserts. * feat(settings): add validation to block vacation-year basis change with open balances feat(absence): reject reversed date ranges in absence queries fix(absence): update absence handling to use atomic upserts instead of delete+insert fix(employee): improve validation for jamkning dates in employee updates fix(opening-balances): ensure created_by field is preserved during upserts test(absence): enhance tests for absence range and date validations test(calculation): add tests for age-based avgifter rates and edge cases test(semesterberedning): validate vacation year closure adjustments and error handling test(employee-opening-balances): update tests to reflect changes in salary_run_employees schema * fix(migrations): implement NOT VALID constraints for pending_operations and add validation migration --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
e7e3c35f9e
commit
b6332e9ff4
+164
-1
@@ -1521,6 +1521,10 @@ export const UpdateSettingsSchema = z.object({
|
||||
.enum(['swedbank', 'seb', 'handelsbanken', 'nordea', 'other'])
|
||||
.nullable()
|
||||
.optional(),
|
||||
// Vacation year basis (payroll gap-closure 3.1): sammanfallande calendar
|
||||
// year (default) or the statutory Apr 1 - Mar 31 split. The settings route
|
||||
// blocks changing this while open vacation-ledger rows exist.
|
||||
salary_vacation_year_basis: z.enum(['calendar', 'statutory_apr_mar']).optional(),
|
||||
}).refine(
|
||||
(data) => {
|
||||
// BFL 3 kap.: Enskild firma must have fiscal year starting January
|
||||
@@ -1959,6 +1963,11 @@ const EmployeeSchemaBase = z.object({
|
||||
employment_start: isoDate,
|
||||
employment_end: isoDate.optional(),
|
||||
employment_degree: z.number().min(1).max(100).default(100),
|
||||
// Arbetsschema-lite: weekly schedule driving the hourly/daily divisors
|
||||
// (legacy 173/21 at the defaults). employment_degree keeps prorating base
|
||||
// salary; these ONLY drive divisors.
|
||||
hours_per_week: z.number().positive().max(80).default(40),
|
||||
workdays_per_week: z.number().min(1).max(7).default(5),
|
||||
salary_type: SalaryTypeSchema.default('monthly'),
|
||||
monthly_salary: z.number().nonnegative().optional(),
|
||||
hourly_rate: z.number().nonnegative().optional(),
|
||||
@@ -1980,6 +1989,14 @@ const EmployeeSchemaBase = z.object({
|
||||
vaxa_stod_eligible: z.boolean().default(false),
|
||||
vaxa_stod_start: isoDate.optional(),
|
||||
vaxa_stod_end: isoDate.optional(),
|
||||
// Jämkning (Skatteverket beslut om ändrad beräkning av skatteavdrag):
|
||||
// overrides the tax-table lookup with a fixed percentage for a bounded
|
||||
// period. Fields have existed on the employees table since the salary
|
||||
// module shipped; this exposes the write path (payroll gap-closure 1.5).
|
||||
// Setting jamkning_percentage to null clears the beslut.
|
||||
jamkning_percentage: z.number().min(0).max(100).nullable().optional(),
|
||||
jamkning_valid_from: isoDate.nullable().optional(),
|
||||
jamkning_valid_to: isoDate.nullable().optional(),
|
||||
// Dimensions PR8: bag applied to the employee's P&L cost lines when a
|
||||
// salary run is booked. {} clears (the UI always sends the field).
|
||||
default_dimensions: DimensionsBagSchema.optional(),
|
||||
@@ -2046,6 +2063,32 @@ export const CreateEmployeeSchema = EmployeeSchemaBase.superRefine((data, ctx) =
|
||||
})
|
||||
}
|
||||
|
||||
// Jämkning: a percentage without a start date is meaningless (the engine
|
||||
// gates on jamkning_valid_from <= payment_date). End date is optional
|
||||
// (beslut often run until year-end implicitly).
|
||||
if (
|
||||
data.jamkning_percentage !== null &&
|
||||
data.jamkning_percentage !== undefined &&
|
||||
!data.jamkning_valid_from
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Jämkningens startdatum måste anges när jämkningsprocent sätts',
|
||||
path: ['jamkning_valid_from'],
|
||||
})
|
||||
}
|
||||
if (
|
||||
data.jamkning_valid_from &&
|
||||
data.jamkning_valid_to &&
|
||||
data.jamkning_valid_to < data.jamkning_valid_from
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Jämkningens slutdatum måste vara efter startdatumet',
|
||||
path: ['jamkning_valid_to'],
|
||||
})
|
||||
}
|
||||
|
||||
// Bank details: validate clearing/kontonummer structure at entry so a typo is
|
||||
// caught here rather than at Bankgirot LB generation. Both empty is allowed.
|
||||
// Update path is validated in the PATCH route (only when the fields actually
|
||||
@@ -2060,7 +2103,28 @@ export const CreateEmployeeSchema = EmployeeSchemaBase.superRefine((data, ctx) =
|
||||
}
|
||||
})
|
||||
|
||||
export const UpdateEmployeeSchema = EmployeeSchemaBase.partial().superRefine((data, ctx) => {
|
||||
// PATCH base: the create-schema defaults are stripped first. Zod 4 applies
|
||||
// .default() even through .partial() (absent key -> default value), which
|
||||
// would (a) make sparse PATCH bodies fail the salary-type refinement below
|
||||
// (salary_type materializes as 'monthly' without monthly_salary present) and
|
||||
// (b) leak default values into routes that spread the parsed body into the
|
||||
// UPDATE (silently resetting e.g. is_sidoinkomst on unrelated edits).
|
||||
const EmployeeSchemaPatchBase = EmployeeSchemaBase.extend({
|
||||
employment_type: EmploymentTypeSchema,
|
||||
employment_degree: z.number().min(1).max(100),
|
||||
hours_per_week: z.number().positive().max(80),
|
||||
workdays_per_week: z.number().min(1).max(7),
|
||||
salary_type: SalaryTypeSchema,
|
||||
tax_column: z.number().int().min(1).max(6),
|
||||
is_sidoinkomst: z.boolean(),
|
||||
f_skatt_status: FSkattStatusSchema,
|
||||
vacation_rule: VacationRuleSchema,
|
||||
vacation_days_per_year: z.number().int().min(25).max(40),
|
||||
semestertillagg_rate: z.number().min(0).max(0.05),
|
||||
vaxa_stod_eligible: z.boolean(),
|
||||
})
|
||||
|
||||
export const UpdateEmployeeSchema = EmployeeSchemaPatchBase.partial().superRefine((data, ctx) => {
|
||||
// Only validate salary when salary_type is being changed in this update
|
||||
if (data.salary_type === 'monthly' && data.monthly_salary !== undefined && data.monthly_salary <= 0) {
|
||||
ctx.addIssue({
|
||||
@@ -2127,6 +2191,23 @@ export const UpdateEmployeeSchema = EmployeeSchemaBase.partial().superRefine((da
|
||||
path: ['vaxa_stod_end'],
|
||||
})
|
||||
}
|
||||
|
||||
// Jämkning: same schema-visibility caveat as växa-stöd above. What the
|
||||
// schema CAN see: a non-null percentage sent WITHOUT any start date in the
|
||||
// same body is only valid if a start date already exists on the row: the
|
||||
// route layer does the merged-state check. Within-body date ordering is
|
||||
// checkable here.
|
||||
if (
|
||||
data.jamkning_valid_from &&
|
||||
data.jamkning_valid_to &&
|
||||
data.jamkning_valid_to < data.jamkning_valid_from
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'Jämkningens slutdatum måste vara efter startdatumet',
|
||||
path: ['jamkning_valid_to'],
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export const EmployeeBenefitTypeSchema = z.enum(['bike', 'car', 'meals', 'housing', 'wellness', 'other'])
|
||||
@@ -2249,6 +2330,88 @@ export const AbsenceRangeQuerySchema = z.object({
|
||||
path: ['from'],
|
||||
})
|
||||
|
||||
// ── Employee opening balances (payroll cutover) ─────────────────────
|
||||
//
|
||||
// Per-employee state a mid-year switcher brings from the previous payroll
|
||||
// system: YTD accumulators, vacation balances (incl. sparade dagar by origin
|
||||
// year per the Semesterlagen 5-year rule), the opening semesterlöneskuld SEK
|
||||
// (feeds vacation-liability report only; the 2920/2940 balance arrived via
|
||||
// SIE), and the högriskskydd karens-count adjustment. See migration
|
||||
// 20260713101000.
|
||||
|
||||
const openingBalancesShape = {
|
||||
cutover_date: isoDate,
|
||||
ytd_gross: z.number().min(0).default(0),
|
||||
ytd_tax: z.number().min(0).default(0),
|
||||
ytd_net: z.number().min(0).default(0),
|
||||
vacation_paid_days_remaining: z.number().min(0).max(40).default(0),
|
||||
vacation_saved_days_by_year: z
|
||||
.record(z.string().regex(/^\d{4}$/, 'Nyckel måste vara ett fyrsiffrigt år'), z.number().min(0).max(40))
|
||||
.default({}),
|
||||
opening_semester_liability: z.number().min(0).default(0),
|
||||
opening_semester_liability_avgifter: z.number().min(0).default(0),
|
||||
karens_periods_adjustment: z.number().int().min(0).max(10).default(0),
|
||||
}
|
||||
|
||||
const openingBalancesRefine = (
|
||||
data: {
|
||||
cutover_date: string
|
||||
ytd_gross: number
|
||||
ytd_tax: number
|
||||
vacation_saved_days_by_year: Record<string, number>
|
||||
},
|
||||
ctx: z.RefinementCtx,
|
||||
) => {
|
||||
if (!data.cutover_date.endsWith('-01')) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'cutover_date måste vara den första dagen i en månad',
|
||||
path: ['cutover_date'],
|
||||
})
|
||||
}
|
||||
const cutoverYear = Number(data.cutover_date.slice(0, 4))
|
||||
const currentYear = new Date().getFullYear()
|
||||
if (cutoverYear < currentYear - 1 || cutoverYear > currentYear) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'cutover_date måste ligga i innevarande eller föregående år',
|
||||
path: ['cutover_date'],
|
||||
})
|
||||
}
|
||||
if (data.ytd_tax > data.ytd_gross) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'ytd_tax kan inte överstiga ytd_gross',
|
||||
path: ['ytd_tax'],
|
||||
})
|
||||
}
|
||||
// Sparade dagar: max 5 years back, never the cutover year itself.
|
||||
for (const yearKey of Object.keys(data.vacation_saved_days_by_year)) {
|
||||
const originYear = Number(yearKey)
|
||||
if (originYear < cutoverYear - 5 || originYear > cutoverYear - 1) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: `Sparade dagar för ${yearKey}: ursprungsåret måste ligga inom 5 år före cutover (${cutoverYear - 5}-${cutoverYear - 1})`,
|
||||
path: ['vacation_saved_days_by_year', yearKey],
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Body for the per-employee PUT (employee id comes from the path). */
|
||||
export const OpeningBalancesFieldsSchema = z
|
||||
.object(openingBalancesShape)
|
||||
.superRefine(openingBalancesRefine)
|
||||
|
||||
/** One item in the bulk PUT (employee id inline). */
|
||||
export const OpeningBalancesItemSchema = z
|
||||
.object({ employee_id: uuid, ...openingBalancesShape })
|
||||
.superRefine(openingBalancesRefine)
|
||||
|
||||
export const OpeningBalancesBulkSchema = z.object({
|
||||
items: z.array(OpeningBalancesItemSchema).min(1).max(200),
|
||||
})
|
||||
|
||||
// ── Worked-hours per-day records (hourly employees) ─────────────────
|
||||
//
|
||||
// Drives base salary calculation for hourly (timanställd) employees:
|
||||
|
||||
+17
-1
@@ -1,13 +1,16 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `107`;
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `123`;
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-keys 1`] = `
|
||||
[
|
||||
"DELETE /api/v1/companies/:companyId/customers/:id",
|
||||
"DELETE /api/v1/companies/:companyId/dimensions/:id/values/:valueId",
|
||||
"DELETE /api/v1/companies/:companyId/employees/:id",
|
||||
"DELETE /api/v1/companies/:companyId/employees/:id/absence",
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id",
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId",
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id/lines/:lineId",
|
||||
"DELETE /api/v1/companies/:companyId/suppliers/:id",
|
||||
"DELETE /api/v1/companies/:companyId/webhooks/:id",
|
||||
"GET /api/v1/companies",
|
||||
@@ -20,6 +23,9 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"GET /api/v1/companies/:companyId/documents/:id/download",
|
||||
"GET /api/v1/companies/:companyId/employees",
|
||||
"GET /api/v1/companies/:companyId/employees/:id",
|
||||
"GET /api/v1/companies/:companyId/employees/:id/absence",
|
||||
"GET /api/v1/companies/:companyId/employees/:id/opening-balances",
|
||||
"GET /api/v1/companies/:companyId/employees/:id/vacation-balance",
|
||||
"GET /api/v1/companies/:companyId/fiscal-periods",
|
||||
"GET /api/v1/companies/:companyId/invoices",
|
||||
"GET /api/v1/companies/:companyId/invoices/:id",
|
||||
@@ -43,6 +49,9 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"GET /api/v1/companies/:companyId/reports/vat-declaration",
|
||||
"GET /api/v1/companies/:companyId/salary-runs",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id/employees",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId",
|
||||
"GET /api/v1/companies/:companyId/salary-runs/:id/payslips/:employeeId/pdf",
|
||||
"GET /api/v1/companies/:companyId/supplier-invoices",
|
||||
"GET /api/v1/companies/:companyId/supplier-invoices/:id",
|
||||
"GET /api/v1/companies/:companyId/suppliers",
|
||||
@@ -59,6 +68,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"PATCH /api/v1/companies/:companyId/employees/:id",
|
||||
"PATCH /api/v1/companies/:companyId/invoices/:id",
|
||||
"PATCH /api/v1/companies/:companyId/salary-runs/:id",
|
||||
"PATCH /api/v1/companies/:companyId/salary-runs/:id/lines/:lineId",
|
||||
"PATCH /api/v1/companies/:companyId/supplier-invoices/:id",
|
||||
"PATCH /api/v1/companies/:companyId/suppliers/:id",
|
||||
"PATCH /api/v1/companies/:companyId/webhooks/:id",
|
||||
@@ -92,8 +102,11 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/approve",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/book",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/calculate",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/employees",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId/lines",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/generate-agi",
|
||||
"POST /api/v1/companies/:companyId/salary-runs/:id/mark-paid",
|
||||
"POST /api/v1/companies/:companyId/salary/vacation-year-close",
|
||||
"POST /api/v1/companies/:companyId/supplier-invoices",
|
||||
"POST /api/v1/companies/:companyId/supplier-invoices/:id/approve",
|
||||
"POST /api/v1/companies/:companyId/supplier-invoices/:id/credit",
|
||||
@@ -111,6 +124,9 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"POST /api/v1/companies/:companyId/webhooks/:id/rotate-secret",
|
||||
"POST /api/v1/companies/:companyId/webhooks/:id/test",
|
||||
"POST /api/v1/webhook-deliveries/:id/retry",
|
||||
"PUT /api/v1/companies/:companyId/employees/:id/absence",
|
||||
"PUT /api/v1/companies/:companyId/employees/:id/opening-balances",
|
||||
"PUT /api/v1/companies/:companyId/employees/opening-balances",
|
||||
]
|
||||
`;
|
||||
|
||||
|
||||
@@ -97,6 +97,26 @@ import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/mark-paid/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/book/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/generate-agi/route'
|
||||
|
||||
// Payroll gap-closure 1.1: per-employee payslip reads (list + detail + PDF).
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/employees/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/employees/[employeeId]/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/payslips/[employeeId]/pdf/route'
|
||||
|
||||
// Payroll gap-closure 1.2: payslip line writes (draft runs only).
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/employees/[employeeId]/lines/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary-runs/[id]/lines/[lineId]/route'
|
||||
|
||||
// Payroll gap-closure 1.4: absence (frånvaro) range endpoints.
|
||||
import '@/app/api/v1/companies/[companyId]/employees/[id]/absence/route'
|
||||
|
||||
// Payroll gap-closure 2.3: cutover opening balances (single + atomic bulk).
|
||||
import '@/app/api/v1/companies/[companyId]/employees/[id]/opening-balances/route'
|
||||
import '@/app/api/v1/companies/[companyId]/employees/opening-balances/route'
|
||||
|
||||
// Payroll gap-closure 3.4: vacation ledger + year close.
|
||||
import '@/app/api/v1/companies/[companyId]/employees/[id]/vacation-balance/route'
|
||||
import '@/app/api/v1/companies/[companyId]/salary/vacation-year-close/route'
|
||||
|
||||
// Phase 5 PR-3: Reports + import async. All reports wrap existing
|
||||
// lib/reports/* generators. Imports run inline today but record their
|
||||
// progress on the `operations` table for consistent polling-shape. KPI,
|
||||
|
||||
@@ -65,7 +65,11 @@ import { API_V1_VERSION, API_V1_VERSION_HEADER } from './version'
|
||||
|
||||
const IDEMPOTENCY_HEADER = 'Idempotency-Key'
|
||||
const DRY_RUN_HEADER = 'X-Dry-Run'
|
||||
const REQUIRES_IDEMPOTENCY = new Set(['POST', 'PATCH', 'DELETE'])
|
||||
// Every state-changing method. PUT is included even though most v1 writes are
|
||||
// POST/PATCH: the set drives THREE behaviors (test-key dry-run forcing,
|
||||
// idempotency replay, requireIdempotencyKey enforcement), and omitting PUT
|
||||
// would let test keys write through PUT routes for real.
|
||||
const REQUIRES_IDEMPOTENCY = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
|
||||
|
||||
export interface ApiV1Context {
|
||||
/** Stable id for this HTTP request: appears in logs, error envelope, X-Request-Id. */
|
||||
|
||||
@@ -102,7 +102,9 @@ export function withRouteContext<P extends DynamicParams = { params: Promise<Rec
|
||||
let errLog = log
|
||||
|
||||
try {
|
||||
const authStart = Date.now()
|
||||
const auth = await requireAuth()
|
||||
const authMs = Date.now() - authStart
|
||||
if (auth.error) {
|
||||
log.warn('auth failed', { status: auth.error.status })
|
||||
// Pass through requireAuth's response unchanged for backwards-compat
|
||||
@@ -119,11 +121,13 @@ export function withRouteContext<P extends DynamicParams = { params: Promise<Rec
|
||||
errLog = userLog
|
||||
|
||||
let companyId: string | null = null
|
||||
const companyStart = Date.now()
|
||||
try {
|
||||
companyId = await getActiveCompanyId(supabase, user.id)
|
||||
} catch (err) {
|
||||
userLog.error('failed to resolve active company', err as Error)
|
||||
}
|
||||
const companyMs = Date.now() - companyStart
|
||||
|
||||
if (!companyId) {
|
||||
return errorResponseFromCode('COMPANY_CONTEXT_MISSING', userLog, { requestId })
|
||||
@@ -152,15 +156,30 @@ export function withRouteContext<P extends DynamicParams = { params: Promise<Rec
|
||||
}
|
||||
errLog = ctx.log
|
||||
|
||||
const handlerStart = Date.now()
|
||||
const response = await handler(request, ctx, params)
|
||||
const handlerMs = Date.now() - handlerStart
|
||||
|
||||
if (response instanceof Response && !response.headers.get('X-Request-Id')) {
|
||||
response.headers.set('X-Request-Id', requestId)
|
||||
}
|
||||
// Per-phase breakdown, visible in browser devtools (Timing tab) and in
|
||||
// the op-completed log: separates the wrapper's own overhead (auth
|
||||
// round trip + company resolution) from the handler's real work, so
|
||||
// latency regressions can be attributed without guessing.
|
||||
if (response instanceof Response && !response.headers.get('Server-Timing')) {
|
||||
response.headers.set(
|
||||
'Server-Timing',
|
||||
`auth;dur=${authMs}, company;dur=${companyMs}, handler;dur=${handlerMs}`,
|
||||
)
|
||||
}
|
||||
|
||||
ctx.log.info('op completed', {
|
||||
durationMs: Date.now() - start,
|
||||
status: response.status,
|
||||
authMs,
|
||||
companyMs,
|
||||
handlerMs,
|
||||
})
|
||||
return response
|
||||
} catch (err) {
|
||||
|
||||
Reference in New Issue
Block a user