Add/stripe invoice link (#998)
* feat(supplier-invoices): show registered invoices under "Att betala" with inline approve Registered supplier invoices are already booked as debt (2440) but were hidden from the "Att betala" tab until approved, which confused users. The tab now shows registered invoices too, marked "Ej godkand" with a compact inline approve button. Approval remains the gate for payment, not visibility; status model and approve API untouched. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(reports): add date range filter to huvudbok (kontoanalys) Mounts the existing ReportDateRange control on /reports/huvudbok so the ledger can be narrowed to any date range within the fiscal year, matching Fortnox kontoanalys. Lines before the range roll into each account's opening balance so running balances stay correct at the range start; lines after the range are dropped. Applies to the XLSX export too. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(invoices): add optional payment link on invoices (paste-link MVP) The user pastes a payment link created in their PSP dashboard (e.g. a Stripe Payment Link) onto an invoice. The recipient gets a "Betala online" button in the invoice email and a QR code + clickable link in the PDF payment box. No PSP integration server-side: this is the demand probe; a future Stripe Connect integration would auto-fill the same column. - invoices.payment_link_url (migration 20260709090000), https-only + 2048-char cap enforced in CreateInvoiceSchema; empty string normalises to undefined and build-invoice-write always writes a concrete value so clearing the field on a draft edit NULLs the column - editor field (real invoices only) with one-link-per-invoice hint; strings in sv+en (messages landed via e0e11066) - email button (customer.language, hidden for credit notes/proforma/ delivery notes, URL escaped for the href attribute) + URL in the plain-text part - PDF QR + link row following the Swish QR pattern; wired into send, download and preview routes - derived documents (credit note, proforma convert, recurring) do NOT copy the link: it encodes one amount for one specific invoice - MCP gnubok_create_invoice accepts payment_link_url (validated at staging and re-checked in the commit executor); v1 API exposes the column; tools/list token ceiling bumped 45K -> 45.5K (ledger entry in payload-size.bench.test.ts, headroom was <10 tokens) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(invoices): show oresavrundning on editor/form totals, supplier list and invoice email The rounding logic (getDisplayTotal) was correct but only applied on the PDF, invoice list/detail and review dialog. The invoice editor summary, the supplier invoice form totals and the supplier invoice list showed the raw ore total right next to the toggle, and the invoice email said "Att betala" with the unrounded invoice.total while the attached PDF showed the rounded amount (and the email also ignored the ROT/RUT deduction). Extract the PDF's Att betala block into getAmountToPay (lib/invoices/rounding.ts) and point PDF + email at it so they cannot drift; behavior-identical refactor for the PDF. Booked amounts stay ore-exact; display-only as designed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): adapt huvudbok date-range tests to the two-step entry-lines fetch The date-range tests (0969168f) mocked the old single-query shape with the parent entry embedded on each line; main's refactor (fetchEntryLines) queries journal_entries first and reattaches. Queue entry rows like the other tests so the merge of the two features is actually exercised. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(invoices): fetch full invoice projection in v1 send so ROT/RUT deduction and payment link reach the PDF and email The v1 send route's hand-rolled column list omitted deduction_total, deduction_personnummer_last4, payment_link_url and the item-level ROT/RUT fields, so invoices sent via the public API overstated 'Att betala' and dropped the deduction box. Reuse the shared INVOICE_FULL_COLUMNS/INVOICE_ITEM_FULL_COLUMNS so the send row can never drift from the GET shape again. Also harden the supplier-invoice inline approve: a thrown fetch left the button stuck spinning; failures now refetch the true server state. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
0ef5593388
commit
7d7f604e00
@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings } from '@/types'
|
||||
|
||||
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
@@ -60,6 +60,7 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
company as CompanySettings,
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(company as CompanySettings, invoice as Invoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(invoice as Invoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: invoice as Invoice,
|
||||
@@ -69,6 +70,7 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
paymentLinkQrDataUrl,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -3,7 +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, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getEmailService } from '@/lib/email/service'
|
||||
import {
|
||||
generateInvoiceEmailHtml,
|
||||
@@ -141,6 +141,7 @@ export const POST = withRouteContext(
|
||||
company as CompanySettings,
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(company as CompanySettings, renderableInvoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(renderableInvoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: renderableInvoice,
|
||||
@@ -150,6 +151,7 @@ export const POST = withRouteContext(
|
||||
originalInvoiceNumber,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
paymentLinkQrDataUrl,
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { renderToBuffer } from '@react-pdf/renderer'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { InvoicePDF } from '@/lib/invoices/pdf-template'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { prepareInvoicePdfRender, buildSwishQrDataUrl, buildPaymentLinkQrDataUrl } from '@/lib/invoices/pdf-render-helpers'
|
||||
import { getVatRules } from '@/lib/invoices/vat-rules'
|
||||
import type { Invoice, InvoiceItem, Customer, CompanySettings, InvoiceDocumentType } from '@/types'
|
||||
|
||||
@@ -14,7 +14,18 @@ import type { Invoice, InvoiceItem, Customer, CompanySettings, InvoiceDocumentTy
|
||||
*/
|
||||
export const POST = withRouteContext('invoice.preview_pdf', async (request, { supabase, user, companyId }) => {
|
||||
const body = await request.json()
|
||||
const { customer_id, invoice_date, due_date, delivery_date, currency, items, your_reference, our_reference, notes, document_type, invoice_number } = body
|
||||
const { customer_id, invoice_date, due_date, delivery_date, currency, items, your_reference, our_reference, notes, document_type, invoice_number, payment_link_url } = body
|
||||
|
||||
// Preview-only https gate, mirroring CreateInvoiceSchema: the value is
|
||||
// rendered as a clickable link + QR in the preview PDF.
|
||||
const previewPaymentLink = (() => {
|
||||
if (typeof payment_link_url !== 'string' || !payment_link_url.trim()) return null
|
||||
try {
|
||||
return new URL(payment_link_url).protocol === 'https:' ? payment_link_url.trim() : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})()
|
||||
|
||||
if (!items || items.length === 0) {
|
||||
return NextResponse.json({ error: 'Rader krävs' }, { status: 400 })
|
||||
@@ -156,6 +167,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, { su
|
||||
your_reference: your_reference || null,
|
||||
our_reference: our_reference || null,
|
||||
notes: notes || null,
|
||||
payment_link_url: previewPaymentLink,
|
||||
reverse_charge_text: vatRules.reverseChargeText || null,
|
||||
credited_invoice_id: null,
|
||||
document_type: docType,
|
||||
@@ -171,6 +183,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, { su
|
||||
company as CompanySettings,
|
||||
)
|
||||
const swishQrDataUrl = await buildSwishQrDataUrl(company as CompanySettings, previewInvoice)
|
||||
const paymentLinkQrDataUrl = await buildPaymentLinkQrDataUrl(previewInvoice)
|
||||
const pdfBuffer = await renderToBuffer(
|
||||
InvoicePDF({
|
||||
invoice: previewInvoice,
|
||||
@@ -180,6 +193,7 @@ export const POST = withRouteContext('invoice.preview_pdf', async (request, { su
|
||||
isPreview: true,
|
||||
branding,
|
||||
swishQrDataUrl,
|
||||
paymentLinkQrDataUrl,
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/reports/general-ledger', () => ({
|
||||
generateGeneralLedger: vi.fn(),
|
||||
}))
|
||||
|
||||
import { generateGeneralLedger } from '@/lib/reports/general-ledger'
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockGenerate = vi.mocked(generateGeneralLedger)
|
||||
|
||||
function authed() {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
}
|
||||
|
||||
function unauthed() {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
}
|
||||
|
||||
const PERIOD = { period_start: '2026-01-01', period_end: '2026-12-31' }
|
||||
|
||||
// Next.js 16 static-route second arg
|
||||
const noParams = { params: Promise.resolve({}) }
|
||||
|
||||
const EMPTY_REPORT = {
|
||||
accounts: [],
|
||||
period: { start: '2026-01-01', end: '2026-12-31' },
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
authed()
|
||||
})
|
||||
|
||||
describe('GET /api/reports/general-ledger', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
unauthed()
|
||||
const res = await GET(createMockRequest('/api/reports/general-ledger'), noParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when period_id is missing', async () => {
|
||||
const res = await GET(createMockRequest('/api/reports/general-ledger'), noParams)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 for a malformed from_date', async () => {
|
||||
enqueue({ data: PERIOD }) // fiscal_periods
|
||||
const res = await GET(
|
||||
createMockRequest('/api/reports/general-ledger', {
|
||||
searchParams: { period_id: 'period-1', from_date: '2026-6-1' },
|
||||
}),
|
||||
noParams
|
||||
)
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
expect(mockGenerate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when the range falls outside the fiscal period', async () => {
|
||||
enqueue({ data: PERIOD }) // fiscal_periods
|
||||
const res = await GET(
|
||||
createMockRequest('/api/reports/general-ledger', {
|
||||
searchParams: { period_id: 'period-1', from_date: '2025-06-01' },
|
||||
}),
|
||||
noParams
|
||||
)
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
expect(mockGenerate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('passes the validated date range through to the generator', async () => {
|
||||
enqueue({ data: PERIOD }) // fiscal_periods
|
||||
mockGenerate.mockResolvedValue({
|
||||
...EMPTY_REPORT,
|
||||
period: { start: '2026-06-01', end: '2026-06-30' },
|
||||
})
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/reports/general-ledger', {
|
||||
searchParams: {
|
||||
period_id: 'period-1',
|
||||
from_date: '2026-06-01',
|
||||
to_date: '2026-06-30',
|
||||
},
|
||||
}),
|
||||
noParams
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof EMPTY_REPORT }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.period).toEqual({ start: '2026-06-01', end: '2026-06-30' })
|
||||
expect(mockGenerate).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'period-1',
|
||||
undefined,
|
||||
undefined,
|
||||
expect.objectContaining({ fromDate: '2026-06-01', toDate: '2026-06-30' })
|
||||
)
|
||||
})
|
||||
|
||||
it('omits the range when no date params are sent (full period)', async () => {
|
||||
enqueue({ data: PERIOD }) // fiscal_periods
|
||||
mockGenerate.mockResolvedValue(EMPTY_REPORT)
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/reports/general-ledger', {
|
||||
searchParams: { period_id: 'period-1' },
|
||||
}),
|
||||
noParams
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockGenerate).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'period-1',
|
||||
undefined,
|
||||
undefined,
|
||||
expect.objectContaining({ fromDate: undefined, toDate: undefined })
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { generateGeneralLedger } from '@/lib/reports/general-ledger'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { parseDimensionFilterParams } from '@/lib/reports/dimension-filter'
|
||||
import { parseReportDateRange, type DateRange } from '@/lib/reports/date-range'
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'report.general_ledger',
|
||||
@@ -23,9 +24,28 @@ export const GET = withRouteContext(
|
||||
return NextResponse.json({ error: dimFilter.error }, { status: 400 })
|
||||
}
|
||||
|
||||
// Validate the optional date sub-range against the fiscal period bounds.
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId!)
|
||||
.single()
|
||||
|
||||
let range: DateRange = {}
|
||||
if (period) {
|
||||
const parsed = parseReportDateRange(searchParams, period)
|
||||
if (!parsed.ok) {
|
||||
return NextResponse.json({ error: parsed.error }, { status: 400 })
|
||||
}
|
||||
range = parsed.range
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await generateGeneralLedger(supabase, companyId!, periodId, accountFrom, accountTo, {
|
||||
dimensions: dimFilter.dimensions,
|
||||
fromDate: range.fromDate,
|
||||
toDate: range.toDate,
|
||||
})
|
||||
return NextResponse.json({ data })
|
||||
} catch (err) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { NextResponse } from 'next/server'
|
||||
import { generateGeneralLedger } from '@/lib/reports/general-ledger'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { parseDimensionFilterParams, dimensionFilterDisclosure, dimensionFilterFileSuffix } from '@/lib/reports/dimension-filter'
|
||||
import { parseReportDateRange, type DateRange } from '@/lib/reports/date-range'
|
||||
import {
|
||||
reportToWorkbook,
|
||||
textColumn,
|
||||
@@ -50,9 +51,28 @@ export const GET = withRouteContext('report.general_ledger.xlsx', async (request
|
||||
return NextResponse.json({ error: dimFilter.error }, { status: 400 })
|
||||
}
|
||||
|
||||
// Validate the optional date sub-range against the fiscal period bounds.
|
||||
const { data: period } = await supabase
|
||||
.from('fiscal_periods')
|
||||
.select('period_start, period_end')
|
||||
.eq('id', periodId)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
let range: DateRange = {}
|
||||
if (period) {
|
||||
const parsed = parseReportDateRange(searchParams, period)
|
||||
if (!parsed.ok) {
|
||||
return NextResponse.json({ error: parsed.error }, { status: 400 })
|
||||
}
|
||||
range = parsed.range
|
||||
}
|
||||
|
||||
try {
|
||||
const report = await generateGeneralLedger(supabase, companyId, periodId, accountFrom, accountTo, {
|
||||
dimensions: dimFilter.dimensions,
|
||||
fromDate: range.fromDate,
|
||||
toDate: range.toDate,
|
||||
})
|
||||
|
||||
// Flatten accounts + their lines into a single sheet. Each account contributes
|
||||
|
||||
@@ -57,14 +57,9 @@ import { eventBus } from '@/lib/events'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { INVOICE_FULL_COLUMNS, INVOICE_ITEM_FULL_COLUMNS } from '@/lib/api/v1/invoice-columns'
|
||||
import type { CompanySettings, Customer, EntityType, Invoice, InvoiceItem } from '@/types'
|
||||
|
||||
// default_dimensions must stay in this projection: the fetched row feeds
|
||||
// createInvoiceJournalEntry, which reads the bag off the row — dropping the
|
||||
// column here silently untags the revenue JE lines.
|
||||
const INVOICE_SEND_RESPONSE_COLUMNS =
|
||||
'id, invoice_number, customer_id, invoice_date, due_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, vat_rate, moms_ruta, your_reference, our_reference, notes, reverse_charge_text, credited_invoice_id, document_type, converted_from_id, paid_at, paid_amount, remaining_amount, default_dimensions, created_at, updated_at'
|
||||
|
||||
const InvoiceSendResponse = z.object({
|
||||
id: z.string().uuid(),
|
||||
invoice_number: z.string(),
|
||||
@@ -158,11 +153,16 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
})
|
||||
}
|
||||
|
||||
// Fetch invoice + customer + items.
|
||||
// Fetch invoice + customer + items. Uses the shared full projections so
|
||||
// the row feeding the PDF/email/journal entry cannot drift from what GET
|
||||
// returns: an earlier hand-rolled list here silently dropped
|
||||
// deduction_total, which made v1-sent ROT/RUT invoices overstate
|
||||
// "Att betala" (default_dimensions must also stay: createInvoiceJournalEntry
|
||||
// reads the bag off this row).
|
||||
const { data: invoice, error: fetchErr } = await ctx.supabase
|
||||
.from('invoices')
|
||||
.select(
|
||||
`${INVOICE_SEND_RESPONSE_COLUMNS}, customer:customers(id, name, customer_number, email, customer_type, country, address_line1, address_line2, postal_code, city, vat_number), items:invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, vat_rate, vat_amount, revenue_account, dimensions)`,
|
||||
`${INVOICE_FULL_COLUMNS}, customer:customers(id, name, customer_number, email, customer_type, country, address_line1, address_line2, postal_code, city, vat_number), items:invoice_items(${INVOICE_ITEM_FULL_COLUMNS})`,
|
||||
)
|
||||
.eq('company_id', ctx.companyId!)
|
||||
.eq('id', invoiceId)
|
||||
|
||||
Reference in New Issue
Block a user