Fix/chrome pdf preview csp (#572)
* feat: add option to exclude year-end closing entries in SIE export and related reports * delete docs * fix: allow Chrome's PDF viewer in verifikat document preview The /api/documents/:id/inline route shipped with `object-src 'none'` in its CSP, which blocked Chrome's built-in PDF viewer (it renders inline PDFs via an internal <embed>). Users on Chrome saw "Det här innehållet har blockerats" when expanding a PDF attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own viewer) were unaffected, and JPGs worked because <img> isn't subject to object-src. Drops the CSP for this route to the minimum needed for embeddability: `frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the fixed Content-Type from the handler already block MIME confusion; X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(auth): add webmail deep link to email confirmation screens Mirrors Stripe's signup UX: after asking the user to verify their email, detect their webmail provider from the domain and show a button that opens the inbox in a new tab. Gmail gets a from:<sender> search pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly. Unknown / custom domains fall back to the existing copy. Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM (default noreply@gnubok.se) so white-label installs can match their Supabase Auth SMTP config. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(auth): unblock first-time password set for BankID users with MFA Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session is required" whenever a TOTP factor is enrolled. BankID magic-link logins produce AAL1, and middleware skips MFA enforcement for bankid_linked users, so they had no path to AAL2 — leaving them unable to set a backup password or disable MFA without going through the email-recovery escape hatch. - /api/account/password: branch on app_metadata.has_password. First-time set writes via service.auth.admin.updateUserById (no existing credential to protect, AAL2 guard does not apply). Change-password keeps the user-session updateUser so AAL2 still fires for credential rotation. - /mfa/verify: accept a safeReturnTo query param and route there after successful verify, so step-up flows can land back where they came from. - SecuritySettings: detect the AAL2 error from both change-password and mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account instead of toasting a dead-end error. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Add tests and rounding utility for öre precision in bokslut calculations - Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations. - Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries. - Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency. - Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies. - Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios. * fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility * fix: enhance security by rejecting data URIs in safeReturnTo function tests * fix: improve rounding logic in roundOre function and add customer_type migration * fix: add customer_type column to customers and enforce CHECK constraint --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
0087b7be3f
commit
32d9978f1b
@@ -12,8 +12,10 @@ import { POST } from '../route'
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
const mockCreateServiceClient = vi.mocked(createServiceClient)
|
||||
|
||||
type AuthMetadata = Record<string, unknown>
|
||||
|
||||
function mockUserClient(opts: {
|
||||
user: { id: string } | null
|
||||
user: { id: string; app_metadata?: AuthMetadata } | null
|
||||
updateUserError?: { message: string; status?: number; code?: string } | null
|
||||
}) {
|
||||
const updateUser = vi.fn().mockResolvedValue({
|
||||
@@ -33,12 +35,24 @@ function mockUserClient(opts: {
|
||||
}
|
||||
|
||||
function mockService(opts: {
|
||||
priorAppMetadata?: Record<string, unknown>
|
||||
updateUserByIdError?: Error | null
|
||||
priorAppMetadata?: AuthMetadata
|
||||
// Returned-error from admin.updateUserById when called with { password }
|
||||
passwordSetError?: { message: string; status?: number; code?: string } | null
|
||||
// Thrown error from admin.updateUserById when called with { app_metadata }
|
||||
flagFlipError?: Error | null
|
||||
}) {
|
||||
const updateUserById = opts.updateUserByIdError
|
||||
? vi.fn().mockRejectedValue(opts.updateUserByIdError)
|
||||
: vi.fn().mockResolvedValue({ data: {}, error: null })
|
||||
const updateUserById = vi
|
||||
.fn()
|
||||
.mockImplementation((_id: string, args: Record<string, unknown>) => {
|
||||
if ('password' in args) {
|
||||
return Promise.resolve({
|
||||
data: {},
|
||||
error: opts.passwordSetError ?? null,
|
||||
})
|
||||
}
|
||||
if (opts.flagFlipError) return Promise.reject(opts.flagFlipError)
|
||||
return Promise.resolve({ data: {}, error: null })
|
||||
})
|
||||
|
||||
const getUserById = vi.fn().mockResolvedValue({
|
||||
data: { user: { app_metadata: opts.priorAppMetadata ?? {} } },
|
||||
@@ -54,6 +68,18 @@ function mockService(opts: {
|
||||
|
||||
const STRONG_PASSWORD = 'StrongP@ssword1'
|
||||
|
||||
function flagFlipCall(updateUserById: ReturnType<typeof vi.fn>) {
|
||||
return updateUserById.mock.calls.find(
|
||||
([, args]) => args && typeof args === 'object' && 'app_metadata' in args,
|
||||
)
|
||||
}
|
||||
|
||||
function passwordSetCall(updateUserById: ReturnType<typeof vi.fn>) {
|
||||
return updateUserById.mock.calls.find(
|
||||
([, args]) => args && typeof args === 'object' && 'password' in args,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
@@ -72,8 +98,8 @@ describe('POST /api/account/password', () => {
|
||||
})
|
||||
|
||||
it('returns 400 when password is too weak', async () => {
|
||||
mockUserClient({ user: { id: 'user-1' } })
|
||||
mockService({})
|
||||
mockUserClient({ user: { id: 'user-1', app_metadata: { has_password: true } } })
|
||||
mockService({ priorAppMetadata: { has_password: true } })
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
@@ -83,65 +109,187 @@ describe('POST /api/account/password', () => {
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 when Supabase rejects the password update', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1' },
|
||||
updateUserError: { message: 'Password too similar to old', status: 400 },
|
||||
})
|
||||
const { updateUserById } = mockService({})
|
||||
describe('first-time set (has_password !== true)', () => {
|
||||
it('writes the password via admin API and flips the flag', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: {
|
||||
id: 'user-1',
|
||||
app_metadata: { has_password: false, bankid_linked: true },
|
||||
},
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: false, bankid_linked: true },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Password too similar')
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
// Flag should NOT be flipped on a failed password update
|
||||
expect(updateUserById).not.toHaveBeenCalled()
|
||||
})
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
it('flips app_metadata.has_password to true on success and preserves siblings', async () => {
|
||||
const { updateUser } = mockUserClient({ user: { id: 'user-1' } })
|
||||
const { getUserById, updateUserById } = mockService({
|
||||
priorAppMetadata: { bankid_linked: true, provider: 'email' },
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
// Did NOT go through the user session — that path would fail with AAL2.
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
// Password set via admin
|
||||
expect(passwordSetCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{ password: STRONG_PASSWORD },
|
||||
])
|
||||
// Flag flipped, siblings preserved
|
||||
expect(flagFlipCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{
|
||||
app_metadata: {
|
||||
has_password: true,
|
||||
bankid_linked: true,
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
it('treats unset has_password as first-time set', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1' /* no app_metadata */ },
|
||||
})
|
||||
const { updateUserById } = mockService({})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
expect(passwordSetCall(updateUserById)).toBeDefined()
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(getUserById).toHaveBeenCalledWith('user-1')
|
||||
expect(updateUserById).toHaveBeenCalledWith('user-1', {
|
||||
app_metadata: {
|
||||
bankid_linked: true,
|
||||
provider: 'email',
|
||||
has_password: true,
|
||||
},
|
||||
|
||||
it('returns 400 and skips flag flip when the admin password set fails', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: false } },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: false },
|
||||
passwordSetError: { message: 'Password too weak', status: 400 },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Password too weak')
|
||||
expect(updateUser).not.toHaveBeenCalled()
|
||||
expect(flagFlipCall(updateUserById)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('still returns success when the flag flip fails after admin password set', async () => {
|
||||
mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: false } },
|
||||
})
|
||||
mockService({
|
||||
priorAppMetadata: { has_password: false },
|
||||
flagFlipError: new Error('admin down'),
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('still returns success when the flag flip fails (password is set; logged)', async () => {
|
||||
mockUserClient({ user: { id: 'user-1' } })
|
||||
mockService({ updateUserByIdError: new Error('admin down') })
|
||||
describe('change-password (has_password === true)', () => {
|
||||
it('writes via the user session so Supabase enforces AAL2', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: true, provider: 'email' },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data?: { ok: boolean }
|
||||
}>(await POST(req))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
// Used user session, NOT admin API for the password itself
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(passwordSetCall(updateUserById)).toBeUndefined()
|
||||
// Flag is still flipped (idempotent) with siblings preserved
|
||||
expect(flagFlipCall(updateUserById)).toEqual([
|
||||
'user-1',
|
||||
{
|
||||
app_metadata: {
|
||||
has_password: true,
|
||||
provider: 'email',
|
||||
},
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('returns 400 and skips flag flip when Supabase rejects the password update', async () => {
|
||||
const { updateUser } = mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
updateUserError: { message: 'Password too similar to old', status: 400 },
|
||||
})
|
||||
const { updateUserById } = mockService({
|
||||
priorAppMetadata: { has_password: true },
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('Password too similar')
|
||||
expect(updateUser).toHaveBeenCalledWith({ password: STRONG_PASSWORD })
|
||||
expect(flagFlipCall(updateUserById)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('surfaces the AAL2 error verbatim so the client can step up via /mfa/verify', async () => {
|
||||
mockUserClient({
|
||||
user: { id: 'user-1', app_metadata: { has_password: true } },
|
||||
updateUserError: {
|
||||
message:
|
||||
'AAL2 session is required to update email or password when MFA is enabled',
|
||||
status: 422,
|
||||
},
|
||||
})
|
||||
mockService({ priorAppMetadata: { has_password: true } })
|
||||
|
||||
const req = createMockRequest('/api/account/password', {
|
||||
method: 'POST',
|
||||
body: { password: STRONG_PASSWORD },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error?: string }>(
|
||||
await POST(req),
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error).toContain('AAL2')
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data?: { ok: boolean } }>(
|
||||
await POST(req),
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data?.ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -23,12 +23,25 @@ const SetPasswordSchema = z.object({
|
||||
/**
|
||||
* POST /api/account/password
|
||||
*
|
||||
* Server-routed password set/change. Wraps `supabase.auth.updateUser({ password })`
|
||||
* on the user's own session, then flips `app_metadata.has_password = true` via the
|
||||
* service client (clients can't write app_metadata).
|
||||
* Server-routed password set/change, then flips `app_metadata.has_password =
|
||||
* true` via the service client (clients can't write app_metadata).
|
||||
*
|
||||
* Two paths depending on whether the user already has a real password:
|
||||
*
|
||||
* - First-time set (`app_metadata.has_password !== true`): write via the
|
||||
* admin API. BankID-only users — and legacy users whose `has_password`
|
||||
* flag was set to false by the backfill — sit at AAL1 with a TOTP factor
|
||||
* enrolled, and `updateUser` on the user session would be rejected with
|
||||
* "AAL2 session is required to update email or password when MFA is
|
||||
* enabled". Setting an initial password has no existing credential to
|
||||
* protect, so bypassing AAL2 is safe.
|
||||
*
|
||||
* - Change-password (`app_metadata.has_password === true`): write via the
|
||||
* user session so Supabase's AAL2 guard still fires. A stolen AAL1
|
||||
* cookie must not be able to rotate a known password.
|
||||
*
|
||||
* This route is the single write path for setting a password. SecuritySettings,
|
||||
* the reset-password page, and the new /account/set-password page all funnel
|
||||
* the reset-password page, and the /account/set-password page all funnel
|
||||
* through here so the flag stays in sync — see lib/auth/has-password.ts.
|
||||
*
|
||||
* If the password update succeeds but the flag write fails, we log and still
|
||||
@@ -49,11 +62,29 @@ export async function POST(request: Request) {
|
||||
if (!result.success) return result.response
|
||||
const { password } = result.data
|
||||
|
||||
const { error: updateError } = await supabase.auth.updateUser({ password })
|
||||
const isFirstTimeSet = user.app_metadata?.has_password !== true
|
||||
const service = createServiceClient()
|
||||
|
||||
let updateError:
|
||||
| { message?: string; status?: number; code?: string }
|
||||
| null
|
||||
| undefined = null
|
||||
|
||||
if (isFirstTimeSet) {
|
||||
const { error } = await service.auth.admin.updateUserById(user.id, {
|
||||
password,
|
||||
})
|
||||
updateError = error
|
||||
} else {
|
||||
const { error } = await supabase.auth.updateUser({ password })
|
||||
updateError = error
|
||||
}
|
||||
|
||||
if (updateError) {
|
||||
log.warn('updateUser({password}) failed', {
|
||||
log.warn('password update failed', {
|
||||
userId: user.id,
|
||||
code: (updateError as { code?: string }).code,
|
||||
isFirstTimeSet,
|
||||
code: updateError.code,
|
||||
status: updateError.status,
|
||||
})
|
||||
return NextResponse.json(
|
||||
@@ -69,7 +100,6 @@ export async function POST(request: Request) {
|
||||
// Read-merge-write so we don't wipe sibling app_metadata keys.
|
||||
// updateUserById replaces app_metadata wholesale (see lib/auth/has-password.ts
|
||||
// and the comment in app/api/account/delete/route.ts).
|
||||
const service = createServiceClient()
|
||||
let flagWriteOk = false
|
||||
try {
|
||||
const { data: u } = await service.auth.admin.getUserById(user.id)
|
||||
@@ -87,7 +117,7 @@ export async function POST(request: Request) {
|
||||
// banner will show once more and a retry will succeed.
|
||||
}
|
||||
|
||||
log.info('password set', { userId: user.id, flagWriteOk })
|
||||
log.info('password set', { userId: user.id, isFirstTimeSet, flagWriteOk })
|
||||
|
||||
return NextResponse.json({ data: { ok: true } })
|
||||
}
|
||||
|
||||
@@ -5,15 +5,87 @@ import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { disposeAsset } from '@/lib/bokslut/assets/asset-service'
|
||||
|
||||
const DisposeAssetSchema = z.object({
|
||||
disposed_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
disposed_proceeds: z.number().nonnegative(),
|
||||
proceeds_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
fiscal_period_id: z.string().uuid(),
|
||||
// accumulated_depreciation is intentionally NOT accepted from the client —
|
||||
// disposeAsset sums depreciation_schedules server-side so callers cannot
|
||||
// inflate the book-value calculation.
|
||||
})
|
||||
const VAT_TREATMENTS = [
|
||||
'standard_25',
|
||||
'reduced_12',
|
||||
'reduced_6',
|
||||
'reverse_charge',
|
||||
'export',
|
||||
'exempt',
|
||||
] as const
|
||||
|
||||
const DisposeAssetSchema = z
|
||||
.object({
|
||||
disposed_at: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
/** Gross proceeds (INCL VAT when applicable). */
|
||||
disposed_proceeds: z.number().nonnegative(),
|
||||
proceeds_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
fiscal_period_id: z.string().uuid(),
|
||||
/** Output VAT on the proceeds. Defaults to 0 (sale was momsfri). */
|
||||
proceeds_vat: z.number().nonnegative().optional(),
|
||||
/** Required when proceeds_vat > 0 so the engine can resolve a 26xx account. */
|
||||
vat_treatment: z.enum(VAT_TREATMENTS).optional(),
|
||||
/** Precomputed jämkning amount (ML 8a kap 7 §). Caller supplies; engine
|
||||
* books a 2641 credit + loss-account debit. */
|
||||
jamkning_amount: z.number().nonnegative().optional(),
|
||||
/** Audit metadata. */
|
||||
jamkning_remaining_months: z.number().int().nonnegative().optional(),
|
||||
jamkning_total_months: z.number().int().positive().optional(),
|
||||
jamkning_original_input_vat: z.number().nonnegative().optional(),
|
||||
// accumulated_depreciation is intentionally NOT accepted from the client —
|
||||
// disposeAsset sums depreciation_schedules server-side so callers cannot
|
||||
// inflate the book-value calculation.
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
// VAT consistency: if a treatment that produces a VAT line is selected,
|
||||
// the VAT amount must equal 25%/12%/6% of the net proceeds. Tolerance is
|
||||
// ±0.50 kr to handle rounding on item prices.
|
||||
if (value.proceeds_vat && value.proceeds_vat > 0) {
|
||||
if (!value.vat_treatment) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['vat_treatment'],
|
||||
message: 'vat_treatment krävs när proceeds_vat > 0.',
|
||||
})
|
||||
return
|
||||
}
|
||||
const rate = vatRateFromTreatment(value.vat_treatment)
|
||||
if (rate === null) {
|
||||
// Treatments without a VAT line must carry 0 VAT.
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['proceeds_vat'],
|
||||
message: `proceeds_vat måste vara 0 för momsbehandling "${value.vat_treatment}".`,
|
||||
})
|
||||
return
|
||||
}
|
||||
// Expected: proceeds_gross = net × (1 + rate), so net = gross / (1 + rate)
|
||||
// and vat = gross - net = gross × rate / (1 + rate).
|
||||
const expectedVat = (value.disposed_proceeds * rate) / (1 + rate)
|
||||
if (Math.abs(expectedVat - value.proceeds_vat) > 0.5) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['proceeds_vat'],
|
||||
message: `proceeds_vat ska vara ~${Math.round(expectedVat * 100) / 100} kr för momsbehandling "${value.vat_treatment}" på ${value.disposed_proceeds} kr brutto.`,
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function vatRateFromTreatment(t: (typeof VAT_TREATMENTS)[number]): number | null {
|
||||
switch (t) {
|
||||
case 'standard_25':
|
||||
return 0.25
|
||||
case 'reduced_12':
|
||||
return 0.12
|
||||
case 'reduced_6':
|
||||
return 0.06
|
||||
case 'reverse_charge':
|
||||
case 'export':
|
||||
case 'exempt':
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'assets.dispose',
|
||||
|
||||
@@ -3,40 +3,66 @@ import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { K3ComponentSchema } from '@/lib/api/schemas'
|
||||
import { getAsset, updateAsset } from '@/lib/bokslut/assets/asset-service'
|
||||
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
|
||||
import type { DepreciationMethod } from '@/types'
|
||||
|
||||
const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [
|
||||
'linear',
|
||||
'declining_balance_30',
|
||||
'declining_balance_20',
|
||||
'restvardesavskrivning_25',
|
||||
] as const
|
||||
|
||||
// Engine only implements linear today — reject declining_balance methods on
|
||||
// both create and update until the engine grows them. The DB enum keeps the
|
||||
// other methods reserved for a future phase.
|
||||
const SUPPORTED_DEPRECIATION_METHODS: readonly DepreciationMethod[] = ['linear'] as const
|
||||
const UpdateAssetSchema = z
|
||||
.object({
|
||||
name: z.string().min(1).optional(),
|
||||
notes: z.string().nullable().optional(),
|
||||
salvage_value: z.number().nonnegative().optional(),
|
||||
useful_life_months: z.number().int().positive().optional(),
|
||||
depreciation_method: z
|
||||
.enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]])
|
||||
.optional(),
|
||||
restvarde_target: z.number().nonnegative().nullable().optional(),
|
||||
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
// K3 component depreciation. Accepting `null` lets the caller clear an
|
||||
// existing breakdown (the engine then falls back to depreciation_method).
|
||||
// Per-component validation runs whenever the field is set to a non-null
|
||||
// value; the cross-sum check needs acquisition_cost so it's deferred to
|
||||
// updateAsset() which can read the existing row.
|
||||
k3_components: z.array(K3ComponentSchema).nullable().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
// Enforce the method/target biconditional when EITHER field is supplied.
|
||||
// We can't see the existing row from a zod refinement, so the
|
||||
// application-level updateAsset() carries the cross-row check; here we
|
||||
// only catch the obviously inconsistent combinations within a single
|
||||
// PATCH body.
|
||||
const hasMethod = value.depreciation_method !== undefined
|
||||
const hasTarget = value.restvarde_target !== undefined
|
||||
if (!hasMethod && !hasTarget) return
|
||||
|
||||
const UpdateAssetSchema = z.object({
|
||||
name: z.string().min(1).optional(),
|
||||
notes: z.string().nullable().optional(),
|
||||
salvage_value: z.number().nonnegative().optional(),
|
||||
useful_life_months: z.number().int().positive().optional(),
|
||||
depreciation_method: z
|
||||
.enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]])
|
||||
.optional()
|
||||
.refine(
|
||||
(m) => m === undefined || (SUPPORTED_DEPRECIATION_METHODS as readonly string[]).includes(m),
|
||||
{
|
||||
message:
|
||||
'Only "linear" depreciation is supported by the engine today. ' +
|
||||
'Declining-balance methods are reserved for a future phase.',
|
||||
},
|
||||
),
|
||||
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
})
|
||||
const isRestvarde = value.depreciation_method === 'restvardesavskrivning_25'
|
||||
const targetIsSet = value.restvarde_target !== null && value.restvarde_target !== undefined
|
||||
|
||||
if (hasMethod && isRestvarde && hasTarget && !targetIsSet) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target krävs när avskrivningsmetoden är restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
if (hasMethod && !isRestvarde && hasTarget && targetIsSet) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target får bara anges för restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'assets.get',
|
||||
@@ -62,6 +88,51 @@ export const PATCH = withRouteContext(
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
const validation = await validateBody(request, UpdateAssetSchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
// K3 component depreciation gating + cross-sum check.
|
||||
// The Zod refinement cannot see the existing asset's acquisition_cost,
|
||||
// so we do both the framework check and the sum validation here at
|
||||
// route level before delegating to updateAsset().
|
||||
if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) {
|
||||
const [{ data: company }, existing] = await Promise.all([
|
||||
supabase
|
||||
.from('companies')
|
||||
.select('accounting_framework')
|
||||
.eq('id', companyId)
|
||||
.single(),
|
||||
getAsset(supabase, companyId, id),
|
||||
])
|
||||
if (!company || company.accounting_framework !== 'k3') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'K3_REQUIRED_FOR_COMPONENTS',
|
||||
message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).',
|
||||
},
|
||||
},
|
||||
{ status: 422 },
|
||||
)
|
||||
}
|
||||
if (!existing) {
|
||||
return NextResponse.json({ error: { code: 'ASSET_NOT_FOUND' } }, { status: 404 })
|
||||
}
|
||||
const { errors } = validateComponents({
|
||||
acquisition_cost: Number(existing.acquisition_cost),
|
||||
k3_components: validation.data.k3_components,
|
||||
})
|
||||
if (errors.length > 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'INVALID_K3_COMPONENTS',
|
||||
message: errors.join(' '),
|
||||
},
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const asset = await updateAsset(supabase, companyId, id, validation.data)
|
||||
return NextResponse.json({ data: asset })
|
||||
|
||||
+102
-15
@@ -3,7 +3,9 @@ import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { K3ComponentSchema } from '@/lib/api/schemas'
|
||||
import { createAsset, listAssets } from '@/lib/bokslut/assets/asset-service'
|
||||
import { validateComponents } from '@/lib/bokslut/assets/k3-components'
|
||||
import type { AssetCategory, DepreciationMethod } from '@/types'
|
||||
|
||||
const ASSET_CATEGORIES: readonly AssetCategory[] = [
|
||||
@@ -17,18 +19,16 @@ const ASSET_CATEGORIES: readonly AssetCategory[] = [
|
||||
'other_tangible',
|
||||
] as const
|
||||
|
||||
// The DB enum keeps all three methods so future phases can add support
|
||||
// without a migration, but the engine only implements linear today. Reject
|
||||
// the unsupported methods at create to avoid silently producing wrong
|
||||
// (linear) numbers under a misleading method label.
|
||||
// All four depreciation methods are now implemented by the engine. The DB
|
||||
// CHECK constraint mirrors this list (see
|
||||
// 20260526120100_restvardeavskrivning.sql).
|
||||
const DEPRECIATION_METHODS: readonly DepreciationMethod[] = [
|
||||
'linear',
|
||||
'declining_balance_30',
|
||||
'declining_balance_20',
|
||||
'restvardesavskrivning_25',
|
||||
] as const
|
||||
|
||||
const SUPPORTED_DEPRECIATION_METHODS: readonly DepreciationMethod[] = ['linear'] as const
|
||||
|
||||
const CreateAssetSchema = z
|
||||
.object({
|
||||
name: z.string().min(1),
|
||||
@@ -41,18 +41,21 @@ const CreateAssetSchema = z
|
||||
useful_life_months: z.number().int().positive(),
|
||||
depreciation_method: z
|
||||
.enum(DEPRECIATION_METHODS as unknown as [DepreciationMethod, ...DepreciationMethod[]])
|
||||
.optional()
|
||||
.refine(
|
||||
(m) => m === undefined || (SUPPORTED_DEPRECIATION_METHODS as readonly string[]).includes(m),
|
||||
{
|
||||
message:
|
||||
'Only "linear" depreciation is supported by the engine today. ' +
|
||||
'Declining-balance methods are reserved for a future phase.',
|
||||
},
|
||||
),
|
||||
.optional(),
|
||||
// Restvärde-target floor for restvärdeavskrivning. Required iff
|
||||
// depreciation_method = 'restvardesavskrivning_25'. The DB CHECK enforces
|
||||
// the same biconditional; we mirror it in the API for an early, Swedish
|
||||
// error message rather than a Postgres check_violation surfacing.
|
||||
restvarde_target: z.number().nonnegative().nullable().optional(),
|
||||
bas_asset_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_accumulated_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
bas_expense_account: z.string().regex(/^\d{4}$/).optional(),
|
||||
// K3 component depreciation (BFNAR 2012:1 ch.17.4). Only meaningful for
|
||||
// companies with accounting_framework='k3' — the route handler rejects
|
||||
// K3_REQUIRED_FOR_COMPONENTS for K2 companies. When present, the engine
|
||||
// dispatches to per-component linear depreciation instead of the
|
||||
// asset-level depreciation_method.
|
||||
k3_components: z.array(K3ComponentSchema).nullable().optional(),
|
||||
notes: z.string().optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
@@ -60,8 +63,70 @@ const CreateAssetSchema = z
|
||||
// outside the legitimate range for the asset category so the chart stays
|
||||
// BAS-aligned and INK2R mappings continue to work.
|
||||
validateBasOverrides(value, ctx)
|
||||
validateRestvardeTarget(value, ctx)
|
||||
validateK3Components(value, ctx)
|
||||
})
|
||||
|
||||
function validateK3Components(
|
||||
value: {
|
||||
acquisition_cost: number
|
||||
k3_components?: { name: string; cost: number; useful_life_months: number; salvage_value?: number }[] | null
|
||||
},
|
||||
ctx: z.RefinementCtx,
|
||||
): void {
|
||||
if (value.k3_components === undefined || value.k3_components === null) return
|
||||
const { errors } = validateComponents({
|
||||
acquisition_cost: value.acquisition_cost,
|
||||
k3_components: value.k3_components,
|
||||
})
|
||||
for (const message of errors) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['k3_components'],
|
||||
message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function validateRestvardeTarget(
|
||||
value: {
|
||||
depreciation_method?: DepreciationMethod
|
||||
restvarde_target?: number | null
|
||||
acquisition_cost?: number
|
||||
},
|
||||
ctx: z.RefinementCtx,
|
||||
): void {
|
||||
const isRestvarde = value.depreciation_method === 'restvardesavskrivning_25'
|
||||
const hasTarget = value.restvarde_target !== undefined && value.restvarde_target !== null
|
||||
if (isRestvarde && !hasTarget) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target krävs när avskrivningsmetoden är restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
if (!isRestvarde && hasTarget) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message: 'restvarde_target får bara anges för restvärdeavskrivning (25 %).',
|
||||
})
|
||||
}
|
||||
if (
|
||||
isRestvarde &&
|
||||
hasTarget &&
|
||||
value.acquisition_cost !== undefined &&
|
||||
(value.restvarde_target as number) >= value.acquisition_cost
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ['restvarde_target'],
|
||||
message:
|
||||
'restvarde_target måste vara lägre än anskaffningsvärdet — annars finns inget kvar att skriva av.',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function validateBasOverrides(
|
||||
value: {
|
||||
category: AssetCategory
|
||||
@@ -151,6 +216,28 @@ export const POST = withRouteContext(
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
const validation = await validateBody(request, CreateAssetSchema)
|
||||
if (!validation.success) return validation.response
|
||||
// K3_REQUIRED_FOR_COMPONENTS: K3 component depreciation is only
|
||||
// meaningful when the company applies the K3 framework. Reject the
|
||||
// write with 422 (Unprocessable Entity) rather than silently dropping
|
||||
// the field so the user knows their input was discarded.
|
||||
if (validation.data.k3_components !== undefined && validation.data.k3_components !== null) {
|
||||
const { data: company } = await supabase
|
||||
.from('companies')
|
||||
.select('accounting_framework')
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
if (!company || company.accounting_framework !== 'k3') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'K3_REQUIRED_FOR_COMPONENTS',
|
||||
message: 'Komponentuppdelning (k3_components) kräver att företaget tillämpar K3 (BFNAR 2012:1).',
|
||||
},
|
||||
},
|
||||
{ status: 422 },
|
||||
)
|
||||
}
|
||||
}
|
||||
try {
|
||||
const asset = await createAsset(supabase, companyId, user.id, validation.data)
|
||||
return NextResponse.json({ data: asset })
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const mockCreateClient = vi.fn()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => mockCreateClient(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
const mockBuildAccrualsProposal = vi.fn()
|
||||
const mockDetectPeriodisering = vi.fn()
|
||||
vi.mock('@/lib/bokslut/accruals/accrual-detector', async () => {
|
||||
const actual =
|
||||
(await vi.importActual('@/lib/bokslut/accruals/accrual-detector')) as Record<string, unknown>
|
||||
return {
|
||||
...actual,
|
||||
buildAccrualsProposal: (...args: unknown[]) => mockBuildAccrualsProposal(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/bokslut/accruals/auto-detect', () => ({
|
||||
detectPeriodisering: (...args: unknown[]) => mockDetectPeriodisering(...args),
|
||||
}))
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: mockUser } }) },
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/bookkeeping/fiscal-periods/[id]/accruals', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: { getUser: vi.fn().mockResolvedValue({ data: { user: null } }) },
|
||||
})
|
||||
const { GET } = await import('../route')
|
||||
const res = await GET(
|
||||
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
|
||||
createMockRouteParams({ id: 'period-1' }),
|
||||
)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns the snapshot plus autoDetected suggestions', async () => {
|
||||
mockBuildAccrualsProposal.mockResolvedValue({
|
||||
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
|
||||
proposals: [],
|
||||
})
|
||||
mockDetectPeriodisering.mockResolvedValue([
|
||||
{
|
||||
source_invoice_id: 'sup-1',
|
||||
source_type: 'supplier_invoice',
|
||||
original_amount: 12000,
|
||||
periodisering_amount: 6000,
|
||||
parsed_start: '2025-07-01',
|
||||
parsed_end: '2026-06-30',
|
||||
confidence: 'high',
|
||||
reason: 'Mock reason',
|
||||
source_label: 'Test Supplier',
|
||||
suggested_prepaid_account: '1710',
|
||||
suggested_deferred_account: null,
|
||||
},
|
||||
])
|
||||
const { GET } = await import('../route')
|
||||
const res = await GET(
|
||||
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
|
||||
createMockRouteParams({ id: 'period-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.autoDetected).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('still returns the snapshot when auto-detect throws', async () => {
|
||||
mockBuildAccrualsProposal.mockResolvedValue({
|
||||
fiscalPeriod: { id: 'period-1', name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
|
||||
proposals: [],
|
||||
})
|
||||
mockDetectPeriodisering.mockRejectedValue(new Error('boom'))
|
||||
const { GET } = await import('../route')
|
||||
const res = await GET(
|
||||
createMockRequest('/api/bookkeeping/fiscal-periods/period-1/accruals'),
|
||||
createMockRouteParams({ id: 'period-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: { autoDetected: unknown[] } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.autoDetected).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -6,11 +6,15 @@ import { validateBody } from '@/lib/api/validate'
|
||||
import { createJournalEntry } from '@/lib/bookkeeping/engine'
|
||||
import {
|
||||
buildAccrualsProposal,
|
||||
proposeAccruedInterest,
|
||||
proposeAccruedUtility,
|
||||
proposeAuditFee,
|
||||
proposeManualAccrued,
|
||||
proposeManualPrepaid,
|
||||
proposeRevenueDeferral,
|
||||
proposeVacationLiabilityChange,
|
||||
} from '@/lib/bokslut/accruals/accrual-detector'
|
||||
import { detectPeriodisering } from '@/lib/bokslut/accruals/auto-detect'
|
||||
import type { AccrualProposal } from '@/lib/bokslut/accruals/types'
|
||||
import type { JournalEntry } from '@/types'
|
||||
|
||||
@@ -20,8 +24,18 @@ export const GET = withRouteContext(
|
||||
const { id } = await params
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
try {
|
||||
const proposal = await buildAccrualsProposal(supabase, companyId, id)
|
||||
return NextResponse.json({ data: proposal })
|
||||
// Run the two independent scans in parallel so the wizard's first
|
||||
// paint isn't gated on the slower auto-detect query.
|
||||
const [proposal, autoDetected] = await Promise.all([
|
||||
buildAccrualsProposal(supabase, companyId, id),
|
||||
detectPeriodisering(supabase, companyId, id).catch((err) => {
|
||||
// Auto-detect is best-effort — a malformed invoice description
|
||||
// shouldn't break the rest of the preflight. Log + return empty.
|
||||
log.warn('auto-detect failed', { error: (err as Error)?.message })
|
||||
return []
|
||||
}),
|
||||
])
|
||||
return NextResponse.json({ data: { ...proposal, autoDetected } })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : ''
|
||||
if (/not found/i.test(message)) {
|
||||
@@ -32,6 +46,19 @@ export const GET = withRouteContext(
|
||||
},
|
||||
)
|
||||
|
||||
// Defense-in-depth on caller-supplied account numbers. The wizard sends
|
||||
// accounts from a closed template list, but the API accepts them as plain
|
||||
// strings so we constrain the BAS class per accrual kind:
|
||||
// - cost accounts (5xxx-8xxx) for expense legs
|
||||
// - revenue accounts (3xxx) for revenue legs
|
||||
// - 17xx for förutbetalda kostnader (prepaid)
|
||||
// - 29xx for upplupna poster (accrued / deferred)
|
||||
// Anything outside these ranges is rejected with 400 before reaching the
|
||||
// engine — keeps a compromised browser session from posting arbitrary
|
||||
// balance-sheet hits.
|
||||
const EXPENSE_ACCOUNT_RE = /^[5-8]\d{3}$/
|
||||
const REVENUE_ACCOUNT_RE = /^3\d{3}$/
|
||||
|
||||
const PostItemSchema = z.discriminatedUnion('kind', [
|
||||
z.object({ kind: z.literal('vacation_liability_change') }),
|
||||
z.object({
|
||||
@@ -42,14 +69,35 @@ const PostItemSchema = z.discriminatedUnion('kind', [
|
||||
z.object({
|
||||
kind: z.literal('manual_prepaid_expense'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(/^\d{4}$/),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
prepaid_account: z.string().regex(/^17\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('manual_accrued_expense'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(/^\d{4}$/),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
accrued_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('deferred_revenue'),
|
||||
amount: z.number().positive(),
|
||||
revenue_account: z.string().regex(REVENUE_ACCOUNT_RE),
|
||||
deferred_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('accrued_interest'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
accrued_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
z.object({
|
||||
kind: z.literal('accrued_utility'),
|
||||
amount: z.number().positive(),
|
||||
expense_account: z.string().regex(EXPENSE_ACCOUNT_RE),
|
||||
accrued_account: z.string().regex(/^29\d{2}$/),
|
||||
description: z.string().min(1),
|
||||
}),
|
||||
@@ -132,6 +180,33 @@ export const POST = withRouteContext(
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
case 'deferred_revenue':
|
||||
proposal = proposeRevenueDeferral({
|
||||
amount: item.amount,
|
||||
revenueAccount: item.revenue_account,
|
||||
deferredAccount: item.deferred_account,
|
||||
description: item.description,
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
case 'accrued_interest':
|
||||
proposal = proposeAccruedInterest({
|
||||
amount: item.amount,
|
||||
expenseAccount: item.expense_account,
|
||||
accruedAccount: item.accrued_account,
|
||||
description: item.description,
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
case 'accrued_utility':
|
||||
proposal = proposeAccruedUtility({
|
||||
amount: item.amount,
|
||||
expenseAccount: item.expense_account,
|
||||
accruedAccount: item.accrued_account,
|
||||
description: item.description,
|
||||
closingDate: period.period_end,
|
||||
})
|
||||
break
|
||||
}
|
||||
if (!proposal) continue
|
||||
|
||||
@@ -199,6 +274,15 @@ async function findExistingAccrualEntry(
|
||||
case 'manual_accrued_expense':
|
||||
pattern = `Periodisering: Upplupen kostnad: ${escapeLike(item.description)}%`
|
||||
break
|
||||
case 'deferred_revenue':
|
||||
pattern = `Periodisering: Förutbetald intäkt: ${escapeLike(item.description)}%`
|
||||
break
|
||||
case 'accrued_interest':
|
||||
pattern = `Periodisering: Upplupen ränta: ${escapeLike(item.description)}%`
|
||||
break
|
||||
case 'accrued_utility':
|
||||
pattern = `Periodisering: Upplupen förbrukning: ${escapeLike(item.description)}%`
|
||||
break
|
||||
}
|
||||
|
||||
const { data } = await supabase
|
||||
|
||||
@@ -3,6 +3,7 @@ import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { buildArsredovisningData } from '@/lib/bokslut/arsredovisning/build-data'
|
||||
import { ArsredovisningPDF } from '@/lib/bokslut/arsredovisning/arsredovisning-pdf'
|
||||
import { ArsredovisningK3PDF } from '@/lib/bokslut/arsredovisning/arsredovisning-k3-pdf'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'period.arsredovisning_pdf',
|
||||
@@ -14,7 +15,15 @@ export const GET = withRouteContext(
|
||||
// inside buildArsredovisningData. The URL stays clean — no narrative
|
||||
// text in query params, access logs, or browser history.
|
||||
const data = await buildArsredovisningData(supabase, companyId, id)
|
||||
const pdfBuffer = await renderToBuffer(ArsredovisningPDF({ data }))
|
||||
// Dispatch on the framework recorded in the data. K3 documents need
|
||||
// the additional kassaflöde + equity-changes pages + richer noter
|
||||
// that ArsredovisningK3PDF renders. K2 (the default) keeps the
|
||||
// existing template byte-for-byte unchanged.
|
||||
const PdfComponent =
|
||||
data.accounting_framework === 'k3'
|
||||
? ArsredovisningK3PDF
|
||||
: ArsredovisningPDF
|
||||
const pdfBuffer = await renderToBuffer(PdfComponent({ data }))
|
||||
// "-utkast" suffix mirrors the existing PDF routes; the file becomes
|
||||
// "fastställd" only after the signature flow records all signatures.
|
||||
// Sanitize the dynamic segment so a stray quote / newline in the date
|
||||
|
||||
@@ -13,7 +13,10 @@ import {
|
||||
} from '@/lib/bokslut/reserves/periodiseringsfond-service'
|
||||
import { proposeOveravskrivningar } from '@/lib/bokslut/reserves/overavskrivningar-service'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
import { buildDispositionsProposal } from '@/lib/bokslut/dispositions-proposal-builder'
|
||||
import {
|
||||
buildDispositionsProposal,
|
||||
buildLatentTaxProposal,
|
||||
} from '@/lib/bokslut/dispositions-proposal-builder'
|
||||
import type { ProposedDisposition } from '@/lib/bokslut/types'
|
||||
import type { JournalEntry } from '@/types'
|
||||
|
||||
@@ -45,6 +48,9 @@ const DISPOSITION_ORDER: Record<string, number> = {
|
||||
periodiseringsfond_avsattning: 2,
|
||||
sarskild_loneskatt: 3,
|
||||
bolagsskatt: 4,
|
||||
// K3 only — posts last because it depends on the closing 21xx balance,
|
||||
// which only stabilises once avsättning / återföring have been applied.
|
||||
uppskjuten_skatt: 5,
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
@@ -112,6 +118,11 @@ const ItemSchema = z.discriminatedUnion('kind', [
|
||||
.enum(['machinery_equipment', 'building', 'immaterial', 'group'])
|
||||
.optional(),
|
||||
}),
|
||||
// K3 only — uppskjuten skatt provision. Server recomputes the amount from
|
||||
// current 2240 + 21xx state so the client cannot override it.
|
||||
z.object({
|
||||
kind: z.literal('uppskjuten_skatt'),
|
||||
}),
|
||||
])
|
||||
|
||||
const PostBodySchema = z.object({
|
||||
@@ -260,6 +271,15 @@ async function computeProposal(
|
||||
additionalAmount: item.additionalAmount,
|
||||
category: item.category,
|
||||
})
|
||||
case 'uppskjuten_skatt':
|
||||
// Server-only: recompute from current TB (which already reflects any
|
||||
// 21xx postings that committed earlier in this batch). The client
|
||||
// sends no amount — the calculator owns the K3 split.
|
||||
return buildLatentTaxProposal({
|
||||
supabase,
|
||||
companyId,
|
||||
fiscalPeriodId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,10 @@ export async function GET(request: Request) {
|
||||
const dateFrom = searchParams.get('date_from')
|
||||
const dateTo = searchParams.get('date_to')
|
||||
const sortDate = searchParams.get('sort_date') // 'asc' | 'desc'
|
||||
// 'series' optional filter — single uppercase letter A–Z. Ignored if any
|
||||
// other value is passed (defense against trivial injection / typos).
|
||||
const seriesRaw = searchParams.get('series')
|
||||
const seriesFilter = seriesRaw && /^[A-Z]$/.test(seriesRaw) ? seriesRaw : null
|
||||
// 'date_desc' (default) | 'date_asc' | 'voucher_asc' | 'voucher_desc'
|
||||
// sort_by overrides sort_date when present. sort_date is kept for backwards
|
||||
// compatibility with older clients.
|
||||
@@ -69,8 +73,18 @@ export async function GET(request: Request) {
|
||||
}
|
||||
|
||||
const rows = data ?? []
|
||||
const entries = rows.map((r: { entry: unknown }) => r.entry)
|
||||
const count = rows.length > 0 ? Number((rows[0] as { total_count: number | string }).total_count) : 0
|
||||
let entries = rows.map((r: { entry: unknown }) => r.entry) as Array<{ voucher_series?: string }>
|
||||
let count = rows.length > 0 ? Number((rows[0] as { total_count: number | string }).total_count) : 0
|
||||
|
||||
// The list_fiscal_period_entries_with_related RPC doesn't accept a series
|
||||
// filter, so post-filter here. Recompute count from the filtered set so
|
||||
// the paginator stays consistent; consequence: when a series filter is
|
||||
// applied, the cross-period follow-up surfacing is still on but the
|
||||
// visible total drops to the matching subset.
|
||||
if (seriesFilter) {
|
||||
entries = entries.filter((e) => (e?.voucher_series ?? 'A') === seriesFilter)
|
||||
count = entries.length
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: entries, count })
|
||||
}
|
||||
@@ -115,6 +129,10 @@ export async function GET(request: Request) {
|
||||
query = query.lte('entry_date', dateTo)
|
||||
}
|
||||
|
||||
if (seriesFilter) {
|
||||
query = query.eq('voucher_series', seriesFilter)
|
||||
}
|
||||
|
||||
const { data, error, count } = await query
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { getActiveCompanyId, requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { AccountingFrameworkSchema } from '@/lib/api/schemas'
|
||||
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
|
||||
const log = createLogger('api/company/current')
|
||||
|
||||
// BAS 2026 accounts required for K3's uppskjuten skatt (latent tax) entries.
|
||||
// Both rows carry k2_excluded=true in lib/bookkeeping/bas-data so they are
|
||||
// NOT seeded by seed_chart_of_accounts() for K2 companies. When a company
|
||||
// opts into K3 we backfill them here so the engine can resolve them by
|
||||
// account_number when the first latent-tax entry is posted.
|
||||
const K3_LATENT_TAX_ACCOUNTS = ['2240', '8940'] as const
|
||||
|
||||
/**
|
||||
* GET /api/company/current
|
||||
@@ -34,3 +49,143 @@ export async function GET() {
|
||||
{ headers: { 'Cache-Control': 'private, no-store' } },
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Body shape for PATCH /api/company/current.
|
||||
*
|
||||
* Currently only carries `accounting_framework` (K2 / K3). Adding more
|
||||
* companies-level fields here is fine but anything that belongs on
|
||||
* company_settings should go to /api/settings instead.
|
||||
*/
|
||||
const PatchBodySchema = z.object({
|
||||
accounting_framework: AccountingFrameworkSchema.optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* PATCH /api/company/current
|
||||
*
|
||||
* Updates company-level fields (in the `companies` table) for the active
|
||||
* company. Separate from /api/settings (which writes to `company_settings`)
|
||||
* because the columns live on different tables.
|
||||
*
|
||||
* Currently scoped to `accounting_framework` (K2 / K3) — only meaningful for
|
||||
* entity_type='aktiebolag'. The handler rejects K3 for non-AB to prevent
|
||||
* impossible chart-of-accounts states downstream.
|
||||
*/
|
||||
export async function PATCH(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const validation = await validateBody(request, PatchBodySchema)
|
||||
if (!validation.success) return validation.response
|
||||
|
||||
const updates: Record<string, unknown> = {}
|
||||
|
||||
if (validation.data.accounting_framework !== undefined) {
|
||||
// Only AB can opt in to K3 — EF stays on the simpler EF rules and never
|
||||
// touches K2/K3. Fetch the entity_type before applying.
|
||||
const { data: company } = await supabase
|
||||
.from('companies')
|
||||
.select('entity_type')
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
if (!company) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Företaget kunde inte hittas' },
|
||||
{ status: 404 },
|
||||
)
|
||||
}
|
||||
if (
|
||||
validation.data.accounting_framework === 'k3'
|
||||
&& company.entity_type !== 'aktiebolag'
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: 'K3 (BFNAR 2012:1) gäller endast aktiebolag.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
updates.accounting_framework = validation.data.accounting_framework
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length === 0) {
|
||||
// Nothing to write — surface the current row so the client can refresh
|
||||
// its local state without a no-op write.
|
||||
const { data } = await supabase
|
||||
.from('companies')
|
||||
.select('id, accounting_framework, entity_type')
|
||||
.eq('id', companyId)
|
||||
.single()
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('companies')
|
||||
.update(updates)
|
||||
.eq('id', companyId)
|
||||
.select('id, accounting_framework, entity_type')
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// When opting in to K3, ensure the two latent-tax (uppskjuten skatt)
|
||||
// accounts exist in the company's chart of accounts. The base seed skips
|
||||
// them for K2 companies via k2_excluded=true, so without this backfill
|
||||
// the engine cannot resolve account_id for the first latent-tax post.
|
||||
// Wrapped in try/catch so a CoA insert failure does not block the
|
||||
// framework update — the user can still re-trigger the seed later.
|
||||
// The reverse switch (K3 → K2) intentionally keeps the rows for audit
|
||||
// history; the legal record of past K3 postings must remain intact.
|
||||
if (data.accounting_framework === 'k3') {
|
||||
try {
|
||||
const rows = K3_LATENT_TAX_ACCOUNTS.map(accountNumber => {
|
||||
const basRef = getBASReference(accountNumber)
|
||||
if (!basRef) return null
|
||||
return {
|
||||
user_id: user.id,
|
||||
company_id: companyId,
|
||||
account_number: basRef.account_number,
|
||||
account_name: basRef.account_name,
|
||||
account_class: basRef.account_class,
|
||||
account_group: basRef.account_group,
|
||||
account_type: basRef.account_type,
|
||||
normal_balance: basRef.normal_balance,
|
||||
sru_code: basRef.sru_code,
|
||||
k2_excluded: basRef.k2_excluded,
|
||||
plan_type: 'full_bas',
|
||||
is_active: true,
|
||||
is_system_account: true,
|
||||
description: basRef.description,
|
||||
}
|
||||
}).filter((row): row is NonNullable<typeof row> => row !== null)
|
||||
|
||||
if (rows.length > 0) {
|
||||
const { error: seedError } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.upsert(rows, { onConflict: 'company_id,account_number', ignoreDuplicates: true })
|
||||
if (seedError) {
|
||||
log.error('Failed to seed K3 latent-tax accounts', {
|
||||
companyId,
|
||||
error: seedError.message,
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
log.error('Unexpected error seeding K3 latent-tax accounts', {
|
||||
companyId,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import {
|
||||
parseJsonResponse,
|
||||
createMockRouteParams,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
import { DELETE } from '../route'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
eventBus.clear()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
// Reset write-permission mock to default ok
|
||||
vi.mocked(requireWritePermission).mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
function makeReq() {
|
||||
return new Request('http://localhost/api/documents/doc-1', { method: 'DELETE' })
|
||||
}
|
||||
|
||||
describe('DELETE /api/documents/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
expect(body).toEqual({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
it('returns 403 when caller has read-only role', async () => {
|
||||
vi.mocked(requireWritePermission).mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json(
|
||||
{ error: 'Du har endast läsbehörighet i detta företag.' },
|
||||
{ status: 403 },
|
||||
),
|
||||
})
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 404 when document not found in company', async () => {
|
||||
enqueue({ data: null, error: null }) // doc lookup
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error).toContain('hittades inte')
|
||||
})
|
||||
|
||||
it('returns 409 with BFL message when doc is linked to a journal entry', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'doc-1',
|
||||
file_name: 'kvitto.pdf',
|
||||
storage_path: 'documents/user-1/kvitto.pdf',
|
||||
journal_entry_id: 'je-99',
|
||||
user_id: 'user-1',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toContain('Bokföringslagen')
|
||||
expect(body.error).toContain('7 kap')
|
||||
})
|
||||
|
||||
it('deletes the row, removes Storage file, and emits document.deleted on unlinked doc', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'doc-1',
|
||||
file_name: 'kvitto.pdf',
|
||||
storage_path: 'documents/user-1/kvitto.pdf',
|
||||
journal_entry_id: null,
|
||||
user_id: 'user-1',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: null, error: null }) // delete
|
||||
|
||||
const handler = vi.fn()
|
||||
eventBus.on('document.deleted', handler)
|
||||
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string; deleted: boolean } }>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toEqual({ id: 'doc-1', deleted: true })
|
||||
|
||||
expect(mockSupabase.storage.from).toHaveBeenCalledWith('documents')
|
||||
const storageBucket = mockSupabase.storage.from.mock.results[0]?.value
|
||||
expect(storageBucket.remove).toHaveBeenCalledWith(['documents/user-1/kvitto.pdf'])
|
||||
|
||||
expect(handler).toHaveBeenCalledOnce()
|
||||
expect(handler).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
document: expect.objectContaining({ id: 'doc-1', file_name: 'kvitto.pdf' }),
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns 409 with BFL message when DB trigger blocks deletion (defense-in-depth)', async () => {
|
||||
// Caller bypasses the application-layer check (e.g. race condition).
|
||||
// The block_document_deletion() trigger raises with "Bokföringslagen" in the
|
||||
// message; the service maps it to a 409.
|
||||
enqueue({
|
||||
data: {
|
||||
id: 'doc-1',
|
||||
file_name: 'kvitto.pdf',
|
||||
storage_path: 'documents/user-1/kvitto.pdf',
|
||||
journal_entry_id: null,
|
||||
user_id: 'user-1',
|
||||
},
|
||||
error: null,
|
||||
})
|
||||
enqueue({
|
||||
data: null,
|
||||
error: { message: 'Cannot delete document linked to a posted journal entry (Bokföringslagen)' },
|
||||
})
|
||||
|
||||
const res = await DELETE(makeReq(), createMockRouteParams({ id: 'doc-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toContain('Bokföringslagen')
|
||||
})
|
||||
})
|
||||
@@ -2,6 +2,8 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
import { deleteDocument } from '@/lib/core/documents/document-service'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
ensureInitialized()
|
||||
@@ -66,3 +68,45 @@ export async function GET(
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/documents/:id
|
||||
* Remove an uploaded document. Only permitted when the document is not yet
|
||||
* linked to a journal entry — once linked, it is räkenskapsinformation under
|
||||
* BFL 7 kap 2§ and must be retained for 7 years. For linked docs the caller
|
||||
* should use POST /api/documents/:id/versions to supersede via a new version.
|
||||
*/
|
||||
export async function DELETE(
|
||||
_request: Request,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const writeCheck = await requireWritePermission(supabase, user.id)
|
||||
if (!writeCheck.ok) return writeCheck.response
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { id } = await params
|
||||
|
||||
try {
|
||||
const result = await deleteDocument(supabase, companyId, id)
|
||||
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.message }, { status: result.status })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { id: result.document.id, deleted: true } })
|
||||
} catch (error) {
|
||||
console.error('[documents/DELETE] Failed to delete document:', error)
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : 'Failed to delete document' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,8 +6,8 @@ import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
/**
|
||||
* POST /api/import/sie/[id]/replace
|
||||
*
|
||||
* Replace a completed SIE import by cancelling its entries, allowing the user
|
||||
* to re-import corrected data for the same fiscal period.
|
||||
* Replace a completed SIE import by hard-deleting its entries, allowing the
|
||||
* user to re-import corrected data for the same fiscal period.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'sie_import.replace',
|
||||
@@ -25,7 +25,7 @@ export const POST = withRouteContext(
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true, cancelledEntries: result.cancelledEntries })
|
||||
return NextResponse.json({ success: true, deletedEntries: result.deletedEntries })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
@@ -39,6 +39,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { createInvoiceJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { uploadDocument } from '@/lib/core/documents/document-service'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { requireWritePermission } from '@/lib/auth/require-write'
|
||||
@@ -134,13 +135,16 @@ export async function POST(
|
||||
// The DB status flip already happened above, but the in-memory `invoice`
|
||||
// is stale and still reads 'draft' — override here so the archived
|
||||
// underlag isn't stamped "UTKAST – inte en giltig faktura".
|
||||
const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const }
|
||||
const { branding } = prepareInvoicePdfRender(settings as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(invoice as Invoice), status: 'sent' as const },
|
||||
invoice: renderableInvoice,
|
||||
customer: invoice.customer as Customer,
|
||||
items,
|
||||
company: settings as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types'
|
||||
|
||||
@@ -66,6 +67,7 @@ export async function GET(
|
||||
|
||||
try {
|
||||
// Generate PDF
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: invoice as Invoice,
|
||||
@@ -73,6 +75,7 @@ export async function GET(
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue('mock-pdf-element'),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
@@ -93,6 +94,7 @@ export const POST = withRouteContext(
|
||||
const isFreshAllocation = !invoice.invoice_number
|
||||
if (isFreshAllocation) {
|
||||
try {
|
||||
const preflight = prepareInvoicePdfRender(company as CompanySettings)
|
||||
await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(invoice as Invoice), invoice_number: 'F-PREVIEW' },
|
||||
@@ -100,6 +102,7 @@ export const POST = withRouteContext(
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding: preflight.branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
@@ -121,13 +124,16 @@ export const POST = withRouteContext(
|
||||
// the in-memory copy: the DB flip happens after email delivery (line
|
||||
// ~185), but if we render with the stale 'draft' status the customer
|
||||
// receives a PDF stamped "UTKAST – inte en giltig faktura".
|
||||
const renderableInvoice = { ...(invoice as Invoice), status: 'sent' as const }
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(invoice as Invoice), status: 'sent' as const },
|
||||
invoice: renderableInvoice,
|
||||
customer,
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export const GET = withRouteContext(
|
||||
|
||||
const url = new URL(request.url)
|
||||
const documentType = url.searchParams.get('document_type') ?? 'invoice'
|
||||
if (!['invoice', 'proforma', 'delivery_note'].includes(documentType)) {
|
||||
if (!['invoice', 'proforma', 'delivery_note', 'quote'].includes(documentType)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'invalid document_type', requestId },
|
||||
{ status: 400 },
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getVatRules } from '@/lib/invoices/vat-rules'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings, InvoiceDocumentType } from '@/types'
|
||||
@@ -167,6 +168,7 @@ export async function POST(request: Request) {
|
||||
} as Invoice
|
||||
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: previewInvoice,
|
||||
@@ -174,6 +176,7 @@ export async function POST(request: Request) {
|
||||
items: invoiceItems,
|
||||
company: company as CompanySettings,
|
||||
isPreview: true,
|
||||
branding,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -120,6 +120,11 @@ export async function GET(request: Request) {
|
||||
sent_at,
|
||||
response_type,
|
||||
action_token_used,
|
||||
interest_amount,
|
||||
interest_rate,
|
||||
interest_from_date,
|
||||
interest_days,
|
||||
reminder_fee,
|
||||
invoice:invoices(
|
||||
id,
|
||||
invoice_number,
|
||||
@@ -159,6 +164,11 @@ export async function GET(request: Request) {
|
||||
const customerData = invoice.customer
|
||||
const customer = Array.isArray(customerData) ? customerData[0] : customerData
|
||||
|
||||
const interestAmount = Number(reminder.interest_amount ?? 0)
|
||||
const reminderFee = Number(reminder.reminder_fee ?? 0)
|
||||
const totalDue =
|
||||
Math.round((Number(invoice.total) + interestAmount + reminderFee) * 100) / 100
|
||||
|
||||
return NextResponse.json({
|
||||
invoiceNumber: invoice.invoice_number,
|
||||
invoiceDate: invoice.invoice_date,
|
||||
@@ -168,6 +178,15 @@ export async function GET(request: Request) {
|
||||
customerName: customer?.name,
|
||||
reminderLevel: reminder.reminder_level,
|
||||
alreadyResponded: reminder.action_token_used,
|
||||
previousResponse: reminder.response_type
|
||||
previousResponse: reminder.response_type,
|
||||
// Dröjsmålsränta + lagstadgad påminnelseavgift surfaced to the
|
||||
// customer-facing action page. Numeric defaults preserve back-compat
|
||||
// for old reminders sent before the surcharge feature shipped.
|
||||
interestAmount,
|
||||
interestRate: reminder.interest_rate !== null ? Number(reminder.interest_rate) : 0,
|
||||
interestFromDate: reminder.interest_from_date,
|
||||
interestDays: reminder.interest_days,
|
||||
reminderFee,
|
||||
totalDue,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,6 +8,16 @@ import { getVatRules, getAvailableVatRates } from '@/lib/invoices/vat-rules'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import { createCreditNoteJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import { ensureInvoiceNumber } from '@/lib/invoices/ensure-invoice-number'
|
||||
import {
|
||||
computeDeduction,
|
||||
computeInvoiceDeductionTotal,
|
||||
validateInvoice as validateRotRut,
|
||||
} from '@/lib/invoices/rot-rut-rules'
|
||||
import {
|
||||
encryptPersonnummer,
|
||||
extractLast4,
|
||||
validatePersonnummer,
|
||||
} from '@/lib/salary/personnummer'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse, errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { Logger } from '@/lib/logger'
|
||||
@@ -135,6 +145,51 @@ export const POST = withRouteContext(
|
||||
}
|
||||
const total = documentType === 'delivery_note' ? 0 : subtotal + vatAmount
|
||||
|
||||
// ROT/RUT-avdrag: validate prerequisites and compute the per-item +
|
||||
// invoice-level deduction. Computed server-side (never trusted from
|
||||
// the client) so a tampered request can't expand the 1513 receivable.
|
||||
// Skipped entirely for proformas, delivery notes, and quotes — those
|
||||
// documents don't post journal entries and have no deduction model.
|
||||
let deductionTotal = 0
|
||||
let deductionPersonnummerEncrypted: string | null = null
|
||||
let deductionPersonnummerLast4: string | null = null
|
||||
if (documentType === 'invoice') {
|
||||
const housingProvided = !!invoiceInput.deduction_housing_designation?.trim()
|
||||
const personnummerRaw = invoiceInput.deduction_personnummer?.trim() || ''
|
||||
const personnummerProvided = personnummerRaw.length > 0
|
||||
|
||||
const validateInput = invoiceInput.items.map((item) => ({
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
deduction_type: item.deduction_type ?? null,
|
||||
labor_hours: item.labor_hours ?? null,
|
||||
housing_designation: item.housing_designation ?? null,
|
||||
}))
|
||||
const validation = validateRotRut(validateInput, personnummerProvided, housingProvided)
|
||||
if (validation.errors.length > 0) {
|
||||
return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_VALIDATION', log, {
|
||||
requestId,
|
||||
details: { errors: validation.errors, warnings: validation.warnings },
|
||||
})
|
||||
}
|
||||
|
||||
// Compute and (when present) encrypt the personnummer. The plaintext
|
||||
// value never touches the DB — only the AES-256-GCM ciphertext + the
|
||||
// last four digits go into invoices columns.
|
||||
deductionTotal = computeInvoiceDeductionTotal(validateInput)
|
||||
if (personnummerProvided) {
|
||||
const pnValid = validatePersonnummer(personnummerRaw)
|
||||
if (!pnValid.valid) {
|
||||
return errorResponseFromCode('INVOICE_CREATE_ROT_RUT_PERSONNUMMER_INVALID', log, {
|
||||
requestId,
|
||||
details: { error: pnValid.error },
|
||||
})
|
||||
}
|
||||
deductionPersonnummerEncrypted = encryptPersonnummer(personnummerRaw)
|
||||
deductionPersonnummerLast4 = extractLast4(personnummerRaw)
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueRates = new Set(invoiceInput.items.map((item) => item.vat_rate ?? vatRules.rate))
|
||||
const isMixedRate = uniqueRates.size > 1
|
||||
|
||||
@@ -182,13 +237,14 @@ export const POST = withRouteContext(
|
||||
vat_amount_sek: documentType === 'delivery_note' ? null : vatAmountSek,
|
||||
total,
|
||||
total_sek: documentType === 'delivery_note' ? null : totalSek,
|
||||
// Initialize remaining_amount to total for real invoices so the open-
|
||||
// invoice queries (InvoicePicker, AR ledger, supplier matching) treat
|
||||
// newly-created invoices as fully unpaid. The DB default is 0 — without
|
||||
// this, brand-new fakturor look settled and disappear from match
|
||||
// candidate lists. Proformas and delivery notes have no payment
|
||||
// obligation, so they keep the 0 default.
|
||||
remaining_amount: documentType === 'invoice' ? total : 0,
|
||||
// Initialize remaining_amount to total - deduction for real invoices
|
||||
// so the open-invoice queries (InvoicePicker, AR ledger, supplier
|
||||
// matching) treat newly-created invoices as fully unpaid for the
|
||||
// CUSTOMER's share — the Skatteverket portion is on 1513 and will be
|
||||
// cleared when the agency pays out, not by the customer payment.
|
||||
// Proformas, delivery notes and quotes have no payment obligation,
|
||||
// so they keep the 0 default.
|
||||
remaining_amount: documentType === 'invoice' ? total - deductionTotal : 0,
|
||||
vat_treatment: vatRules.treatment,
|
||||
vat_rate: documentType === 'delivery_note' ? 0 : (isMixedRate ? null : (uniqueRates.values().next().value ?? vatRules.rate)),
|
||||
moms_ruta: vatRules.momsRuta,
|
||||
@@ -197,6 +253,9 @@ export const POST = withRouteContext(
|
||||
our_reference: invoiceInput.our_reference,
|
||||
notes: invoiceInput.notes,
|
||||
document_type: documentType,
|
||||
deduction_total: deductionTotal,
|
||||
deduction_personnummer_encrypted: deductionPersonnummerEncrypted,
|
||||
deduction_personnummer_last4: deductionPersonnummerLast4,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
@@ -213,6 +272,18 @@ export const POST = withRouteContext(
|
||||
const itemRate = item.vat_rate !== undefined ? item.vat_rate : vatRules.rate
|
||||
const lineTotal = item.quantity * item.unit_price
|
||||
const itemVat = documentType === 'delivery_note' ? 0 : Math.round(lineTotal * itemRate / 100 * 100) / 100
|
||||
// ROT/RUT deduction is recomputed server-side so a tampered client
|
||||
// can't expand the 1513 receivable beyond the rules. Non-invoice
|
||||
// document types never carry deduction_type (rules above strip them
|
||||
// implicitly because validateRotRut isn't invoked).
|
||||
const deductionType = documentType === 'invoice' ? (item.deduction_type ?? null) : null
|
||||
const deductionAmount = deductionType
|
||||
? computeDeduction({
|
||||
unit_price: item.unit_price,
|
||||
quantity: item.quantity,
|
||||
deduction_type: deductionType,
|
||||
})
|
||||
: 0
|
||||
return {
|
||||
invoice_id: invoice.id,
|
||||
sort_order: index,
|
||||
@@ -223,6 +294,12 @@ export const POST = withRouteContext(
|
||||
line_total: lineTotal,
|
||||
vat_rate: itemRate,
|
||||
vat_amount: itemVat,
|
||||
deduction_type: deductionType,
|
||||
deduction_amount: deductionAmount,
|
||||
labor_hours: documentType === 'invoice' ? (item.labor_hours ?? null) : null,
|
||||
work_type: documentType === 'invoice' ? (item.work_type ?? null) : null,
|
||||
housing_designation: documentType === 'invoice' ? (item.housing_designation ?? null) : null,
|
||||
apartment_number: documentType === 'invoice' ? (item.apartment_number ?? null) : null,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -296,7 +373,7 @@ export const POST = withRouteContext(
|
||||
.eq('id', invoice.id)
|
||||
.single()
|
||||
|
||||
// Emit event only for real invoices (proformas / delivery notes are informational).
|
||||
// Emit event only for real invoices (proformas / delivery notes / quotes are informational).
|
||||
if (completeInvoice && documentType === 'invoice') {
|
||||
await eventBus.emit({
|
||||
type: 'invoice.created',
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/bookkeeping/currency-utils', () => ({
|
||||
resolveSekAmount: vi.fn((amount: number) => amount),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
interface QueryResult {
|
||||
data: unknown
|
||||
error: unknown
|
||||
}
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
customer: { id: string; name: string } | null,
|
||||
invoicesResult: QueryResult,
|
||||
entriesResult: QueryResult
|
||||
) {
|
||||
let invoiceCallNum = 0
|
||||
let entryCallNum = 0
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'customers') {
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: customer, error: null }),
|
||||
}
|
||||
}
|
||||
if (table === 'invoices') {
|
||||
invoiceCallNum += 1
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(invoicesResult),
|
||||
}
|
||||
}
|
||||
// journal_entries
|
||||
entryCallNum += 1
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(entriesResult),
|
||||
}
|
||||
}),
|
||||
_stats: () => ({ invoiceCallNum, entryCallNum }),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/ar-ledger/customer/[customerId]/invoices', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/ar-ledger/customer/cust-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when customer is unknown', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/ar-ledger/customer/cust-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns invoices with linked journal entries', async () => {
|
||||
const invoices = [
|
||||
{
|
||||
id: 'inv-1',
|
||||
invoice_number: '2026-001',
|
||||
invoice_date: '2026-05-01',
|
||||
due_date: '2026-06-01',
|
||||
total: 1250,
|
||||
paid_amount: 0,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
remaining_amount: 1250,
|
||||
notes: null,
|
||||
},
|
||||
]
|
||||
const entries = [
|
||||
{
|
||||
id: 'je-1',
|
||||
voucher_number: 22,
|
||||
voucher_series: 'A',
|
||||
description: 'Faktura 2026-001',
|
||||
source_id: 'inv-1',
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(
|
||||
{ id: 'user-1' },
|
||||
{ id: 'cust-1', name: 'Acme AB' },
|
||||
{ data: invoices, error: null },
|
||||
{ data: entries, error: null }
|
||||
) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/ar-ledger/customer/cust-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ customerId: 'cust-1' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
customer_id: string
|
||||
customer_name: string
|
||||
lines: Array<{
|
||||
invoice_id: string
|
||||
voucher_number: number
|
||||
journal_entry_id: string
|
||||
outstanding: number
|
||||
}>
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.customer_id).toBe('cust-1')
|
||||
expect(body.data.customer_name).toBe('Acme AB')
|
||||
expect(body.data.lines).toHaveLength(1)
|
||||
expect(body.data.lines[0].invoice_id).toBe('inv-1')
|
||||
expect(body.data.lines[0].journal_entry_id).toBe('je-1')
|
||||
expect(body.data.lines[0].voucher_number).toBe(22)
|
||||
expect(body.data.lines[0].outstanding).toBe(1250)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
|
||||
/**
|
||||
* GET /api/reports/ar-ledger/customer/[customerId]/invoices
|
||||
*
|
||||
* Returns the invoices that contribute to a customer's outstanding balance.
|
||||
* Each row exposes the registration journal entry (if any) via
|
||||
* `journal_entry_id`, so the UI can link directly to `/bookkeeping/[id]`.
|
||||
*
|
||||
* If an invoice has no posted registration entry yet (still draft), the
|
||||
* `journal_entry_id` is null and the UI must fall back to `/invoices/[id]`.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ customerId: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { customerId } = await params
|
||||
|
||||
// Verify customer belongs to the company.
|
||||
const { data: customer } = await supabase
|
||||
.from('customers')
|
||||
.select('id, name')
|
||||
.eq('id', customerId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!customer) {
|
||||
return NextResponse.json({ error: 'Kund saknas' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Pull this customer's outstanding invoices. Mirrors the filter in
|
||||
// `generateARLedger` so the UI sees the same set the aggregate is built
|
||||
// from.
|
||||
const { data, error } = await supabase
|
||||
.from('invoices')
|
||||
.select(`
|
||||
id,
|
||||
invoice_number,
|
||||
invoice_date,
|
||||
due_date,
|
||||
total,
|
||||
paid_amount,
|
||||
currency,
|
||||
exchange_rate,
|
||||
remaining_amount,
|
||||
notes
|
||||
`)
|
||||
.eq('company_id', companyId)
|
||||
.eq('customer_id', customerId)
|
||||
.in('status', ['sent', 'overdue', 'credited'])
|
||||
.order('invoice_date', { ascending: true })
|
||||
.limit(PAGE_LIMIT)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// For each invoice, find the registration journal entry (source_type =
|
||||
// 'invoice_created', source_id = invoice.id). We batch them to keep this
|
||||
// a single DB roundtrip.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const invoices = (data || []) as any[]
|
||||
const ids = invoices.map((i) => i.id)
|
||||
const entryMap = new Map<
|
||||
string,
|
||||
{ id: string; voucher_number: number; voucher_series: string; description: string | null }
|
||||
>()
|
||||
|
||||
if (ids.length > 0) {
|
||||
const { data: entries } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id, voucher_number, voucher_series, description, source_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('source_type', 'invoice_created')
|
||||
.in('source_id', ids)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
|
||||
for (const e of entries || []) {
|
||||
entryMap.set(e.source_id, {
|
||||
id: e.id,
|
||||
voucher_number: e.voucher_number,
|
||||
voucher_series: e.voucher_series || 'A',
|
||||
description: e.description,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Shape each invoice as a ReportSourceLine. The "debit" column carries
|
||||
// the outstanding SEK amount (it's a receivable on 1510); "credit" is 0
|
||||
// unless the invoice is fully a credit note.
|
||||
const lines: (ReportSourceLine & {
|
||||
invoice_id: string
|
||||
invoice_number: string | null
|
||||
outstanding: number
|
||||
outstanding_sek: number | null
|
||||
currency: string
|
||||
paid_amount: number
|
||||
due_date: string
|
||||
})[] = invoices.map((inv) => {
|
||||
const entry = entryMap.get(inv.id)
|
||||
const paidAmount = Number(inv.paid_amount) || 0
|
||||
const total = Number(inv.total) || 0
|
||||
const outstanding = Math.round((total - paidAmount) * 100) / 100
|
||||
const isFx = inv.currency && inv.currency !== 'SEK'
|
||||
const hasRate = inv.exchange_rate != null && Number(inv.exchange_rate) > 0
|
||||
const outstandingSek =
|
||||
isFx && !hasRate
|
||||
? null
|
||||
: resolveSekAmount(outstanding, null, inv.currency, inv.exchange_rate)
|
||||
|
||||
return {
|
||||
journal_entry_id: entry?.id ?? '',
|
||||
voucher_number: entry?.voucher_number ?? 0,
|
||||
voucher_series: entry?.voucher_series ?? 'A',
|
||||
date: inv.invoice_date || '',
|
||||
description:
|
||||
entry?.description ?? `Faktura ${inv.invoice_number || '(utkast)'}`,
|
||||
debit: outstandingSek ?? outstanding,
|
||||
credit: 0,
|
||||
invoice_id: inv.id,
|
||||
invoice_number: inv.invoice_number,
|
||||
outstanding,
|
||||
outstanding_sek: outstandingSek,
|
||||
currency: inv.currency || 'SEK',
|
||||
paid_amount: paidAmount,
|
||||
due_date: inv.due_date,
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
customer_id: customer.id,
|
||||
customer_name: customer.name,
|
||||
lines,
|
||||
next_cursor: null,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateARLedger } from '@/lib/reports/ar-ledger'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface AgingRow {
|
||||
customer_name: string
|
||||
current: number
|
||||
days_1_30: number
|
||||
days_31_60: number
|
||||
days_61_90: number
|
||||
days_90_plus: number
|
||||
total_outstanding: number
|
||||
}
|
||||
|
||||
interface InvoiceRow {
|
||||
customer_name: string
|
||||
invoice_number: string
|
||||
invoice_date: Date | string
|
||||
due_date: Date | string
|
||||
total: number
|
||||
paid_amount: number
|
||||
outstanding: number
|
||||
outstanding_sek: number | null
|
||||
days_overdue: number
|
||||
currency: string
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const asOfDate = searchParams.get('as_of_date') || undefined
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const ledger = await generateARLedger(supabase, companyId, asOfDate)
|
||||
|
||||
const agingRows: AgingRow[] = ledger.entries.map((e) => ({
|
||||
customer_name: e.customer_name,
|
||||
current: e.current,
|
||||
days_1_30: e.days_1_30,
|
||||
days_31_60: e.days_31_60,
|
||||
days_61_90: e.days_61_90,
|
||||
days_90_plus: e.days_90_plus,
|
||||
total_outstanding: e.total_outstanding,
|
||||
}))
|
||||
|
||||
const invoiceRows: InvoiceRow[] = []
|
||||
for (const e of ledger.entries) {
|
||||
for (const inv of e.invoices) {
|
||||
invoiceRows.push({
|
||||
customer_name: e.customer_name,
|
||||
invoice_number: inv.invoice_number,
|
||||
invoice_date: toDate(inv.invoice_date) ?? inv.invoice_date,
|
||||
due_date: toDate(inv.due_date) ?? inv.due_date,
|
||||
total: inv.total,
|
||||
paid_amount: inv.paid_amount,
|
||||
outstanding: inv.outstanding,
|
||||
outstanding_sek: inv.outstanding_sek,
|
||||
days_overdue: inv.days_overdue,
|
||||
currency: inv.currency,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Åldersfördelning',
|
||||
columns: [
|
||||
textColumn('Kund'),
|
||||
currencyColumn('Ej förfallet'),
|
||||
currencyColumn('1-30 dagar'),
|
||||
currencyColumn('31-60 dagar'),
|
||||
currencyColumn('61-90 dagar'),
|
||||
currencyColumn('90+ dagar'),
|
||||
currencyColumn('Totalt utestående'),
|
||||
],
|
||||
rows: agingRows,
|
||||
mapRow: (r) => [
|
||||
r.customer_name,
|
||||
r.current,
|
||||
r.days_1_30,
|
||||
r.days_31_60,
|
||||
r.days_61_90,
|
||||
r.days_90_plus,
|
||||
r.total_outstanding,
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Fakturor',
|
||||
columns: [
|
||||
textColumn('Kund'),
|
||||
textColumn('Fakturanr'),
|
||||
dateColumn('Fakturadatum'),
|
||||
dateColumn('Förfallodatum'),
|
||||
currencyColumn('Totalt'),
|
||||
currencyColumn('Betalt'),
|
||||
currencyColumn('Utestående'),
|
||||
currencyColumn('Utestående (SEK)'),
|
||||
integerColumn('Dagar förfallet'),
|
||||
textColumn('Valuta'),
|
||||
],
|
||||
rows: invoiceRows,
|
||||
mapRow: (r) => [
|
||||
r.customer_name,
|
||||
r.invoice_number,
|
||||
r.invoice_date instanceof Date ? r.invoice_date : null,
|
||||
r.due_date instanceof Date ? r.due_date : null,
|
||||
r.total,
|
||||
r.paid_amount,
|
||||
r.outstanding,
|
||||
r.outstanding_sek,
|
||||
r.days_overdue,
|
||||
r.currency,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'kundreskontra',
|
||||
companyRow?.company_name ?? '',
|
||||
asOfDate ?? new Date().toISOString().slice(0, 10),
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera kundreskontra' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateBalanceSheet } from '@/lib/reports/balance-sheet'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
section: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
amount: number
|
||||
isSubtotal: boolean
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateBalanceSheet(supabase, companyId, periodId)
|
||||
|
||||
// Flatten nested sections into a single tabular view, mirroring how the
|
||||
// PDF lays them out: each section's rows followed by a subtotal line, with
|
||||
// grand totals at the end. The "Sektion" column keeps the grouping queryable.
|
||||
const assetRows: FlatRow[] = []
|
||||
for (const s of report.asset_sections) {
|
||||
for (const r of s.rows) {
|
||||
assetRows.push({
|
||||
section: s.title,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
amount: r.amount,
|
||||
isSubtotal: false,
|
||||
})
|
||||
}
|
||||
assetRows.push({
|
||||
section: s.title,
|
||||
account_number: '',
|
||||
account_name: `Summa ${s.title}`,
|
||||
amount: s.subtotal,
|
||||
isSubtotal: true,
|
||||
})
|
||||
}
|
||||
assetRows.push({
|
||||
section: 'Tillgångar',
|
||||
account_number: '',
|
||||
account_name: 'Summa tillgångar',
|
||||
amount: report.total_assets,
|
||||
isSubtotal: true,
|
||||
})
|
||||
|
||||
const equityRows: FlatRow[] = []
|
||||
for (const s of report.equity_liability_sections) {
|
||||
for (const r of s.rows) {
|
||||
equityRows.push({
|
||||
section: s.title,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
amount: r.amount,
|
||||
isSubtotal: false,
|
||||
})
|
||||
}
|
||||
equityRows.push({
|
||||
section: s.title,
|
||||
account_number: '',
|
||||
account_name: `Summa ${s.title}`,
|
||||
amount: s.subtotal,
|
||||
isSubtotal: true,
|
||||
})
|
||||
}
|
||||
equityRows.push({
|
||||
section: 'Eget kapital och skulder',
|
||||
account_number: '',
|
||||
account_name: 'Summa eget kapital och skulder',
|
||||
amount: report.total_equity_liabilities,
|
||||
isSubtotal: true,
|
||||
})
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Tillgångar',
|
||||
columns: [
|
||||
textColumn('Sektion'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Belopp'),
|
||||
],
|
||||
rows: assetRows,
|
||||
mapRow: (r) => [r.section, r.account_number, r.account_name, r.amount],
|
||||
},
|
||||
{
|
||||
name: 'Eget kapital och skulder',
|
||||
columns: [
|
||||
textColumn('Sektion'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Belopp'),
|
||||
],
|
||||
rows: equityRows,
|
||||
mapRow: (r) => [r.section, r.account_number, r.account_name, r.amount],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('balansrakning', companyRow?.company_name ?? '', period.period_end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera balansräkning' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateBalansrapport } from '@/lib/reports/balansrapport'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
group: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
ib: number
|
||||
period_change: number
|
||||
ub: number
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateBalansrapport(supabase, companyId, periodId)
|
||||
|
||||
const rows: FlatRow[] = []
|
||||
for (const g of report.groups) {
|
||||
for (const r of g.rows) {
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
ib: r.ib,
|
||||
period_change: r.period_change,
|
||||
ub: r.ub,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: '',
|
||||
account_name: `Summa ${g.class_label}`,
|
||||
ib: g.subtotal_ib,
|
||||
period_change: Math.round((g.subtotal_ub - g.subtotal_ib) * 100) / 100,
|
||||
ub: g.subtotal_ub,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: 'Beräknat resultat',
|
||||
account_number: '',
|
||||
account_name: 'Beräknat resultat',
|
||||
ib: 0,
|
||||
period_change: report.beraknat_resultat,
|
||||
ub: report.beraknat_resultat,
|
||||
})
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Balansrapport',
|
||||
columns: [
|
||||
textColumn('Grupp'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('IB'),
|
||||
currencyColumn('Periodförändring'),
|
||||
currencyColumn('UB'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.group,
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.ib,
|
||||
r.period_change,
|
||||
r.ub,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'balansrapport',
|
||||
companyRow?.company_name ?? '',
|
||||
report.period.end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera balansrapport' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateGeneralLedger } from '@/lib/reports/general-ledger'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
account_number: string
|
||||
account_name: string
|
||||
date: Date | string
|
||||
voucher: string
|
||||
description: string
|
||||
source_type: string
|
||||
debit: number
|
||||
credit: number
|
||||
balance: number
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | string {
|
||||
// Preserve original ISO string in the cell if parsing fails (avoids NaN
|
||||
// dates polluting the workbook).
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? s : d
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
const accountFrom = searchParams.get('account_from') || undefined
|
||||
const accountTo = searchParams.get('account_to') || undefined
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateGeneralLedger(supabase, companyId, periodId, accountFrom, accountTo)
|
||||
|
||||
// Flatten accounts + their lines into a single sheet. Each account contributes
|
||||
// an opening-balance row, its lines (with running balance), and a closing
|
||||
// row — matching how huvudbok is read in Fortnox/Visma.
|
||||
const rows: FlatRow[] = []
|
||||
for (const acc of report.accounts) {
|
||||
rows.push({
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
date: '',
|
||||
voucher: '',
|
||||
description: 'Ingående balans',
|
||||
source_type: '',
|
||||
debit: 0,
|
||||
credit: 0,
|
||||
balance: acc.opening_balance,
|
||||
})
|
||||
for (const line of acc.lines) {
|
||||
rows.push({
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
date: toDate(line.date),
|
||||
voucher: `${line.voucher_series}${line.voucher_number}`,
|
||||
description: line.description,
|
||||
source_type: line.source_type,
|
||||
debit: line.debit,
|
||||
credit: line.credit,
|
||||
balance: line.balance,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
account_number: acc.account_number,
|
||||
account_name: acc.account_name,
|
||||
date: '',
|
||||
voucher: '',
|
||||
description: 'Utgående balans',
|
||||
source_type: '',
|
||||
debit: acc.total_debit,
|
||||
credit: acc.total_credit,
|
||||
balance: acc.closing_balance,
|
||||
})
|
||||
}
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Huvudbok',
|
||||
columns: [
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
dateColumn('Datum'),
|
||||
textColumn('Verifikat'),
|
||||
textColumn('Beskrivning'),
|
||||
textColumn('Källa'),
|
||||
currencyColumn('Debet'),
|
||||
currencyColumn('Kredit'),
|
||||
currencyColumn('Saldo'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.date instanceof Date ? r.date : null,
|
||||
r.voucher,
|
||||
r.description,
|
||||
r.source_type,
|
||||
r.debit,
|
||||
r.credit,
|
||||
r.balance,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('huvudbok', companyRow?.company_name ?? '', report.period.end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera huvudbok' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import type { IncomeStatementSection } from '@/types'
|
||||
|
||||
interface FlatRow {
|
||||
section: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
function flatten(
|
||||
sections: IncomeStatementSection[],
|
||||
groupLabel: string,
|
||||
groupTotalLabel: string,
|
||||
groupTotal: number,
|
||||
): FlatRow[] {
|
||||
const rows: FlatRow[] = []
|
||||
for (const s of sections) {
|
||||
for (const r of s.rows) {
|
||||
rows.push({
|
||||
section: s.title,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
amount: r.amount,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
section: s.title,
|
||||
account_number: '',
|
||||
account_name: `Summa ${s.title}`,
|
||||
amount: s.subtotal,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
section: groupLabel,
|
||||
account_number: '',
|
||||
account_name: groupTotalLabel,
|
||||
amount: groupTotal,
|
||||
})
|
||||
return rows
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateIncomeStatement(supabase, companyId, periodId)
|
||||
|
||||
const revenueRows = flatten(
|
||||
report.revenue_sections,
|
||||
'Rörelseintäkter',
|
||||
'Summa rörelseintäkter',
|
||||
report.total_revenue,
|
||||
)
|
||||
const expenseRows = flatten(
|
||||
report.expense_sections,
|
||||
'Rörelsekostnader',
|
||||
'Summa rörelsekostnader',
|
||||
report.total_expenses,
|
||||
)
|
||||
const financialRows = flatten(
|
||||
report.financial_sections,
|
||||
'Finansiella poster',
|
||||
'Summa finansiella poster',
|
||||
report.total_financial,
|
||||
)
|
||||
|
||||
const summaryRows: FlatRow[] = [
|
||||
{
|
||||
section: 'Sammanfattning',
|
||||
account_number: '',
|
||||
account_name: 'Rörelseresultat',
|
||||
amount: Math.round((report.total_revenue - report.total_expenses) * 100) / 100,
|
||||
},
|
||||
{
|
||||
section: 'Sammanfattning',
|
||||
account_number: '',
|
||||
account_name: 'Årets resultat',
|
||||
amount: report.net_result,
|
||||
},
|
||||
]
|
||||
|
||||
const columns = [
|
||||
textColumn('Sektion'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Belopp'),
|
||||
]
|
||||
const mapRow = (r: FlatRow) => [r.section, r.account_number, r.account_name, r.amount]
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{ name: 'Intäkter', columns, rows: revenueRows, mapRow },
|
||||
{ name: 'Kostnader', columns, rows: expenseRows, mapRow },
|
||||
{ name: 'Finansiella poster', columns, rows: financialRows, mapRow },
|
||||
{ name: 'Sammanfattning', columns, rows: summaryRows, mapRow },
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'resultatrakning',
|
||||
companyRow?.company_name ?? '',
|
||||
period.period_end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera resultaträkning' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateJournalRegister } from '@/lib/reports/journal-register'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
voucher: string
|
||||
date: Date | null
|
||||
description: string
|
||||
source_type: string
|
||||
status: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
debit: number
|
||||
credit: number
|
||||
}
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateJournalRegister(supabase, companyId, periodId)
|
||||
|
||||
// Flatten: one row per (entry, line). Voucher metadata repeats so the
|
||||
// file is filterable in Excel without losing context.
|
||||
const rows: FlatRow[] = []
|
||||
for (const entry of report.entries) {
|
||||
const voucherLabel = `${entry.voucher_series}${entry.voucher_number}`
|
||||
for (const line of entry.lines) {
|
||||
rows.push({
|
||||
voucher: voucherLabel,
|
||||
date: toDate(entry.date),
|
||||
description: entry.description,
|
||||
source_type: entry.source_type,
|
||||
status: entry.status,
|
||||
account_number: line.account_number,
|
||||
account_name: line.account_name,
|
||||
debit: line.debit,
|
||||
credit: line.credit,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Grundbok',
|
||||
columns: [
|
||||
textColumn('Verifikat'),
|
||||
dateColumn('Datum'),
|
||||
textColumn('Beskrivning'),
|
||||
textColumn('Källa'),
|
||||
textColumn('Status'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Debet'),
|
||||
currencyColumn('Kredit'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.voucher,
|
||||
r.date,
|
||||
r.description,
|
||||
r.source_type,
|
||||
r.status,
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.debit,
|
||||
r.credit,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('grundbok', companyRow?.company_name ?? '', report.period.end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera grundbok' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { generateKassaflodesanalys } from '@/lib/reports/kassaflodesanalys'
|
||||
import { KassaflodesanalysPDF } from '@/lib/reports/kassaflodesanalys-pdf-template'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { CompanySettings } from '@/types'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!companyRow) {
|
||||
return NextResponse.json({ error: 'Företagsinställningar saknas' }, { status: 404 })
|
||||
}
|
||||
// An identifiable period is part of räkenskapsinformation (BFL 7 kap). Refuse
|
||||
// to render a PDF that can't be archived with the period it refers to.
|
||||
if (!period) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
'Räkenskapsperioden kunde inte läsas. Välj en befintlig period innan du genererar PDF.',
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateKassaflodesanalys(supabase, companyId, periodId)
|
||||
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
KassaflodesanalysPDF({
|
||||
report,
|
||||
company: companyRow as CompanySettings,
|
||||
generatedAt: new Date().toISOString(),
|
||||
})
|
||||
)
|
||||
|
||||
const filename = `kassaflodesanalys-${report.period_start}.pdf`
|
||||
|
||||
return new Response(new Uint8Array(pdfBuffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera kassaflödesanalys' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateKassaflodesanalys } from '@/lib/reports/kassaflodesanalys'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await generateKassaflodesanalys(supabase, companyId, periodId)
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Failed to generate kassaflödesanalys' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateIncomeStatement } from '@/lib/reports/income-statement'
|
||||
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
||||
import { generateARLedger } from '@/lib/reports/ar-ledger'
|
||||
import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown'
|
||||
import {
|
||||
calculateCashPosition,
|
||||
calculateGrossMargin,
|
||||
calculateExpenseRatio,
|
||||
calculateAvgPaymentDays,
|
||||
} from '@/lib/reports/kpi'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
percentColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface KpiKv {
|
||||
label: string
|
||||
value: number | null
|
||||
}
|
||||
|
||||
interface MonthRow {
|
||||
label: string
|
||||
income: number
|
||||
expenses: number
|
||||
net: number
|
||||
}
|
||||
|
||||
interface CompositionRow {
|
||||
klass: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
interface SupplierRow {
|
||||
supplier_name: string
|
||||
total: number
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end, is_closed')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Fiscal period not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
try {
|
||||
const [
|
||||
incomeStatement,
|
||||
trialBalanceResult,
|
||||
arLedger,
|
||||
monthlyBreakdown,
|
||||
paidInvoicesResult,
|
||||
topSuppliersResult,
|
||||
] = await Promise.all([
|
||||
generateIncomeStatement(supabase, companyId, periodId),
|
||||
generateTrialBalance(supabase, companyId, periodId),
|
||||
generateARLedger(supabase, companyId),
|
||||
generateMonthlyBreakdown(supabase, companyId, periodId),
|
||||
supabase
|
||||
.from('invoices')
|
||||
.select('invoice_date, paid_at')
|
||||
.eq('company_id', companyId)
|
||||
.eq('status', 'paid')
|
||||
.not('paid_at', 'is', null),
|
||||
supabase
|
||||
.from('supplier_invoices')
|
||||
.select('supplier_id, total_sek, total, supplier:suppliers(id, name)')
|
||||
.eq('company_id', companyId)
|
||||
.gte('invoice_date', period.period_start)
|
||||
.lte('invoice_date', period.period_end)
|
||||
.neq('status', 'credited'),
|
||||
])
|
||||
|
||||
const cashPosition = calculateCashPosition(trialBalanceResult.rows)
|
||||
const vatOutputAccounts = ['2611', '2621', '2631']
|
||||
const vatInputAccounts = ['2641', '2645']
|
||||
const outputVat = trialBalanceResult.rows
|
||||
.filter((r) => vatOutputAccounts.includes(r.account_number))
|
||||
.reduce((sum, r) => sum + (r.closing_credit - r.closing_debit), 0)
|
||||
const inputVat = trialBalanceResult.rows
|
||||
.filter((r) => vatInputAccounts.includes(r.account_number))
|
||||
.reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0)
|
||||
const vatLiability = Math.round((outputVat - inputVat) * 100) / 100
|
||||
|
||||
const paidInvoices = (paidInvoicesResult.data ?? []).map((inv) => ({
|
||||
invoice_date: inv.invoice_date as string,
|
||||
paid_at: inv.paid_at as string,
|
||||
}))
|
||||
|
||||
// Expense composition by BAS class (mirrors KPI JSON route logic).
|
||||
const expenseComposition = trialBalanceResult.rows.reduce(
|
||||
(acc, r) => {
|
||||
if (r.account_class < 4 || r.account_class > 7) return acc
|
||||
const amount = r.closing_debit - r.closing_credit
|
||||
if (amount <= 0) return acc
|
||||
if (r.account_class === 4) acc.class4 += amount
|
||||
else if (r.account_class === 5) acc.class5 += amount
|
||||
else if (r.account_class === 6) acc.class6 += amount
|
||||
else if (r.account_class === 7) acc.class7 += amount
|
||||
return acc
|
||||
},
|
||||
{ class4: 0, class5: 0, class6: 0, class7: 0 },
|
||||
)
|
||||
|
||||
type SupplierInvoiceRow = {
|
||||
supplier_id: string | null
|
||||
total_sek: number | null
|
||||
total: number | null
|
||||
supplier: { id: string; name: string } | { id: string; name: string }[] | null
|
||||
}
|
||||
const supplierTotals = new Map<string, { name: string; total: number }>()
|
||||
for (const row of (topSuppliersResult.data ?? []) as SupplierInvoiceRow[]) {
|
||||
if (!row.supplier_id) continue
|
||||
const supplier = Array.isArray(row.supplier) ? row.supplier[0] : row.supplier
|
||||
if (!supplier?.name) continue
|
||||
const amount = row.total_sek ?? null
|
||||
if (amount == null) continue
|
||||
const existing = supplierTotals.get(row.supplier_id)
|
||||
if (existing) existing.total += amount
|
||||
else supplierTotals.set(row.supplier_id, { name: supplier.name, total: amount })
|
||||
}
|
||||
const topSuppliers = Array.from(supplierTotals.values())
|
||||
.map((v) => ({
|
||||
supplier_name: v.name,
|
||||
total: Math.round(v.total * 100) / 100,
|
||||
}))
|
||||
.sort((a, b) => b.total - a.total)
|
||||
.slice(0, 7)
|
||||
|
||||
// Sheet 1: scalar KPIs, label + value. Currency by default; percent rows
|
||||
// are split into a separate sheet so the formatting is unambiguous.
|
||||
const currencyKpis: KpiKv[] = [
|
||||
{ label: 'Årets resultat', value: incomeStatement.net_result },
|
||||
{ label: 'Likvida medel', value: cashPosition },
|
||||
{ label: 'Utestående kundfordringar', value: arLedger.total_outstanding },
|
||||
{ label: 'Förfallna kundfordringar', value: arLedger.total_overdue },
|
||||
{ label: 'Momsskuld (ruta 49)', value: vatLiability },
|
||||
{ label: 'Totala intäkter', value: incomeStatement.total_revenue },
|
||||
{ label: 'Totala kostnader', value: incomeStatement.total_expenses },
|
||||
]
|
||||
|
||||
const percentKpis: KpiKv[] = [
|
||||
// calculateGrossMargin returns percentage as `25.5` (i.e. percent units).
|
||||
// The xlsx percent format expects fractional values (0.255 → 25.50%).
|
||||
// Divide by 100 so the displayed value matches the in-app KPI tile.
|
||||
{ label: 'Bruttomarginal', value: scaleToFraction(calculateGrossMargin(incomeStatement)) },
|
||||
{ label: 'Kostnadsandel', value: scaleToFraction(calculateExpenseRatio(incomeStatement)) },
|
||||
]
|
||||
|
||||
const integerKpis: KpiKv[] = [
|
||||
{ label: 'Genomsnittliga betaldagar', value: calculateAvgPaymentDays(paidInvoices) },
|
||||
]
|
||||
|
||||
const monthRows: MonthRow[] = monthlyBreakdown.months
|
||||
|
||||
const compositionRows: CompositionRow[] = [
|
||||
{ klass: '4 — Material/varor', amount: Math.round(expenseComposition.class4 * 100) / 100 },
|
||||
{ klass: '5 — Externa kostnader', amount: Math.round(expenseComposition.class5 * 100) / 100 },
|
||||
{ klass: '6 — Externa kostnader', amount: Math.round(expenseComposition.class6 * 100) / 100 },
|
||||
{ klass: '7 — Personalkostnader', amount: Math.round(expenseComposition.class7 * 100) / 100 },
|
||||
]
|
||||
|
||||
const supplierRows: SupplierRow[] = topSuppliers
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Nyckeltal (kr)',
|
||||
columns: [textColumn('Nyckeltal'), currencyColumn('Värde')],
|
||||
rows: currencyKpis,
|
||||
mapRow: (r) => [r.label, r.value],
|
||||
},
|
||||
{
|
||||
name: 'Nyckeltal (%)',
|
||||
columns: [textColumn('Nyckeltal'), percentColumn('Värde')],
|
||||
rows: percentKpis,
|
||||
mapRow: (r) => [r.label, r.value],
|
||||
},
|
||||
{
|
||||
name: 'Nyckeltal (övrigt)',
|
||||
columns: [textColumn('Nyckeltal'), integerColumn('Värde')],
|
||||
rows: integerKpis,
|
||||
mapRow: (r) => [r.label, r.value],
|
||||
},
|
||||
{
|
||||
name: 'Månadsbrytning',
|
||||
columns: [
|
||||
textColumn('Månad'),
|
||||
currencyColumn('Intäkter'),
|
||||
currencyColumn('Kostnader'),
|
||||
currencyColumn('Netto'),
|
||||
],
|
||||
rows: monthRows,
|
||||
mapRow: (m) => [m.label, m.income, m.expenses, m.net],
|
||||
},
|
||||
{
|
||||
name: 'Kostnadssammansättning',
|
||||
columns: [textColumn('Kontoklass'), currencyColumn('Belopp')],
|
||||
rows: compositionRows,
|
||||
mapRow: (r) => [r.klass, r.amount],
|
||||
},
|
||||
{
|
||||
name: 'Topp leverantörer',
|
||||
columns: [textColumn('Leverantör'), currencyColumn('Totalt')],
|
||||
rows: supplierRows,
|
||||
mapRow: (r) => [r.supplier_name, r.total],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('nyckeltal', companyRow?.company_name ?? '', period.period_end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera nyckeltalsrapport' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function scaleToFraction(value: number | null): number | null {
|
||||
return value === null ? null : Math.round(value) / 100
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateMonthlyBreakdown } from '@/lib/reports/monthly-breakdown'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
try {
|
||||
const breakdown = await generateMonthlyBreakdown(supabase, companyId, periodId)
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Månadsbrytning',
|
||||
columns: [
|
||||
textColumn('Månad'),
|
||||
currencyColumn('Intäkter'),
|
||||
currencyColumn('Kostnader'),
|
||||
currencyColumn('Netto'),
|
||||
],
|
||||
rows: breakdown.months,
|
||||
mapRow: (m) => [m.label, m.income, m.expenses, m.net],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'manadsbrytning',
|
||||
companyRow?.company_name ?? '',
|
||||
period?.period_end ?? new Date().toISOString().slice(0, 10),
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera månadsbrytning' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateResultatrapport } from '@/lib/reports/resultatrapport'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface FlatRow {
|
||||
group: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
current_period: number
|
||||
prior_period: number
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateResultatrapport(supabase, companyId, periodId)
|
||||
|
||||
const rows: FlatRow[] = []
|
||||
for (const g of report.groups) {
|
||||
for (const r of g.rows) {
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
current_period: r.current_period,
|
||||
prior_period: r.prior_period,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: g.class_label,
|
||||
account_number: '',
|
||||
account_name: `Summa ${g.class_label}`,
|
||||
current_period: g.subtotal_current,
|
||||
prior_period: g.subtotal_prior,
|
||||
})
|
||||
}
|
||||
rows.push({
|
||||
group: 'Resultat',
|
||||
account_number: '',
|
||||
account_name: 'Årets resultat',
|
||||
current_period: report.net_result_current,
|
||||
prior_period: report.net_result_prior,
|
||||
})
|
||||
|
||||
const buffer = reportToWorkbook<FlatRow>([
|
||||
{
|
||||
name: 'Resultatrapport',
|
||||
columns: [
|
||||
textColumn('Grupp'),
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
currencyColumn('Aktuell period'),
|
||||
currencyColumn('Föregående period'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.group,
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.current_period,
|
||||
r.prior_period,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'resultatrapport',
|
||||
companyRow?.company_name ?? '',
|
||||
report.period.end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera resultatrapport' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { generateSalaryJournal } from '@/lib/reports/salary-journal'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
dateColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
function toDate(s: string): Date | null {
|
||||
if (!s) return null
|
||||
const d = new Date(s)
|
||||
return isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const year = parseInt(searchParams.get('year') || new Date().getFullYear().toString())
|
||||
const monthFrom = searchParams.get('month_from') ? parseInt(searchParams.get('month_from')!) : undefined
|
||||
const monthTo = searchParams.get('month_to') ? parseInt(searchParams.get('month_to')!) : undefined
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const report = await generateSalaryJournal(supabase, companyId, year, monthFrom, monthTo)
|
||||
|
||||
const buffer = reportToWorkbook([
|
||||
{
|
||||
name: 'Lönejournal',
|
||||
columns: [
|
||||
textColumn('Anställd'),
|
||||
textColumn('Personnr (4)'),
|
||||
textColumn('Anställning'),
|
||||
integerColumn('År'),
|
||||
integerColumn('Månad'),
|
||||
dateColumn('Utbetalningsdatum'),
|
||||
currencyColumn('Bruttolön'),
|
||||
currencyColumn('Skatt'),
|
||||
currencyColumn('Nettolön'),
|
||||
currencyColumn('Arbetsgivaravgifter'),
|
||||
currencyColumn('Semesterlönereservation'),
|
||||
currencyColumn('Semesterskuld avgifter'),
|
||||
currencyColumn('Total arbetsgivarkostnad'),
|
||||
integerColumn('Sjukdagar'),
|
||||
integerColumn('VAB-dagar'),
|
||||
integerColumn('Föräldradagar'),
|
||||
integerColumn('Semesterdagar uttagna'),
|
||||
textColumn('Status'),
|
||||
],
|
||||
rows: report.rows,
|
||||
mapRow: (r) => [
|
||||
r.employeeName,
|
||||
r.personnummerLast4,
|
||||
r.employmentType,
|
||||
r.periodYear,
|
||||
r.periodMonth,
|
||||
toDate(r.paymentDate),
|
||||
r.grossSalary,
|
||||
r.taxWithheld,
|
||||
r.netSalary,
|
||||
r.avgifterAmount,
|
||||
r.vacationAccrual,
|
||||
r.vacationAccrualAvgifter,
|
||||
r.totalEmployerCost,
|
||||
r.sickDays,
|
||||
r.vabDays,
|
||||
r.parentalDays,
|
||||
r.vacationDaysTaken,
|
||||
r.salaryRunStatus,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
// Use the period's last month-end as the filename anchor. For full-year
|
||||
// reports this is `YYYY-12-31`; for narrowed month ranges we approximate
|
||||
// with the end month's last day (good enough for filename ordering).
|
||||
const endMonth = monthTo ?? 12
|
||||
const periodAnchor = `${year}-${String(endMonth).padStart(2, '0')}-31`
|
||||
const filename = xlsxFilename(
|
||||
'lonejournal',
|
||||
companyRow?.company_name ?? '',
|
||||
periodAnchor,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera lönejournal' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/bookkeeping/currency-utils', () => ({
|
||||
resolveSekAmount: vi.fn((amount: number) => amount),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
interface QueryResult {
|
||||
data: unknown
|
||||
error: unknown
|
||||
}
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
supplier: { id: string; name: string } | null,
|
||||
invoicesResult: QueryResult,
|
||||
entriesResult: QueryResult
|
||||
) {
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'suppliers') {
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: supplier, error: null }),
|
||||
}
|
||||
}
|
||||
if (table === 'supplier_invoices') {
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(invoicesResult),
|
||||
}
|
||||
}
|
||||
// journal_entries
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: QueryResult) => void) => resolve(entriesResult),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/supplier-ledger/supplier/[supplierId]/invoices', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/supplier-ledger/supplier/sup-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when supplier is unknown', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/supplier-ledger/supplier/sup-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns supplier invoices with journal entries', async () => {
|
||||
const invoices = [
|
||||
{
|
||||
id: 'si-1',
|
||||
supplier_invoice_number: 'INV-7',
|
||||
invoice_date: '2026-05-10',
|
||||
due_date: '2026-06-10',
|
||||
total: 2500,
|
||||
paid_amount: 0,
|
||||
remaining_amount: 2500,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
registration_journal_entry_id: 'je-3',
|
||||
},
|
||||
]
|
||||
const entries = [
|
||||
{
|
||||
id: 'je-3',
|
||||
voucher_number: 33,
|
||||
voucher_series: 'B',
|
||||
description: 'Leverantörsfaktura INV-7',
|
||||
entry_date: '2026-05-10',
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(
|
||||
{ id: 'user-1' },
|
||||
{ id: 'sup-1', name: 'Office Supply AB' },
|
||||
{ data: invoices, error: null },
|
||||
{ data: entries, error: null }
|
||||
) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/supplier-ledger/supplier/sup-1/invoices'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ supplierId: 'sup-1' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
supplier_id: string
|
||||
supplier_name: string
|
||||
lines: Array<{
|
||||
supplier_invoice_id: string
|
||||
journal_entry_id: string
|
||||
voucher_number: number
|
||||
credit: number
|
||||
}>
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.supplier_id).toBe('sup-1')
|
||||
expect(body.data.supplier_name).toBe('Office Supply AB')
|
||||
expect(body.data.lines).toHaveLength(1)
|
||||
expect(body.data.lines[0].supplier_invoice_id).toBe('si-1')
|
||||
expect(body.data.lines[0].journal_entry_id).toBe('je-3')
|
||||
expect(body.data.lines[0].voucher_number).toBe(33)
|
||||
expect(body.data.lines[0].credit).toBe(2500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,143 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import { resolveSekAmount } from '@/lib/bookkeeping/currency-utils'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
|
||||
/**
|
||||
* GET /api/reports/supplier-ledger/supplier/[supplierId]/invoices
|
||||
*
|
||||
* Returns the supplier invoices behind a supplier's outstanding balance.
|
||||
* Each row's `journal_entry_id` points at the registration journal entry
|
||||
* (when posted) so the UI can link to `/bookkeeping/[id]`.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ supplierId: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { supplierId } = await params
|
||||
|
||||
const { data: supplier } = await supabase
|
||||
.from('suppliers')
|
||||
.select('id, name')
|
||||
.eq('id', supplierId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!supplier) {
|
||||
return NextResponse.json({ error: 'Leverantör saknas' }, { status: 404 })
|
||||
}
|
||||
|
||||
// Mirror `generateSupplierLedger`'s filter: registered/approved/partially
|
||||
// paid/overdue invoices that still have an outstanding balance.
|
||||
const { data, error } = await supabase
|
||||
.from('supplier_invoices')
|
||||
.select(`
|
||||
id,
|
||||
supplier_invoice_number,
|
||||
invoice_date,
|
||||
due_date,
|
||||
total,
|
||||
paid_amount,
|
||||
remaining_amount,
|
||||
currency,
|
||||
exchange_rate,
|
||||
registration_journal_entry_id
|
||||
`)
|
||||
.eq('company_id', companyId)
|
||||
.eq('supplier_id', supplierId)
|
||||
.in('status', ['registered', 'approved', 'partially_paid', 'overdue'])
|
||||
.order('invoice_date', { ascending: true })
|
||||
.limit(PAGE_LIMIT)
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const invoices = (data || []) as any[]
|
||||
|
||||
// Pull the registration entries in one batch to get voucher numbers.
|
||||
const entryIds = invoices
|
||||
.map((i) => i.registration_journal_entry_id)
|
||||
.filter((id): id is string => !!id)
|
||||
const entryMap = new Map<
|
||||
string,
|
||||
{ voucher_number: number; voucher_series: string; description: string | null; entry_date: string }
|
||||
>()
|
||||
if (entryIds.length > 0) {
|
||||
const { data: entries } = await supabase
|
||||
.from('journal_entries')
|
||||
.select('id, voucher_number, voucher_series, description, entry_date')
|
||||
.eq('company_id', companyId)
|
||||
.in('id', entryIds)
|
||||
.in('status', ['posted', 'reversed'])
|
||||
for (const e of entries || []) {
|
||||
entryMap.set(e.id, {
|
||||
voucher_number: e.voucher_number,
|
||||
voucher_series: e.voucher_series || 'A',
|
||||
description: e.description,
|
||||
entry_date: e.entry_date,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const lines: (ReportSourceLine & {
|
||||
supplier_invoice_id: string
|
||||
supplier_invoice_number: string
|
||||
remaining_sek: number | null
|
||||
currency: string
|
||||
paid_amount: number
|
||||
due_date: string
|
||||
})[] = invoices.map((inv) => {
|
||||
const entry = inv.registration_journal_entry_id
|
||||
? entryMap.get(inv.registration_journal_entry_id)
|
||||
: undefined
|
||||
|
||||
const remaining = Number(inv.remaining_amount) || 0
|
||||
const isFx = inv.currency && inv.currency !== 'SEK'
|
||||
const hasRate = inv.exchange_rate != null && Number(inv.exchange_rate) > 0
|
||||
const remainingSek =
|
||||
isFx && !hasRate
|
||||
? null
|
||||
: resolveSekAmount(remaining, null, inv.currency, inv.exchange_rate)
|
||||
|
||||
return {
|
||||
journal_entry_id: inv.registration_journal_entry_id || '',
|
||||
voucher_number: entry?.voucher_number ?? 0,
|
||||
voucher_series: entry?.voucher_series ?? 'A',
|
||||
date: inv.invoice_date || entry?.entry_date || '',
|
||||
description:
|
||||
entry?.description ??
|
||||
`Leverantörsfaktura ${inv.supplier_invoice_number || ''}`,
|
||||
debit: 0,
|
||||
// For an unpaid AP entry, the open balance is a credit on 2440.
|
||||
credit: remainingSek ?? remaining,
|
||||
supplier_invoice_id: inv.id,
|
||||
supplier_invoice_number: inv.supplier_invoice_number || '',
|
||||
remaining_sek: remainingSek,
|
||||
currency: inv.currency || 'SEK',
|
||||
paid_amount: Number(inv.paid_amount) || 0,
|
||||
due_date: inv.due_date,
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
supplier_id: supplier.id,
|
||||
supplier_name: supplier.name,
|
||||
lines,
|
||||
next_cursor: null,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateSupplierLedger } from '@/lib/reports/supplier-ledger'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
interface AgingRow {
|
||||
supplier_name: string
|
||||
current: number
|
||||
days_1_30: number
|
||||
days_31_60: number
|
||||
days_61_90: number
|
||||
days_90_plus: number
|
||||
total_outstanding: number
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const asOfDate = searchParams.get('as_of_date') || undefined
|
||||
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
try {
|
||||
const ledger = await generateSupplierLedger(supabase, companyId, asOfDate)
|
||||
|
||||
const rows: AgingRow[] = ledger.entries.map((e) => ({
|
||||
supplier_name: e.supplier_name,
|
||||
current: e.current,
|
||||
days_1_30: e.days_1_30,
|
||||
days_31_60: e.days_31_60,
|
||||
days_61_90: e.days_61_90,
|
||||
days_90_plus: e.days_90_plus,
|
||||
total_outstanding: e.total_outstanding,
|
||||
}))
|
||||
|
||||
const buffer = reportToWorkbook<AgingRow>([
|
||||
{
|
||||
name: 'Leverantörsreskontra',
|
||||
columns: [
|
||||
textColumn('Leverantör'),
|
||||
currencyColumn('Ej förfallet'),
|
||||
currencyColumn('1-30 dagar'),
|
||||
currencyColumn('31-60 dagar'),
|
||||
currencyColumn('61-90 dagar'),
|
||||
currencyColumn('90+ dagar'),
|
||||
currencyColumn('Totalt utestående'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [
|
||||
r.supplier_name,
|
||||
r.current,
|
||||
r.days_1_30,
|
||||
r.days_31_60,
|
||||
r.days_61_90,
|
||||
r.days_90_plus,
|
||||
r.total_outstanding,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'leverantorsreskontra',
|
||||
companyRow?.company_name ?? '',
|
||||
asOfDate ?? new Date().toISOString().slice(0, 10),
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera leverantörsreskontra' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
interface AuthShape {
|
||||
auth: { getUser: ReturnType<typeof vi.fn> }
|
||||
from: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
account: { account_number: string; account_name: string } | null,
|
||||
linesResult: { data: unknown; error: unknown }
|
||||
): AuthShape {
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation((table: string) => {
|
||||
if (table === 'chart_of_accounts') {
|
||||
const chain = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: account, error: null }),
|
||||
}
|
||||
return chain
|
||||
}
|
||||
// journal_entry_lines
|
||||
const chain = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
gte: vi.fn().mockReturnThis(),
|
||||
lte: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
or: vi.fn().mockReturnThis(),
|
||||
then: (resolve: (v: unknown) => void) => resolve(linesResult),
|
||||
}
|
||||
return chain
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/trial-balance/account/[accountNumber]/sources', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/1930/sources',
|
||||
{ searchParams: { fiscal_period_id: 'period-1' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '1930' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when fiscal_period_id is missing', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/1930/sources'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '1930' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when account is unknown for the company', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/9999/sources',
|
||||
{ searchParams: { fiscal_period_id: 'period-1' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '9999' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns mapped lines for an account', async () => {
|
||||
const linesData = [
|
||||
{
|
||||
debit_amount: 1250,
|
||||
credit_amount: 0,
|
||||
journal_entry_id: 'je-1',
|
||||
journal_entries: {
|
||||
id: 'je-1',
|
||||
voucher_number: 7,
|
||||
voucher_series: 'A',
|
||||
entry_date: '2026-05-02',
|
||||
description: 'Provision',
|
||||
status: 'posted',
|
||||
company_id: 'company-1',
|
||||
fiscal_period_id: 'period-1',
|
||||
},
|
||||
},
|
||||
{
|
||||
debit_amount: 0,
|
||||
credit_amount: 700,
|
||||
journal_entry_id: 'je-2',
|
||||
journal_entries: {
|
||||
id: 'je-2',
|
||||
voucher_number: 8,
|
||||
voucher_series: 'A',
|
||||
entry_date: '2026-05-03',
|
||||
description: 'Återbet',
|
||||
status: 'posted',
|
||||
company_id: 'company-1',
|
||||
fiscal_period_id: 'period-1',
|
||||
},
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(
|
||||
{ id: 'user-1' },
|
||||
{ account_number: '1930', account_name: 'Företagskonto' },
|
||||
{ data: linesData, error: null }
|
||||
) as never
|
||||
)
|
||||
|
||||
const req = createMockRequest(
|
||||
'/api/reports/trial-balance/account/1930/sources',
|
||||
{ searchParams: { fiscal_period_id: 'period-1' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ accountNumber: '1930' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
account_number: string
|
||||
account_name: string
|
||||
lines: Array<{ voucher_number: number; debit: number; credit: number; journal_entry_id: string }>
|
||||
next_cursor: string | null
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.account_number).toBe('1930')
|
||||
expect(body.data.account_name).toBe('Företagskonto')
|
||||
expect(body.data.lines).toHaveLength(2)
|
||||
expect(body.data.lines[0].voucher_number).toBe(7)
|
||||
expect(body.data.lines[0].debit).toBe(1250)
|
||||
expect(body.data.lines[0].journal_entry_id).toBe('je-1')
|
||||
expect(body.data.lines[1].credit).toBe(700)
|
||||
expect(body.data.next_cursor).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,138 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
|
||||
/**
|
||||
* GET /api/reports/trial-balance/account/[accountNumber]/sources
|
||||
*
|
||||
* Returns the journal entry lines for one account in a fiscal period,
|
||||
* ordered by entry date then voucher number ASC. Used by the trial balance
|
||||
* drilldown UI to show the verifikat behind an aggregated row.
|
||||
*
|
||||
* Pagination uses an opaque cursor of `<entry_date>|<voucher_number>` for
|
||||
* the last seen row; pass it back as `cursor` to continue.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ accountNumber: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { accountNumber } = await params
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const fiscalPeriodId = searchParams.get('fiscal_period_id')
|
||||
const cursor = searchParams.get('cursor')
|
||||
|
||||
if (!fiscalPeriodId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'fiscal_period_id is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// Look up account name (and verify account belongs to the company)
|
||||
const { data: account } = await supabase
|
||||
.from('chart_of_accounts')
|
||||
.select('account_number, account_name')
|
||||
.eq('company_id', companyId)
|
||||
.eq('account_number', accountNumber)
|
||||
.maybeSingle()
|
||||
|
||||
if (!account) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Konto saknas' },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Pull all lines on this account in this period. We rely on the same
|
||||
// join+filter pattern as `generateTrialBalance`. Pagination is server-side
|
||||
// via cursor so even an account with tens of thousands of rows stays cheap.
|
||||
let query = supabase
|
||||
.from('journal_entry_lines')
|
||||
.select(`
|
||||
debit_amount,
|
||||
credit_amount,
|
||||
journal_entry_id,
|
||||
journal_entries!inner(
|
||||
id,
|
||||
voucher_number,
|
||||
voucher_series,
|
||||
entry_date,
|
||||
description,
|
||||
status,
|
||||
company_id,
|
||||
fiscal_period_id
|
||||
)
|
||||
`)
|
||||
.eq('account_number', accountNumber)
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.eq('journal_entries.fiscal_period_id', fiscalPeriodId)
|
||||
.in('journal_entries.status', ['posted', 'reversed'])
|
||||
.order('entry_date', { foreignTable: 'journal_entries', ascending: true })
|
||||
.order('voucher_number', { foreignTable: 'journal_entries', ascending: true })
|
||||
.limit(PAGE_LIMIT + 1)
|
||||
|
||||
if (cursor) {
|
||||
// Cursor format: <iso-date>|<voucher_number>
|
||||
const [cursorDate, cursorVoucher] = cursor.split('|')
|
||||
const cursorVoucherNum = parseInt(cursorVoucher, 10)
|
||||
if (!cursorDate || isNaN(cursorVoucherNum)) {
|
||||
return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 })
|
||||
}
|
||||
// Filter for rows strictly after the cursor (date>cur OR same date & voucher>cur).
|
||||
// Supabase doesn't expose tuple compare, so use an `or()` clause.
|
||||
query = query.or(
|
||||
`entry_date.gt.${cursorDate},and(entry_date.eq.${cursorDate},voucher_number.gt.${cursorVoucherNum})`,
|
||||
{ foreignTable: 'journal_entries' }
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const rows = (data || []) as any[]
|
||||
|
||||
const lines: ReportSourceLine[] = rows
|
||||
.slice(0, PAGE_LIMIT)
|
||||
.map((row) => ({
|
||||
journal_entry_id: row.journal_entries.id,
|
||||
voucher_number: row.journal_entries.voucher_number,
|
||||
voucher_series: row.journal_entries.voucher_series || 'A',
|
||||
date: row.journal_entries.entry_date,
|
||||
description: row.journal_entries.description || '',
|
||||
debit: Math.round((Number(row.debit_amount) || 0) * 100) / 100,
|
||||
credit: Math.round((Number(row.credit_amount) || 0) * 100) / 100,
|
||||
}))
|
||||
|
||||
// If we got more than PAGE_LIMIT rows back, the next cursor points at the
|
||||
// last delivered row so the next call resumes from after it.
|
||||
let next_cursor: string | null = null
|
||||
if (rows.length > PAGE_LIMIT && lines.length > 0) {
|
||||
const last = lines[lines.length - 1]
|
||||
next_cursor = `${last.date}|${last.voucher_number}`
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
account_number: account.account_number,
|
||||
account_name: account.account_name,
|
||||
lines,
|
||||
next_cursor,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { generateTrialBalance } from '@/lib/reports/trial-balance'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
integerColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import type { TrialBalanceRow } from '@/types'
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodId = searchParams.get('period_id')
|
||||
|
||||
if (!periodId) {
|
||||
return NextResponse.json({ error: 'period_id is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: period }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Räkenskapsperioden kunde inte läsas.' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateTrialBalance(supabase, companyId, periodId)
|
||||
|
||||
const buffer = reportToWorkbook<TrialBalanceRow>([
|
||||
{
|
||||
name: 'Saldobalans',
|
||||
columns: [
|
||||
textColumn('Konto'),
|
||||
textColumn('Kontonamn'),
|
||||
integerColumn('Klass'),
|
||||
currencyColumn('IB Debet'),
|
||||
currencyColumn('IB Kredit'),
|
||||
currencyColumn('Period Debet'),
|
||||
currencyColumn('Period Kredit'),
|
||||
currencyColumn('UB Debet'),
|
||||
currencyColumn('UB Kredit'),
|
||||
],
|
||||
rows: report.rows,
|
||||
mapRow: (r) => [
|
||||
r.account_number,
|
||||
r.account_name,
|
||||
r.account_class,
|
||||
r.opening_debit,
|
||||
r.opening_credit,
|
||||
r.period_debit,
|
||||
r.period_credit,
|
||||
r.closing_debit,
|
||||
r.closing_credit,
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename('saldobalans', companyRow?.company_name ?? '', period.period_end)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera saldobalans' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, createMockRouteParams } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
function buildSupabase(
|
||||
user: { id: string } | null,
|
||||
linesResult: { data: unknown; error: unknown }
|
||||
) {
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user } }),
|
||||
},
|
||||
from: vi.fn().mockImplementation(() => ({
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
in: vi.fn().mockReturnThis(),
|
||||
gte: vi.fn().mockReturnThis(),
|
||||
lte: vi.fn().mockReturnThis(),
|
||||
order: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn().mockReturnThis(),
|
||||
or: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: null, error: null }),
|
||||
then: (resolve: (v: unknown) => void) => resolve(linesResult),
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/vat-declaration/ruta/[ruta]/sources', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase(null, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/10/sources',
|
||||
{ searchParams: { periodType: 'monthly', year: '2026', period: '5' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '10' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when period params are missing', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/10/sources'
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '10' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when ruta has no underlying BAS accounts', async () => {
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, { data: [], error: null }) as never
|
||||
)
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/99/sources',
|
||||
{ searchParams: { periodType: 'monthly', year: '2026', period: '5' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '99' }))
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('happy path: returns mapped lines for ruta10', async () => {
|
||||
const linesData = [
|
||||
{
|
||||
account_number: '2611',
|
||||
debit_amount: 0,
|
||||
credit_amount: 250,
|
||||
journal_entries: {
|
||||
id: 'je-1',
|
||||
voucher_number: 12,
|
||||
voucher_series: 'A',
|
||||
entry_date: '2026-05-12',
|
||||
description: 'Faktura 1001',
|
||||
status: 'posted',
|
||||
company_id: 'company-1',
|
||||
},
|
||||
},
|
||||
]
|
||||
mockCreateClient.mockResolvedValue(
|
||||
buildSupabase({ id: 'user-1' }, { data: linesData, error: null }) as never
|
||||
)
|
||||
|
||||
const req = createMockRequest(
|
||||
'/api/reports/vat-declaration/ruta/10/sources',
|
||||
{ searchParams: { periodType: 'monthly', year: '2026', period: '5' } }
|
||||
)
|
||||
const res = await GET(req, createMockRouteParams({ ruta: '10' }))
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const body = (await res.json()) as {
|
||||
data: {
|
||||
ruta: string
|
||||
lines: Array<{ voucher_number: number; credit: number }>
|
||||
}
|
||||
}
|
||||
|
||||
expect(body.data.ruta).toBe('ruta10')
|
||||
expect(body.data.lines).toHaveLength(1)
|
||||
expect(body.data.lines[0].voucher_number).toBe(12)
|
||||
expect(body.data.lines[0].credit).toBe(250)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
ACCOUNT_RUTA,
|
||||
calculatePeriodDates,
|
||||
} from '@/lib/reports/vat-declaration'
|
||||
import type { ReportSourceLine } from '@/lib/reports/source-lines'
|
||||
import type { VatDeclarationRutor, VatPeriodType } from '@/types'
|
||||
|
||||
/**
|
||||
* GET /api/reports/vat-declaration/ruta/[ruta]/sources
|
||||
*
|
||||
* Returns the journal entry lines that contribute to a single ruta on the
|
||||
* VAT declaration. The mapping ruta → BAS accounts is the inverse of
|
||||
* `ACCOUNT_RUTA` in `lib/reports/vat-declaration.ts`.
|
||||
*
|
||||
* Period can be specified either via:
|
||||
* ?periodType=monthly|quarterly|yearly&year=2026&period=5
|
||||
* ?fiscal_period_id=<uuid>
|
||||
*
|
||||
* The periodType form mirrors the way the main VAT report is fetched.
|
||||
*/
|
||||
const PAGE_LIMIT = 500
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ ruta: string }> }
|
||||
) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
const { ruta: rutaParam } = await params
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const cursor = searchParams.get('cursor')
|
||||
|
||||
// Normalise ruta param to the keyof VatDeclarationRutor (`ruta10`, `ruta48`).
|
||||
const rutaKey = (
|
||||
rutaParam.startsWith('ruta') ? rutaParam : `ruta${rutaParam}`
|
||||
) as keyof VatDeclarationRutor
|
||||
|
||||
// Invert ACCOUNT_RUTA: which BAS accounts feed this ruta?
|
||||
const accountsForRuta = Object.entries(ACCOUNT_RUTA)
|
||||
.filter(([, m]) => m.box === rutaKey)
|
||||
.map(([acc]) => acc)
|
||||
|
||||
if (accountsForRuta.length === 0) {
|
||||
return NextResponse.json(
|
||||
{ error: `Ruta ${rutaParam} har inga underliggande konton` },
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
// Resolve the period — either by fiscal_period_id or periodType/year/period.
|
||||
let start: string | null = null
|
||||
let end: string | null = null
|
||||
const fiscalPeriodId = searchParams.get('fiscal_period_id')
|
||||
if (fiscalPeriodId) {
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', fiscalPeriodId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (!period) {
|
||||
return NextResponse.json({ error: 'Period saknas' }, { status: 404 })
|
||||
}
|
||||
start = period.period_start
|
||||
end = period.period_end
|
||||
} else {
|
||||
const periodType = searchParams.get('periodType') as VatPeriodType | null
|
||||
const yearStr = searchParams.get('year')
|
||||
const periodStr = searchParams.get('period')
|
||||
if (!periodType || !yearStr || !periodStr) {
|
||||
return NextResponse.json(
|
||||
{ error: 'periodType/year/period or fiscal_period_id is required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
const year = parseInt(yearStr, 10)
|
||||
const periodNum = parseInt(periodStr, 10)
|
||||
if (isNaN(year) || isNaN(periodNum)) {
|
||||
return NextResponse.json({ error: 'Invalid period' }, { status: 400 })
|
||||
}
|
||||
const dates = calculatePeriodDates(periodType, year, periodNum)
|
||||
start = dates.start
|
||||
end = dates.end
|
||||
}
|
||||
|
||||
let query = supabase
|
||||
.from('journal_entry_lines')
|
||||
.select(`
|
||||
account_number,
|
||||
debit_amount,
|
||||
credit_amount,
|
||||
journal_entries!inner(
|
||||
id,
|
||||
voucher_number,
|
||||
voucher_series,
|
||||
entry_date,
|
||||
description,
|
||||
status,
|
||||
company_id
|
||||
)
|
||||
`)
|
||||
.in('account_number', accountsForRuta)
|
||||
.eq('journal_entries.company_id', companyId)
|
||||
.in('journal_entries.status', ['posted', 'reversed'])
|
||||
.gte('journal_entries.entry_date', start)
|
||||
.lte('journal_entries.entry_date', end)
|
||||
.order('entry_date', { foreignTable: 'journal_entries', ascending: true })
|
||||
.order('voucher_number', { foreignTable: 'journal_entries', ascending: true })
|
||||
.limit(PAGE_LIMIT + 1)
|
||||
|
||||
if (cursor) {
|
||||
const [cursorDate, cursorVoucher] = cursor.split('|')
|
||||
const cursorVoucherNum = parseInt(cursorVoucher, 10)
|
||||
if (!cursorDate || isNaN(cursorVoucherNum)) {
|
||||
return NextResponse.json({ error: 'Invalid cursor' }, { status: 400 })
|
||||
}
|
||||
query = query.or(
|
||||
`entry_date.gt.${cursorDate},and(entry_date.eq.${cursorDate},voucher_number.gt.${cursorVoucherNum})`,
|
||||
{ foreignTable: 'journal_entries' }
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 })
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const rows = (data || []) as any[]
|
||||
|
||||
const lines: ReportSourceLine[] = rows
|
||||
.slice(0, PAGE_LIMIT)
|
||||
.map((row) => ({
|
||||
journal_entry_id: row.journal_entries.id,
|
||||
voucher_number: row.journal_entries.voucher_number,
|
||||
voucher_series: row.journal_entries.voucher_series || 'A',
|
||||
date: row.journal_entries.entry_date,
|
||||
description: row.journal_entries.description || '',
|
||||
debit: Math.round((Number(row.debit_amount) || 0) * 100) / 100,
|
||||
credit: Math.round((Number(row.credit_amount) || 0) * 100) / 100,
|
||||
}))
|
||||
|
||||
let next_cursor: string | null = null
|
||||
if (rows.length > PAGE_LIMIT && lines.length > 0) {
|
||||
const last = lines[lines.length - 1]
|
||||
next_cursor = `${last.date}|${last.voucher_number}`
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
ruta: rutaKey,
|
||||
lines,
|
||||
next_cursor,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
calculateVatDeclaration,
|
||||
formatPeriodLabel,
|
||||
} from '@/lib/reports/vat-declaration'
|
||||
import { requireCompanyId } from '@/lib/company/context'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
currencyColumn,
|
||||
xlsxFilename,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
import {
|
||||
VAT_RUTA_LABELS,
|
||||
type VatPeriodType,
|
||||
type VatDeclarationRutor,
|
||||
type AccountingMethod,
|
||||
} from '@/types'
|
||||
|
||||
interface RutaRow {
|
||||
ruta: string
|
||||
label: string
|
||||
amount: number
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const supabase = await createClient()
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const companyId = await requireCompanyId(supabase, user.id)
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const periodType = searchParams.get('periodType') as VatPeriodType | null
|
||||
const yearStr = searchParams.get('year')
|
||||
const periodStr = searchParams.get('period')
|
||||
|
||||
if (!periodType || !yearStr || !periodStr) {
|
||||
return NextResponse.json(
|
||||
{ error: 'periodType, year, and period are required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
if (!['monthly', 'quarterly', 'yearly'].includes(periodType)) {
|
||||
return NextResponse.json({ error: 'Invalid periodType' }, { status: 400 })
|
||||
}
|
||||
|
||||
const year = parseInt(yearStr, 10)
|
||||
const period = parseInt(periodStr, 10)
|
||||
if (isNaN(year) || isNaN(period)) {
|
||||
return NextResponse.json({ error: 'Invalid year or period' }, { status: 400 })
|
||||
}
|
||||
|
||||
const [{ data: settings }, { data: companyRow }] = await Promise.all([
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('accounting_method')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single(),
|
||||
])
|
||||
|
||||
const accountingMethod = (settings?.accounting_method as AccountingMethod) || 'accrual'
|
||||
|
||||
try {
|
||||
const declaration = await calculateVatDeclaration(
|
||||
supabase, companyId, periodType, year, period, accountingMethod,
|
||||
)
|
||||
|
||||
const rows: RutaRow[] = (Object.keys(declaration.rutor) as (keyof VatDeclarationRutor)[]).map(
|
||||
(key) => ({
|
||||
ruta: key.replace(/^ruta/, 'Ruta '),
|
||||
label: VAT_RUTA_LABELS[key],
|
||||
amount: declaration.rutor[key],
|
||||
}),
|
||||
)
|
||||
|
||||
const buffer = reportToWorkbook<RutaRow>([
|
||||
{
|
||||
name: `Moms ${formatPeriodLabel(periodType, year, period)}`,
|
||||
columns: [
|
||||
textColumn('Ruta'),
|
||||
textColumn('Beskrivning'),
|
||||
currencyColumn('Belopp'),
|
||||
],
|
||||
rows,
|
||||
mapRow: (r) => [r.ruta, r.label, r.amount],
|
||||
},
|
||||
])
|
||||
|
||||
const filename = xlsxFilename(
|
||||
'momsdeklaration',
|
||||
companyRow?.company_name ?? '',
|
||||
declaration.period.end,
|
||||
)
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? err.message : 'Kunde inte generera momsdeklaration' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ vi.mock('@react-pdf/renderer', () => ({
|
||||
}))
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue({}),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import { z } from 'zod'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { registerEndpoint } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
@@ -148,6 +149,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
|
||||
let pdfBuffer: Buffer
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(company as CompanySettings)
|
||||
pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: typed as Invoice,
|
||||
@@ -155,6 +157,7 @@ export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }
|
||||
items,
|
||||
company: company as CompanySettings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
|
||||
@@ -71,6 +71,7 @@ vi.mock('@/lib/email/invoice-templates', () => ({
|
||||
|
||||
vi.mock('@/lib/invoices/pdf-template', () => ({
|
||||
InvoicePDF: vi.fn().mockReturnValue({}),
|
||||
brandingFromCompanySettings: vi.fn().mockReturnValue({}),
|
||||
}))
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ import { registerEndpoint } from '@/lib/api/v1/registry'
|
||||
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
|
||||
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
@@ -264,6 +265,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
const isFreshAllocation = !typed.invoice_number
|
||||
if (isFreshAllocation) {
|
||||
try {
|
||||
const preflight = prepareInvoicePdfRender(settings)
|
||||
await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: { ...(typed as Invoice), invoice_number: 'F-PREVIEW' },
|
||||
@@ -271,6 +273,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
items,
|
||||
company: settings,
|
||||
originalInvoiceNumber,
|
||||
branding: preflight.branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
@@ -352,6 +355,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
|
||||
let pdfBuffer: Buffer
|
||||
try {
|
||||
const { branding } = prepareInvoicePdfRender(settings)
|
||||
pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: renderableInvoice,
|
||||
@@ -359,6 +363,7 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
items,
|
||||
company: settings,
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
|
||||
Reference in New Issue
Block a user