Bug/resend and invoices (#1192)
* fix(invoices): anchor the PDF logo to the top-left of its header cell The logo box is always the full 240x80pt reserved area (any larger logo is clamped to exactly that), so objectFit: 'contain' placed the image inside it with the default 50% 50% centering. A wide banner logo fills the width and lands on the left margin, but a near-square logo scaled down to the 80pt height cap is only ~117pt wide and got pushed ~60pt in from the margin, which reads as a misaligned logo and forced companies to reshape their artwork. Anchor the image top-left so every aspect ratio starts at the margin. Covered by a test that renders the real PDF and reads the image placement matrix out of the content stream, for both a wide and a near-square logo. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(invoices): show the real delivery outcome in the send history "Skickad" only meant the email provider accepted the message, so a bounced invoice looked identical to one that arrived. Resend reports the outcome asynchronously; that report now lands on the delivery row and drives the history: green is reserved for a confirmed delivery, bounce/blocked reads red, delayed and spam-marked read amber, and an accepted-but-unconfirmed send is neutral instead of falsely green. The report arrives on a signed webhook and may only touch the three new provider status columns of an already sent, unredacted row: the WORM trigger proves nothing else changed, and a lower ranked or older report can never downgrade an observed failure. The provider reason text can quote the failing address, so it is masked on read and cleared by the daily PII redaction job. Timestamps also formatted in Europe/Stockholm instead of falling back to the runtime zone, which rendered a 14:05 send as 12:05 on Vercel. Delivery reports are per message, never per recipient: Resend sends one event for the whole message, so splitting a send per recipient would be the only way to get finer granularity, at the cost of CC. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(stripe): make the integration feed-only Stripe sync now only imports balance transactions into the transactions inbox, like any bank feed; nothing auto-books. The event/settlement sync (lib/sync.ts, lib/payouts.ts) stays in the repo but is no longer wired to any route or cron: the 15-min sync cron is removed from vercel.json. Payment links on invoice send are unchanged; their payments arrive as feed rows and are matched manually. - /sync runs only syncStripeBalanceTransactions; response is { success, transactions } - connecting via OAuth enables the nightly feed by default (toggle stays as opt-out) - panel: needs-review section and plumbing removed, copy rewritten to transactions-first (sv + en), toast reports fetched/imported/linked and calls out an empty result instead of silent all-zeros Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): return the article currency from the v1 article list The dashboard, importer, export and MCP article surfaces all learned to carry a non-SEK article price (#1166, #1183, #1184), but the v1 projection still omitted currency. An API or agent caller therefore read price_excl_vat with nothing marking it as EUR and would copy the number straight onto a SEK invoice line, at a nine-to-one error. Adds currency to the projection, the response shape and the example, plus a pitfall stating the price is not always SEK and that this endpoint does no FX conversion. Additive field only; no migration (articles.currency already exists). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat(settings): replace the settings modal with a routed panel sheet Settings now renders as a sheet that fills the main panel, sliding up over the page the user came from and back down on close, with the sidebar and frame left visible and usable. Behind it sits one shared master-detail surface: underline search across every section and subsection, the grouped section rail, and the active section as a direct-editing accordion. All 11 sections are decomposed into subsections, and the legacy *SettingsContent components compose the same pieces so the stacked and accordion layouts cannot drift. The sheet is the only presentation, on every entry path. The intercepting route handles in-app navigation and closes by popping the history entry, landing back on the page underneath. @settingsModal/default.tsx handles cold loads (refresh, deep link, new tab), where interception never fires; nothing is mounted underneath there, so it closes to the dashboard. Both branch on one shared predicate, isSheetSection, together with the settings layout, which must render nothing for those sections or the surface would stack twice behind the sheet and run every section's fetches twice. Closing is deliberate rather than incidental: the X, Esc, or navigating away. The dialog is non-modal so the sidebar's account popover and company switcher keep working with settings up, and an outside click no longer dismisses it. Sections land fully collapsed, and the scroll position of the page behind survives opening and closing the sheet. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * feat: enhance article management and settings UI - Add PATCH test for toggling article active state without other fields. - Remove unused MessageCircle icon from DashboardContent. - Refactor AccountingFrameworkForm to use SettingsFieldRow for better help text display. - Update CompanyInfoForm, DimensionsToggle, and various settings forms to replace description with help text. - Remove redundant headings and intros in several settings components to streamline UI. - Improve help text for various settings in English and Swedish translations. - Update structured error messages for better clarity on article deletion. * refactor(ArticleDetailPage): remove unused imports and duplicate state variable * fix(settings): own deep-linked settings routes by route list, not nav visibility Review fixes from the settings panel sheet work: * isSheetSection reads the full settings route list so a hidden-but-deep-linked section (assistant before BankID, banking in sandbox, api without MCP) is claimed by the sheet instead of rendering the legacy shell around an empty panel * keep 503 on the Resend delivery webhook when the signing secret is unset, with a test pinning the behaviour * stripe callback route test coverage Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * refactor: update salary, tax, and templates settings components - Refactored SalarySettingsContent to use a form wrapper and improved payment settings UI. - Enhanced TaxSettingsContent with new signals for EU sales, KU obligations, and ROT/RUT deductions. - Updated TemplatesSettingsContent to remove legacy comments and improve readability. - Simplified navigation items by removing unnecessary constants and directly using hrefs. - Cleaned up translation files by removing deprecated keys and adding new descriptions for clarity. --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
f07a34c51b
commit
d54b43f80f
@@ -63,6 +63,27 @@ describe('GET/PATCH/DELETE /api/articles/[id]', () => {
|
||||
expect(body.data.price_excl_vat).toBe(1500)
|
||||
})
|
||||
|
||||
// The article detail page's Inaktivera/Aktivera button sends nothing but the
|
||||
// flag, so an active-only body must be a valid sparse update on its own.
|
||||
it('PATCH toggles active on its own without any other field', async () => {
|
||||
enqueue({ data: { id: 'a1', name: 'Konsulttimme', active: false } })
|
||||
|
||||
const request = createMockRequest('/api/articles/a1', {
|
||||
method: 'PATCH',
|
||||
body: { active: false },
|
||||
})
|
||||
|
||||
const response = await PATCH(request, createMockRouteParams({ id: 'a1' }))
|
||||
const { status, body } = await parseJsonResponse<{ data: { active: boolean } }>(response)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.active).toBe(false)
|
||||
// Only the articles update: no revenue-account lookup is triggered by a
|
||||
// body that carries nothing but the flag.
|
||||
expect(supabase.from).toHaveBeenCalledTimes(1)
|
||||
expect(supabase.from).toHaveBeenCalledWith('articles')
|
||||
})
|
||||
|
||||
it('PATCH answers ACCOUNTS_NOT_IN_CHART for a BAS class-3 account missing from the chart', async () => {
|
||||
// chart_of_accounts lookup: no row, but 3999 is a known BAS class-3
|
||||
// account → activatable via the activate-and-retry dialog flow.
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
// Mock dependencies: factory must not reference outer variables
|
||||
const mockExchangeCodeForAccount = vi.fn()
|
||||
const mockFetchAccountDisplayName = vi.fn()
|
||||
vi.mock('@/extensions/general/stripe/lib/connect', () => ({
|
||||
exchangeCodeForAccount: (...args: unknown[]) => mockExchangeCodeForAccount(...args),
|
||||
fetchAccountDisplayName: (...args: unknown[]) => mockFetchAccountDisplayName(...args),
|
||||
}))
|
||||
|
||||
const { mockFrom } = vi.hoisted(() => ({ mockFrom: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createServiceClient: vi.fn().mockResolvedValue({ from: mockFrom }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'http://localhost:3000')
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
const CONNECTION_ID = 'connection-1'
|
||||
const OAUTH_STATE = 'state-token-1'
|
||||
|
||||
function makeRequest(params: Record<string, string>) {
|
||||
const url = new URL('http://localhost:3000/api/extensions/stripe/callback')
|
||||
for (const [k, v] of Object.entries(params)) {
|
||||
url.searchParams.set(k, v)
|
||||
}
|
||||
return new Request(url.toString())
|
||||
}
|
||||
|
||||
function mockChain(result: { data?: unknown; error?: unknown }) {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const m of ['select', 'eq', 'update', 'insert']) {
|
||||
chain[m] = vi.fn().mockReturnValue(chain)
|
||||
}
|
||||
chain.single = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
|
||||
// For chains ending without .single() (the insert and the error-path updates)
|
||||
chain.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
return chain
|
||||
}
|
||||
|
||||
describe('GET /api/extensions/stripe/callback', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockExchangeCodeForAccount.mockResolvedValue({
|
||||
stripeAccountId: 'acct_123',
|
||||
livemode: false,
|
||||
})
|
||||
mockFetchAccountDisplayName.mockResolvedValue('Test Shop')
|
||||
})
|
||||
|
||||
it('activates the connection and turns the transaction feed on by default', async () => {
|
||||
const findChain = mockChain({
|
||||
data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' },
|
||||
})
|
||||
const replayChain = mockChain({ error: null })
|
||||
const activateChain = mockChain({
|
||||
data: {
|
||||
id: CONNECTION_ID,
|
||||
company_id: 'company-1',
|
||||
user_id: 'user-1',
|
||||
stripe_account_id: 'acct_123',
|
||||
livemode: false,
|
||||
},
|
||||
})
|
||||
mockFrom
|
||||
.mockReturnValueOnce(findChain)
|
||||
.mockReturnValueOnce(replayChain)
|
||||
.mockReturnValueOnce(activateChain)
|
||||
|
||||
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
|
||||
|
||||
expect(response.status).toBe(307)
|
||||
expect(response.headers.get('location')).toBe(
|
||||
'http://localhost:3000/import?mode=stripe&stripe_connected=true',
|
||||
)
|
||||
|
||||
// Feed-only product: a completed OAuth must leave the nightly sync armed,
|
||||
// otherwise a connected account silently ingests nothing.
|
||||
const activatePayload = (activateChain.update as ReturnType<typeof vi.fn>).mock.calls[0][0]
|
||||
expect(activatePayload).toMatchObject({
|
||||
stripe_account_id: 'acct_123',
|
||||
livemode: false,
|
||||
display_name: 'Test Shop',
|
||||
status: 'active',
|
||||
oauth_state: null,
|
||||
transaction_sync_enabled: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('redirects with an error and never activates when the state is unknown', async () => {
|
||||
mockFrom.mockReturnValueOnce(mockChain({ data: null, error: { code: 'PGRST116' } }))
|
||||
|
||||
const response = await GET(makeRequest({ code: 'ac_123', state: 'unknown-state' }))
|
||||
|
||||
expect(response.headers.get('location')).toBe(
|
||||
'http://localhost:3000/import?mode=stripe&stripe_error=invalid_state',
|
||||
)
|
||||
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('redirects with an error when the authorization code was already used', async () => {
|
||||
mockFrom
|
||||
.mockReturnValueOnce(
|
||||
mockChain({ data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' } }),
|
||||
)
|
||||
.mockReturnValueOnce(mockChain({ error: { code: '23505' } }))
|
||||
|
||||
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
|
||||
|
||||
expect(response.headers.get('location')).toBe(
|
||||
'http://localhost:3000/import?mode=stripe&stripe_error=invalid_state',
|
||||
)
|
||||
expect(mockExchangeCodeForAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports the conflict when the Stripe account is already connected', async () => {
|
||||
mockFrom
|
||||
.mockReturnValueOnce(
|
||||
mockChain({ data: { id: CONNECTION_ID, user_id: 'user-1', company_id: 'company-1' } }),
|
||||
)
|
||||
.mockReturnValueOnce(mockChain({ error: null }))
|
||||
.mockReturnValueOnce(mockChain({ data: null, error: { code: '23505', message: 'dup' } }))
|
||||
.mockReturnValueOnce(mockChain({ error: null }))
|
||||
|
||||
const response = await GET(makeRequest({ code: 'ac_123', state: OAUTH_STATE }))
|
||||
|
||||
expect(response.headers.get('location')).toBe(
|
||||
'http://localhost:3000/import?mode=stripe&stripe_error=account_already_connected',
|
||||
)
|
||||
})
|
||||
|
||||
it('redirects without touching Stripe when parameters are missing', async () => {
|
||||
const response = await GET(makeRequest({ state: OAUTH_STATE }))
|
||||
|
||||
expect(response.headers.get('location')).toBe(
|
||||
'http://localhost:3000/import?mode=stripe&stripe_error=missing_parameters',
|
||||
)
|
||||
expect(mockFrom).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -118,6 +118,10 @@ export async function GET(request: Request) {
|
||||
connected_at: new Date().toISOString(),
|
||||
error_message: null,
|
||||
oauth_state: null, // Clear to prevent replay
|
||||
// Feed-only product: connecting Stripe means fetching its
|
||||
// transactions, so the nightly feed starts on by default. The panel
|
||||
// toggle remains as the opt-out.
|
||||
transaction_sync_enabled: true,
|
||||
})
|
||||
.eq('id', pendingConnection.id)
|
||||
.select('id, company_id, user_id, stripe_account_id, livemode')
|
||||
|
||||
@@ -79,6 +79,9 @@ describe('GET /api/invoices/[id]/deliveries', () => {
|
||||
body_text: 'Hej! Här kommer fakturan.',
|
||||
provider: 'resend',
|
||||
provider_message_id: 'provider-1',
|
||||
provider_status: 'delivered',
|
||||
provider_status_at: '2026-07-22T10:30:04.000Z',
|
||||
provider_status_detail: null,
|
||||
error_code: null,
|
||||
document_attachment_id: 'document-1',
|
||||
attachment_filename: 'faktura-f-1001.pdf',
|
||||
@@ -105,6 +108,9 @@ describe('GET /api/invoices/[id]/deliveries', () => {
|
||||
to_addresses: ['***@example.com'],
|
||||
cc_addresses: ['***@example.com'],
|
||||
provider: 'resend',
|
||||
provider_status: 'delivered',
|
||||
provider_status_at: '2026-07-22T10:30:04.000Z',
|
||||
provider_status_detail: null,
|
||||
error_code: null,
|
||||
document_attachment_id: 'document-1',
|
||||
attachment_filename: 'faktura-f-1001.pdf',
|
||||
@@ -127,4 +133,85 @@ describe('GET /api/invoices/[id]/deliveries', () => {
|
||||
p_invoice_id: INVOICE_ID,
|
||||
})
|
||||
})
|
||||
|
||||
it('masks recipient addresses quoted inside the provider reason text', async () => {
|
||||
enqueue({ data: { id: INVOICE_ID }, error: null })
|
||||
enqueue({
|
||||
data: [{
|
||||
id: 'delivery-2',
|
||||
channel: 'email',
|
||||
status: 'sent',
|
||||
to_addresses: ['customer@example.com'],
|
||||
cc_addresses: [],
|
||||
provider: 'resend',
|
||||
provider_status: 'bounced',
|
||||
provider_status_at: '2026-07-22T10:31:00.000Z',
|
||||
provider_status_detail:
|
||||
'550 5.1.1 <customer@example.com>: Recipient address rejected Permanent/General',
|
||||
error_code: null,
|
||||
document_attachment_id: 'document-1',
|
||||
attachment_filename: 'faktura-f-1001.pdf',
|
||||
sent_at: '2026-07-22T10:30:00.000Z',
|
||||
failed_at: null,
|
||||
created_at: '2026-07-22T10:29:59.000Z',
|
||||
}],
|
||||
error: null,
|
||||
})
|
||||
|
||||
const response = await GET(
|
||||
createMockRequest(`/api/invoices/${INVOICE_ID}/deliveries`),
|
||||
createMockRouteParams({ id: INVOICE_ID }),
|
||||
)
|
||||
const { body } = await parseJsonResponse<{ data: Array<Record<string, unknown>> }>(response)
|
||||
|
||||
expect(body.data[0].provider_status).toBe('bounced')
|
||||
expect(body.data[0].provider_status_detail).toBe(
|
||||
'550 5.1.1 <***@example.com>: Recipient address rejected Permanent/General',
|
||||
)
|
||||
})
|
||||
|
||||
// An ASCII allow-list stops at the first character it cannot spell and leaks
|
||||
// the head of the address ("anna.bergstr" out of anna.bergström@). Each of
|
||||
// these forms is a real local part a provider can quote back at us.
|
||||
it.each([
|
||||
['non-ASCII local part', 'anna.bergström@example.se avvisad', '***@example.se avvisad'],
|
||||
['quoted local part', '"anna berg"@example.com bounced', '***@example.com bounced'],
|
||||
['apostrophe in local part', "o'brien@example.se hard bounce", '***@example.se hard bounce'],
|
||||
[
|
||||
'several addresses in one reason',
|
||||
'delivered to anna@example.se but not bob@example.com',
|
||||
'delivered to ***@example.se but not ***@example.com',
|
||||
],
|
||||
])('masks the %s in the provider reason text', async (_label, detail, expected) => {
|
||||
enqueue({ data: { id: INVOICE_ID }, error: null })
|
||||
enqueue({
|
||||
data: [{
|
||||
id: 'delivery-3',
|
||||
channel: 'email',
|
||||
status: 'sent',
|
||||
to_addresses: ['customer@example.com'],
|
||||
cc_addresses: [],
|
||||
provider: 'resend',
|
||||
provider_status: 'bounced',
|
||||
provider_status_at: '2026-07-22T10:31:00.000Z',
|
||||
provider_status_detail: detail,
|
||||
error_code: null,
|
||||
document_attachment_id: null,
|
||||
attachment_filename: null,
|
||||
sent_at: '2026-07-22T10:30:00.000Z',
|
||||
failed_at: null,
|
||||
created_at: '2026-07-22T10:29:59.000Z',
|
||||
}],
|
||||
error: null,
|
||||
})
|
||||
|
||||
const response = await GET(
|
||||
createMockRequest(`/api/invoices/${INVOICE_ID}/deliveries`),
|
||||
createMockRouteParams({ id: INVOICE_ID }),
|
||||
)
|
||||
const { body } = await parseJsonResponse<{ data: Array<Record<string, unknown>> }>(response)
|
||||
|
||||
expect(body.data[0].provider_status_detail).toBe(expected)
|
||||
expect(body.data[0].provider_status_detail).not.toContain('anna')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,11 @@ import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import type { InvoiceDeliveryChannel, InvoiceDeliveryStatus } from '@/types'
|
||||
import type {
|
||||
InvoiceDeliveryChannel,
|
||||
InvoiceDeliveryProviderStatus,
|
||||
InvoiceDeliveryStatus,
|
||||
} from '@/types'
|
||||
|
||||
interface InvoiceDeliverySummaryRow {
|
||||
id: string
|
||||
@@ -11,6 +15,9 @@ interface InvoiceDeliverySummaryRow {
|
||||
to_addresses: string[]
|
||||
cc_addresses: string[]
|
||||
provider: string | null
|
||||
provider_status: InvoiceDeliveryProviderStatus | null
|
||||
provider_status_at: string | null
|
||||
provider_status_detail: string | null
|
||||
error_code: string | null
|
||||
document_attachment_id: string | null
|
||||
attachment_filename: string | null
|
||||
@@ -35,8 +42,12 @@ interface MaskedInvoiceDeliverySummaryRow
|
||||
* addresses stay server-side. The attachment filename passes through: it is
|
||||
* derived from data the invoice already exposes to every company member. The
|
||||
* database allow-list and masking boundary is defined by
|
||||
* list_invoice_delivery_summaries in migration 20260723150000; this route
|
||||
* list_invoice_delivery_summaries in migration 20260724160000; this route
|
||||
* masks returned addresses again as defense in depth.
|
||||
*
|
||||
* The provider delivery outcome is message-level, never per recipient: the
|
||||
* provider reports one result for the whole send, and its reason text can
|
||||
* quote the failing address, so that text is masked the same way.
|
||||
*/
|
||||
export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'invoice.deliveries.list',
|
||||
@@ -79,6 +90,9 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
to_addresses: delivery.to_addresses.map(maskRecipientDomain),
|
||||
cc_addresses: delivery.cc_addresses.map(maskRecipientDomain),
|
||||
provider: delivery.provider,
|
||||
provider_status: delivery.provider_status,
|
||||
provider_status_at: delivery.provider_status_at,
|
||||
provider_status_detail: maskAddressesInText(delivery.provider_status_detail),
|
||||
error_code: delivery.error_code,
|
||||
document_attachment_id: delivery.document_attachment_id,
|
||||
attachment_filename: delivery.attachment_filename,
|
||||
@@ -94,6 +108,27 @@ export const GET = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
},
|
||||
)
|
||||
|
||||
/**
|
||||
* Provider reason texts routinely quote the address that failed
|
||||
* ("550 5.1.1 <anna@example.se>: user unknown"). Keep the diagnostic value,
|
||||
* drop the local part, matching how the recipient list itself is masked.
|
||||
*
|
||||
* The local part is matched by exclusion, not by an allow-list of ASCII mail
|
||||
* characters: an allow-list stops at the first character it does not know, so
|
||||
* it leaks the head of every address it cannot spell. `anna.bergström@` would
|
||||
* mask only the `m`, and a quoted local part ("anna berg"@example.com) would
|
||||
* not match at all. Anything up to the delimiters that genuinely cannot sit
|
||||
* inside an address (whitespace, the angle brackets and punctuation providers
|
||||
* wrap addresses in) is treated as local part, so over-masking is the failure
|
||||
* mode rather than a partial disclosure.
|
||||
*/
|
||||
const ADDRESS_LOCAL_PART = /"[^"]*"@|[^\s<>()[\],;:"@]+@/gu
|
||||
|
||||
function maskAddressesInText(text: string | null): string | null {
|
||||
if (!text) return null
|
||||
return text.replace(ADDRESS_LOCAL_PART, '***@')
|
||||
}
|
||||
|
||||
function maskRecipientDomain(address: string): MaskedRecipientAddress {
|
||||
const separator = address.lastIndexOf('@')
|
||||
if (separator <= 0 || separator === address.length - 1) {
|
||||
|
||||
@@ -34,6 +34,7 @@ const SAMPLE_ARTICLE = {
|
||||
type: 'tjanst',
|
||||
unit: 'tim',
|
||||
price_excl_vat: 850,
|
||||
currency: 'SEK',
|
||||
vat_rate: 25,
|
||||
revenue_account: null,
|
||||
cost_price: null,
|
||||
@@ -111,6 +112,26 @@ describe('GET /api/v1/companies/:companyId/articles', () => {
|
||||
expect(client.eqCalls).toContainEqual(['articles', 'active', true])
|
||||
})
|
||||
|
||||
it('exposes the article currency so a caller can tell a non-SEK price apart', async () => {
|
||||
// price_excl_vat alone is ambiguous: without currency an agent copies a EUR
|
||||
// price onto a SEK invoice line with no FX conversion.
|
||||
const client = makeSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
articles: { data: [{ ...SAMPLE_ARTICLE, price_excl_vat: 95, currency: 'EUR' }], error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(client)
|
||||
|
||||
const res = await listArticles(
|
||||
makeRequest(`https://x.test/api/v1/companies/${COMPANY_ID}/articles`),
|
||||
routeParams,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.data.articles[0].currency).toBe('EUR')
|
||||
expect(body.data.articles[0].price_excl_vat).toBe(95)
|
||||
})
|
||||
|
||||
it('includes inactive articles with ?include_inactive=true', async () => {
|
||||
const client = makeSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
|
||||
@@ -23,6 +23,7 @@ const ArticleShape = z.object({
|
||||
type: z.enum(['vara', 'tjanst']),
|
||||
unit: z.string(),
|
||||
price_excl_vat: z.number(),
|
||||
currency: z.string(),
|
||||
vat_rate: z.number(),
|
||||
revenue_account: z.string().nullable(),
|
||||
cost_price: z.number().nullable(),
|
||||
@@ -36,7 +37,7 @@ const ArticleShape = z.object({
|
||||
|
||||
// Explicit projection: excludes user_id, company_id (internal scoping).
|
||||
const ARTICLE_COLUMNS =
|
||||
'id, article_number, name, name_en, type, unit, price_excl_vat, vat_rate, revenue_account, cost_price, ean, housework_type, notes, active, created_at, updated_at'
|
||||
'id, article_number, name, name_en, type, unit, price_excl_vat, currency, vat_rate, revenue_account, cost_price, ean, housework_type, notes, active, created_at, updated_at'
|
||||
|
||||
registerEndpoint({
|
||||
operation: 'articles.list',
|
||||
@@ -52,6 +53,7 @@ registerEndpoint({
|
||||
pitfalls: [
|
||||
'Linking article_id does NOT auto-fill the invoice line: send description, unit_price, vat_rate etc. explicitly on the item (copy them from this response).',
|
||||
'price_excl_vat always excludes VAT.',
|
||||
'price_excl_vat is denominated in the article\'s own currency, which is NOT always SEK. Check currency before copying the price onto an invoice line: the invoice carries a single currency for all its lines and there is no FX conversion here.',
|
||||
'housework_type is an arbetstypskod hint (e.g. BYGG, STAD); the invoice line still needs deduction_type + labor_hours + work_type set explicitly for ROT/RUT.',
|
||||
'Inactive articles (active=false) are hidden by default but remain linkable for historical reads.',
|
||||
],
|
||||
@@ -67,6 +69,7 @@ registerEndpoint({
|
||||
type: 'tjanst',
|
||||
unit: 'tim',
|
||||
price_excl_vat: 850,
|
||||
currency: 'SEK',
|
||||
vat_rate: 25,
|
||||
revenue_account: null,
|
||||
cost_price: null,
|
||||
|
||||
Reference in New Issue
Block a user