feat(invoices): offert (quote) document type with own OF-series, decisions, conversion, MCP and v1 (#2163)

* fix(invoices): reminders, AR ledger, AR reconciliation and deadlines only read fakturor

The overdue-reminder run, the kundreskontra, the 1510 reconciliation and the
deadlines page selected invoices by status alone. A sent proforma past its
due date was chased with a betalningspaminnelse and flipped to 'overdue',
and it appeared as a receivable. All four now filter document_type =
'invoice', which is also the precondition for adding quotes (offert): a
quote carries a date but never a receivable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56

* feat(invoices): offert (quote) document type with its own OF-series, decisions and conversion

Adds document_type 'quote' with valid_until, quote_status (open / accepted /
declined; expired is derived from valid_until, never stored) and
quote_decided_at. Quotes are numbered OF-nnn at insert from
company_settings.next_quote_number via generate_quote_number(), the same
pattern as delivery notes, so a declined quote never leaves a hole in the
F-series the way a proforma does. The column next_quote_number already
existed on prod and staging without a migration; the migration adopts it.

Engine: build-invoice-write writes the quote columns and keeps
remaining_amount at 0; the draft editor refuses accepted or declined
quotes; PATCH refuses changing a quote's or delivery note's document type
since the number belongs to the series; mark-paid refuses quotes.

New POST /api/invoices/[id]/quote-status records the decision and locks
once an invoice exists. Conversion is extracted into
lib/invoices/convert-to-invoice.ts (one implementation for the route and
the MCP staged commit, which had drifted): a converted quote stays and
flips to accepted, the invoice links back via converted_from_id and gets
its due date from the customer's payment terms; a declined or already
invoiced quote is refused. next-number previews the OF-series for quotes.

Migration applied to the staging branch and registered as 20260902140000;
the pg test runs in CI (pg-real).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56

* feat(invoices): quote PDF, email and filename surfaces

The customer-facing surfaces get a quote sibling for every proforma branch:
PDF title OFFERT / QUOTE with Offertdatum and Giltig till instead of the
due date, a notice that the document is not an invoice or a payment
request, and no payment box, OCR, bankgiro, Swish, QR or payment link.
The email says the quote is attached and valid until the expiry, drops
the payment details and pay-online button, and asks about the quote
rather than the invoice. Filenames read "Offert nr OF-001". Seller VAT
number and payment accounts are skipped for quotes as for proformas:
a quote is not a faktura under ML 17 kap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56

* feat(invoices): offert in the editor, list and detail pages

Editor: "Offert" document type with a required "Giltig till" field
(default today + 30 days) in place of the due date; the wire body mirrors
it into due_date so the shared schema is satisfied. Payment link, ROT/RUT,
periodisering and the bank box are already gated on real invoices. The
type cannot be switched on an existing quote (its OF-number belongs to
the series).

List: an Offerter tab beside Proforma, "Ny offert" in the split button,
and a status column that shows the decision or the derived expiry:
Utgången and Avböjd are exception chips, Öppen and Accepterad muted text.

Detail: Acceptera and Skapa faktura in the header, Avböj in the overflow
menu; an expired quote asks before accepting or invoicing (bypassable);
once an invoice exists the page links to it as Fakturerad and hides the
decision actions. Strings in both sv and en.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56

* feat(mcp,v1): expose offert on the MCP tools and the v1 REST surface

MCP: create_invoice takes document_type quote with a required valid_until
and allocates the OF-number at insert; the convert tool keeps its id and
accepts quotes with the registry refusal codes; new set_quote_status;
list_invoices and get_invoice expose valid_until and the effective quote
status, including a derived expired filter. The tools/list payload stays
under its ceiling without a ledger change. The MCP staged convert now
uses the shared converter.

v1: POST /invoices/{id}/quote-status (registered in the endpoint registry,
scope map and route loader), valid_until and quote_status in the list,
create and detail shapes, and a quote_status list filter. Skill atoms
mention offert. Decision log lines for the own number series, derived
expiry, accepted-not-cancelled conversion and the header action layout.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56

* test(invoices): pass route params and period id in the new quote tests

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56

* refactor(invoices): literal update payloads in the converter so the phantom-column guard can read them

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W45yD8NfQ97JhyYaXpzN56

* fix(invoices): close the quote review findings in one pass

Skeptics (correctness, compliance, regression) and CodeRabbit on #2163:

- quote_status is no longer a write-builder output, so a v1 PATCH or MCP
  update_invoice can never reset a recorded accept/decline; new quotes are
  opened by the invoices_quote_defaults trigger (20260902141000), which
  also keeps due_date and valid_until equal. v1 PATCH and the MCP update
  executor now use the shared editable-draft predicate.
- One live invoice per converted source, enforced by a partial unique
  index; the converter maps 23505 to INVOICE_QUOTE_ALREADY_INVOICED and
  both quote-status routes compare-and-set on the decision they read.
- MCP-created quotes carry remaining_amount 0; mark-paid, transaction
  match and voucher link refuse non-invoices on the MCP staging tools,
  the executors and the dashboard link route.
- Conversion of a foreign-currency source refetches the rate for the
  conversion day (ML 8 kap 21-23 paragraphs) and fails closed without one;
  0-day payment terms mean due on receipt.
- bulk-create refuses quotes per item; list_invoices rejects a
  quote_status filter combined with another document_type; an omitted
  document_type on PATCH means unchanged.
- attention, push notifications, open-AR count, FX revaluation, year-end
  and accrual auto-detect and bank-match suggestions only read fakturor.
- Quote PDF and email print Summa / Total instead of Att betala.
- Regenerated skills/accounted-api for the new v1 endpoint.

Declined with reasons in DECISIONS.md: NOT VALID + VALIDATE and CONCURRENTLY
on the migrations (repo precedent, 13.8k rows, transactional apply);
re-validating VAT treatment at conversion (the converted invoice is a
draft the user reviews; follow-up).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs

* fix(invoices): second review round: migration versions, order links, batch allocation, races

- Migrations renamed to 20260902220000 / 20260902221000: #2166 shipped its
  own 20260902141000 to prod while this PR was in review and prod's head
  moved past both files; below-head versions are skipped by branching,
  which would have left the quote trigger off prod. Staging rows renamed.
- Quote lines never carry sales_order_item_id (an offer must not count as
  invoiced kundorder quantity); the converter carries a proforma line's
  order link onto the invoice.
- Converter compare-and-sets the source (proforma cancel, quote accept):
  a concurrent cancel, proforma-to-order conversion or decision removes
  the orphan invoice with INVOICE_CONVERT_SOURCE_CHANGED instead of a
  second document for the same sale.
- MCP set_quote_status gets the same compare-and-set as the HTTP routes;
  0-row updates report INVOICE_QUOTE_CHANGED_CONCURRENTLY everywhere.
  quote-status (dashboard, v1, MCP) accepts valid_until so an expired
  sent quote can be reopened, as the docs promised.
- MCP mark-paid refuses only quotes, parity with the dashboard route
  (a sent proforma marked paid is a supported prepayment record).
- Batch allocation (dashboard route and MCP tool) refuses non-invoices
  before the RPC, which gates on status alone.
- Customer AR drill-down, v1 customer open invoices and archive guard,
  and the calendar feed read fakturor only.
- Draft quote PDF says "UTKAST" instead of "not a valid invoice"; the
  editor locks the document type on existing quotes and delivery notes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs

* chore(invoices): use roundOre in the quote MCP summaries and FX test after main tightened the guard baseline

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs

* fix(invoices): third review round: atomic decision lock, viewer gate, lookup errors, quote payment terms

- 20260902222000: BEFORE UPDATE trigger locks an accepted quote while a
  live converted invoice exists (the compare-and-set in the three decision
  writers could still be beaten by a conversion landing in between); the
  routes and the MCP tool map the raise to 409 INVOICE_QUOTE_ALREADY_INVOICED.
  generate_quote_number now also requires a non-viewer membership so a
  viewer's session token cannot burn OF-numbers through PostgREST.
- Converter checks quote eligibility before the Riksbanken call and treats
  a failed company_settings read as a failure instead of a 30-day default.
- Re-sending the same decision keeps quote_decided_at (idempotent).
- gnubok_find_voucher_candidates_for_invoice refuses non-invoices like its
  write sibling; the dashboard link route surfaces a failed lookup.
- Late-fee and credit-term texts never print on a quote.
Applied and registered on staging; pg tests added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs

* fix(invoices): review nits: fail-closed batch lookup, dry-run expiry, quote heading, quote-date CHECK

- match-batch surfaces a failed document lookup instead of allocating.
- v1 quote-status dry-run preview carries the new valid_until.
- Quote PDF heading reads Offertinformation / Quote information.
- 20260902222000 also pins the date invariants the trigger maintains as a
  CHECK: a quote always has valid_until = due_date, nothing else has one.
  Applied on staging.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0111fYAUxKtpxU1BHiBioqzs

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-09-02 22:40:25 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 3f9a21c64d
commit 1c82baf553
102 changed files with 5044 additions and 418 deletions
+121 -36
View File
@@ -114,6 +114,9 @@ export type InvoiceEditorProps = (
/** Open with the självfaktura tab preselected (the "Självfaktura" entry in
* the invoice list's split button). Create mode only. */
initialSelfBilled?: boolean
/** Open with this document type preselected (the "Ny offert" entry in the
* invoice list's split button). Create mode only. */
initialDocumentType?: InvoiceDocumentType
}
// Subset of Article fields the line picker needs to pre-fill a row.
@@ -188,6 +191,10 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
// 2026-08-17). Self-billing is never available when editing a draft.
const mode: 'invoice' | 'self_billed' =
props.initialSelfBilled && !isEditMode ? 'self_billed' : 'invoice'
const createDocumentType: InvoiceDocumentType =
!isEditMode && !isCopyMode && !props.initialSelfBilled && props.initialDocumentType
? props.initialDocumentType
: 'invoice'
// Company-wide opt-in from the invoice settings page: the whole payment
// link section (manual field + Stripe auto toggle) stays hidden until the
// company enables it. The send routes enforce the same setting server-side
@@ -350,9 +357,13 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
customer_id: z.string().min(1, t('validation_customer_required')),
invoice_date: z.string().min(1, t('validation_invoice_date_required')),
due_date: z.string().min(1, t('validation_due_date_required')),
// Quotes only: the expiry date ("Giltig till"). due_date mirrors it on
// the wire (the column is NOT NULL); required for quotes via the
// superRefine below so the error lands under the visible field.
valid_until: z.string().optional(),
delivery_date: z.string().optional(),
currency: z.enum(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']),
document_type: z.enum(['invoice', 'proforma', 'delivery_note']),
document_type: z.enum(['invoice', 'proforma', 'delivery_note', 'quote']),
your_reference: z.string().optional(),
our_reference: z.string().optional(),
invoice_marking: z.string().optional(),
@@ -389,6 +400,14 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
deduction_personnummer: z.string().optional(),
deduction_housing_designation: z.string().optional(),
items: z.array(itemSchema).min(1, t('validation_min_one_row')),
}).superRefine((data, ctx) => {
if (data.document_type === 'quote' && !data.valid_until) {
ctx.addIssue({
code: 'custom',
path: ['valid_until'],
message: t('validation_valid_until_required'),
})
}
})
}, [t, ta])
@@ -540,6 +559,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
customer_id: initial.customer_id,
invoice_date: initial.invoice_date,
due_date: initial.due_date,
valid_until:
initial.document_type === 'quote' ? initial.valid_until ?? initial.due_date : '',
delivery_date: initial.delivery_date ?? '',
currency: initial.currency,
document_type: (initial.document_type ?? 'invoice') as InvoiceDocumentType,
@@ -582,6 +603,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
customer_id: copyInitial.customer_id,
invoice_date: '',
due_date: '',
valid_until: '',
delivery_date: '',
currency: copyInitial.currency,
document_type: 'invoice' as InvoiceDocumentType,
@@ -602,8 +624,9 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
customer_id: '',
invoice_date: '',
due_date: '',
valid_until: '',
currency: 'SEK',
document_type: 'invoice' as InvoiceDocumentType,
document_type: createDocumentType,
payment_link_url: '',
payment_link_auto: true,
external_invoice_number: '',
@@ -625,6 +648,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
setValue('invoice_date', format(new Date(), 'yyyy-MM-dd'))
setValue('received_date', format(new Date(), 'yyyy-MM-dd'))
setValue('due_date', format(addDays(new Date(), 30), 'yyyy-MM-dd'))
setValue('valid_until', format(addDays(new Date(), 30), 'yyyy-MM-dd'))
}, [])
const { fields, append, remove, move } = useFieldArray({
@@ -652,6 +676,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
// stay live while the settings panel is collapsed.
const watchInvoiceDate = watch('invoice_date')
const watchDueDate = watch('due_date')
const watchValidUntil = watch('valid_until')
const watchReceivedDate = watch('received_date')
const watchDeliveryDate = watch('delivery_date')
const watchYourReference = watch('your_reference')
@@ -1176,6 +1201,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
const isSelfBilled = mode === 'self_billed'
// ROT/RUT is an own-issued, B2C concept: never shown for a received self-bill.
const isInvoiceDoc = watchDocumentType === 'invoice' && !isSelfBilled
// Offert: no due date (an expiry instead), no payment box, never books.
const isQuoteDoc = watchDocumentType === 'quote' && !isSelfBilled
rotRutCompletenessAppliesRef.current = isInvoiceDoc
// ROT/RUT yearly-ceiling context: what this customer has already been
@@ -1423,6 +1450,15 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
}
}
// A quote's "Giltig till" is its own field; the shared schema still wants a
// due_date, so the wire body mirrors valid_until into it. Other document
// types never send valid_until (undefined disappears in JSON).
function withQuoteValidity(data: FormData): FormData {
if (data.document_type !== 'quote') return { ...data, valid_until: undefined }
const validUntil = data.valid_until || data.due_date
return { ...data, due_date: validUntil, valid_until: validUntil }
}
async function onSubmit(data: FormData) {
if (isEditMode) {
// Editing a draft: no review dialog, straight to PATCH.
@@ -1494,6 +1530,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
function getDocLabel(type: InvoiceDocumentType): string {
if (type === 'proforma') return t('doc_label_proforma')
if (type === 'delivery_note') return t('doc_label_delivery_note')
if (type === 'quote') return t('doc_label_quote')
return t('doc_label_invoice')
}
@@ -1516,7 +1553,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
// Shared body builder (lib/invoices/editor-payload.ts): dimension pruning,
// ROT/RUT privacy strip, self-billing-carrier removal and the always-sent
// ore_rounding / default_dimensions all live there, pinned by parity tests.
const sanitizedPayload = buildInvoiceWritePayload(pendingData, {
const sanitizedPayload = buildInvoiceWritePayload(withQuoteValidity(pendingData), {
oreRounding,
defaultDims,
})
@@ -1572,7 +1609,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
// failures keep their toasts: this replaces the client-side validation
// toast only.
function focusSettingsField(
name: 'invoice_date' | 'due_date' | 'received_date' | 'payment_link_url',
name: 'invoice_date' | 'due_date' | 'valid_until' | 'received_date' | 'payment_link_url',
) {
// In self-billed mode fakturadatum and mottagningsdatum render uncollapsed
// next to the external number: focus directly, no panel to expand.
@@ -1598,10 +1635,13 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
customerTriggerRef.current?.focus()
break
case 'invoice_date':
case 'due_date':
case 'received_date':
focusSettingsField(step.kind)
break
case 'due_date':
// A quote's date row is "Giltig till": the step reuses the due kind.
focusSettingsField(isQuoteDoc ? 'valid_until' : 'due_date')
break
case 'rows_empty':
entryInputRef.current?.focus()
break
@@ -1656,6 +1696,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
}
if (errs.customer_id) customerTriggerRef.current?.focus()
else if (errs.invoice_date) focusSettingsField('invoice_date')
else if (errs.valid_until) focusSettingsField('valid_until')
else if (errs.due_date) focusSettingsField('due_date')
}
@@ -1666,7 +1707,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
async function saveDraftData(data: FormData) {
setIsSavingDraft(true)
const payload = buildInvoiceWritePayload(data, {
const payload = buildInvoiceWritePayload(withQuoteValidity(data), {
saveAsDraft: true,
oreRounding,
defaultDims,
@@ -1709,7 +1750,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
if (!initial) return
setIsSubmitting(true)
const payload = buildInvoiceWritePayload(data, {
const payload = buildInvoiceWritePayload(withQuoteValidity(data), {
oreRounding,
defaultDims,
})
@@ -1791,7 +1832,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
body: JSON.stringify({
customer_id: data.customer_id,
invoice_date: data.invoice_date,
due_date: data.due_date,
due_date: withQuoteValidity(data).due_date,
valid_until: withQuoteValidity(data).valid_until,
currency: data.currency,
document_type: data.document_type,
items: data.items,
@@ -1856,7 +1898,9 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
? t('title_proforma')
: watchDocumentType === 'delivery_note'
? t('title_delivery_note')
: t('title_invoice')
: watchDocumentType === 'quote'
? t('title_quote')
: t('title_invoice')
// In bare (dialog) mode the dialog owns the accessible title (sr-only
// DialogTitle) and the page already has its own h1, so the visible heading
// steps down to h2: it still tracks document type and number preview live.
@@ -1879,7 +1923,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
isSelfBilled,
customerSelected: Boolean(watchCustomerId),
invoiceDate: watchInvoiceDate || '',
dueDate: watchDueDate || '',
dueDate: (isQuoteDoc ? watchValidUntil : watchDueDate) || '',
receivedDate: watchReceivedDate || '',
externalInvoiceNumber: watchExternalNumber || '',
items: watchItems ?? [],
@@ -1898,7 +1942,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
const nextStepLabels: Record<Exclude<NextStep['kind'], 'ready' | 'row_incomplete'>, string> = {
customer: t('next_step_customer'),
invoice_date: t('next_step_invoice_date'),
due_date: t('next_step_due_date'),
due_date: isQuoteDoc ? t('next_step_valid_until') : t('next_step_due_date'),
rows_empty: t('next_step_add_row'),
payment_link: t('next_step_payment_link'),
personnummer: t('next_step_personnummer'),
@@ -1923,6 +1967,7 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
currency: watchCurrency,
invoiceDate: watchInvoiceDate || '',
dueDate: watchDueDate || '',
validUntil: watchValidUntil || '',
receivedDate: watchReceivedDate || '',
deliveryDate: watchDeliveryDate || '',
yourReference: watchYourReference || '',
@@ -1934,7 +1979,11 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
const chipTexts = forvalChips.map((chip) => {
switch (chip.kind) {
case 'doc_type':
return chip.documentType === 'proforma' ? t('doctype_proforma') : t('doctype_delivery_note')
return chip.documentType === 'proforma'
? t('doctype_proforma')
: chip.documentType === 'quote'
? t('doctype_quote')
: t('doctype_delivery_note')
case 'currency':
return t('chip_currency', { currency: chip.currency })
case 'invoice_date':
@@ -1943,6 +1992,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
return t('chip_due_days', { days: chip.days, date: chip.date })
case 'due_date':
return t('chip_due_date', { date: chip.date })
case 'valid_until':
return t('chip_valid_until', { date: chip.date })
case 'received':
return t('chip_received', { date: chip.date })
case 'delivery':
@@ -2924,13 +2975,21 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
name="document_type"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange}>
<Select
value={field.value}
onValueChange={field.onChange}
// Quotes and delivery notes are numbered from their
// own series at insert, so an existing one cannot
// change type (the API refuses it too).
disabled={isEditMode && (field.value === 'quote' || field.value === 'delivery_note')}
>
<SelectTrigger className="h-8 w-44 text-[13px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="invoice">{t('doctype_invoice')}</SelectItem>
<SelectItem value="proforma">{t('doctype_proforma')}</SelectItem>
<SelectItem value="quote">{t('doctype_quote')}</SelectItem>
<SelectItem value="delivery_note">{t('doctype_delivery_note')}</SelectItem>
</SelectContent>
</Select>
@@ -2984,22 +3043,41 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
</div>
)}
<div className={SETTINGS_ROW_CLASS}>
<Label className="text-[13px] font-normal">
{t('due_date_label')}<RequiredMark />
</Label>
<div>
<Input
type="date"
{...register('due_date')}
aria-required="true"
className="h-8 w-40 text-[13px] tabular-nums"
/>
{errors.due_date && (
<p className="mt-1 text-xs text-destructive">{errors.due_date.message}</p>
)}
{isQuoteDoc ? (
<div className={SETTINGS_ROW_CLASS}>
<Label className="text-[13px] font-normal">
{t('valid_until_label')}<RequiredMark />
</Label>
<div>
<Input
type="date"
{...register('valid_until')}
aria-required="true"
className="h-8 w-40 text-[13px] tabular-nums"
/>
{errors.valid_until && (
<p className="mt-1 text-xs text-destructive">{errors.valid_until.message}</p>
)}
</div>
</div>
</div>
) : (
<div className={SETTINGS_ROW_CLASS}>
<Label className="text-[13px] font-normal">
{t('due_date_label')}<RequiredMark />
</Label>
<div>
<Input
type="date"
{...register('due_date')}
aria-required="true"
className="h-8 w-40 text-[13px] tabular-nums"
/>
{errors.due_date && (
<p className="mt-1 text-xs text-destructive">{errors.due_date.message}</p>
)}
</div>
</div>
)}
{watchDocumentType === 'invoice' && !isSelfBilled && (
<div className={SETTINGS_ROW_CLASS}>
@@ -3307,21 +3385,27 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
isSubmitting={isSubmitting}
title={watchDocumentType === 'proforma'
? t('review_dialog_title_proforma')
: watchDocumentType === 'delivery_note'
? t('review_dialog_title_delivery_note')
: t('review_dialog_title_invoice')}
: watchDocumentType === 'quote'
? t('review_dialog_title_quote')
: watchDocumentType === 'delivery_note'
? t('review_dialog_title_delivery_note')
: t('review_dialog_title_invoice')}
warningText={watchDocumentType === 'invoice'
? accountingMethod === 'cash'
? t('review_warning_invoice_cash')
: t('review_warning_invoice_accrual')
: watchDocumentType === 'proforma'
? t('review_warning_proforma')
: t('review_warning_delivery_note')}
: watchDocumentType === 'quote'
? t('review_warning_quote')
: t('review_warning_delivery_note')}
confirmLabel={watchDocumentType === 'proforma'
? t('confirm_create_proforma')
: watchDocumentType === 'delivery_note'
? t('confirm_create_delivery_note')
: t('confirm_create_invoice')}
: watchDocumentType === 'quote'
? t('confirm_create_quote')
: watchDocumentType === 'delivery_note'
? t('confirm_create_delivery_note')
: t('confirm_create_invoice')}
extraActions={
<Button
variant="outline"
@@ -3340,7 +3424,8 @@ export default function InvoiceEditor(props: InvoiceEditorProps = { mode: 'creat
<InvoiceReviewContent
customer={selectedCustomer}
invoiceDate={pendingData?.invoice_date || ''}
dueDate={pendingData?.due_date || ''}
dueDate={(isQuoteDoc ? pendingData?.valid_until : pendingData?.due_date) || ''}
dueDateLabelKey={isQuoteDoc ? 'valid_until' : 'due_date'}
currency={(pendingData?.currency || 'SEK') as Currency}
items={(pendingData?.items || []).map((item) => ({
...item,
+4 -1
View File
@@ -54,6 +54,8 @@ interface InvoiceReviewContentProps {
/** Payment-link förval on this invoice: Stripe auto-link on send, a manually
* pasted link, or none. Renders in the Förval summary line when set. */
paymentLink?: 'auto' | 'manual' | null
/** Quotes show their expiry ("Giltig till") where an invoice shows its due date. */
dueDateLabelKey?: 'due_date' | 'valid_until'
}
export function InvoiceReviewContent({
@@ -68,6 +70,7 @@ export function InvoiceReviewContent({
yourReference,
ourReference,
invoiceMarking,
dueDateLabelKey = 'due_date',
notes,
numberPreview,
oreRounding,
@@ -122,7 +125,7 @@ export function InvoiceReviewContent({
<p className="font-medium">{invoiceDate ? formatDate(invoiceDate) : ''}</p>
</div>
<div>
<span className="text-muted-foreground">{t('due_date')}</span>
<span className="text-muted-foreground">{t(dueDateLabelKey)}</span>
<p className="font-medium">{dueDate ? formatDate(dueDate) : ''}</p>
</div>
</div>
+24 -6
View File
@@ -22,6 +22,7 @@ import {
// "Ny faktura" opens instead of the dialog chunk followed by a second,
// dependent editor chunk (and then the editor's own data fetches).
import InvoiceEditor from '@/components/invoices/InvoiceEditor'
import type { InvoiceDocumentType } from '@/types'
interface Props {
open: boolean
@@ -29,6 +30,8 @@ interface Props {
copyFromId?: string | null
/** Preselect the självfaktura tab (split-button entry on /invoices). */
selfBilled?: boolean
/** Preselect a document type, e.g. 'quote' ("Ny offert" split-button entry). */
documentType?: InvoiceDocumentType
}
/**
@@ -38,11 +41,17 @@ interface Props {
* (unmounting the host list page and this dialog with it).
*
* The accessible title is visually hidden: the bare editor renders its own
* live heading, which tracks document type (faktura/proforma/följesedel) and
* shows the invoice-number preview: a static DialogTitle would duplicate or
* contradict it.
* live heading, which tracks document type (faktura/proforma/offert/följesedel)
* and shows the invoice-number preview: a static DialogTitle would duplicate
* or contradict it.
*/
export default function NewInvoiceDialog({ open, onOpenChange, copyFromId = null, selfBilled = false }: Props) {
export default function NewInvoiceDialog({
open,
onOpenChange,
copyFromId = null,
selfBilled = false,
documentType,
}: Props) {
const t = useTranslations('invoice_editor')
const { company } = useCompany()
const supabase = useMemo(() => createClient(), [])
@@ -133,7 +142,11 @@ export default function NewInvoiceDialog({ open, onOpenChange, copyFromId = null
onInteractOutside={(e) => e.preventDefault()}
>
<DialogTitle className="sr-only">
{copyFromId ? t('title_copy') : t('title_invoice')}
{copyFromId
? t('title_copy')
: documentType === 'quote' && !selfBilled
? t('title_quote')
: t('title_invoice')}
</DialogTitle>
{copyFromId ? (
copyLoadFailed ? (
@@ -154,7 +167,12 @@ export default function NewInvoiceDialog({ open, onOpenChange, copyFromId = null
</div>
)
) : (
<InvoiceEditor mode="create" bare initialSelfBilled={selfBilled} />
<InvoiceEditor
mode="create"
bare
initialSelfBilled={selfBilled}
initialDocumentType={documentType}
/>
)}
</DialogContent>
</Dialog>
@@ -205,6 +205,22 @@ describe('deriveForvalChips', () => {
})
})
it('replaces the due chips with a valid-until chip for a quote', () => {
const chips = deriveForvalChips(
chipsInput({ documentType: 'quote', validUntil: '2026-09-16' }),
)
expect(chips[0]).toEqual({ kind: 'doc_type', documentType: 'quote' })
expect(chips).toContainEqual({ kind: 'valid_until', date: '2026-09-16' })
expect(chips.find((c) => c.kind === 'due_days')).toBeUndefined()
expect(chips.find((c) => c.kind === 'due_date')).toBeUndefined()
})
it('skips the valid-until chip while a quote has no expiry yet', () => {
const chips = deriveForvalChips(chipsInput({ documentType: 'quote', validUntil: '' }))
expect(chips.find((c) => c.kind === 'valid_until')).toBeUndefined()
expect(chips.find((c) => c.kind === 'due_days')).toBeUndefined()
})
it('falls back to a plain due date when the invoice date is missing or after', () => {
expect(deriveForvalChips(chipsInput({ invoiceDate: '' }))).toContainEqual({
kind: 'due_date',
+10 -3
View File
@@ -113,11 +113,12 @@ export function deriveNextStep(input: NextStepInput): NextStep {
}
export type ForvalChip =
| { kind: 'doc_type'; documentType: 'proforma' | 'delivery_note' }
| { kind: 'doc_type'; documentType: 'proforma' | 'delivery_note' | 'quote' }
| { kind: 'currency'; currency: string }
| { kind: 'invoice_date'; date: string }
| { kind: 'due_days'; days: number; date: string }
| { kind: 'due_date'; date: string }
| { kind: 'valid_until'; date: string }
| { kind: 'received'; date: string }
| { kind: 'delivery'; date: string }
| { kind: 'your_reference'; reference: string }
@@ -128,10 +129,12 @@ export type ForvalChip =
export interface ForvalChipsInput {
isSelfBilled: boolean
documentType: 'invoice' | 'proforma' | 'delivery_note'
documentType: 'invoice' | 'proforma' | 'delivery_note' | 'quote'
currency: string
invoiceDate: string
dueDate: string
/** Quotes only: the expiry date ("Giltig till"). Replaces the due chips. */
validUntil?: string
receivedDate: string
deliveryDate: string
yourReference: string
@@ -162,7 +165,11 @@ export function deriveForvalChips(input: ForvalChipsInput): ForvalChip[] {
if (input.invoiceDate) {
chips.push({ kind: 'invoice_date', date: input.invoiceDate })
}
if (input.dueDate) {
if (input.documentType === 'quote' && !input.isSelfBilled) {
// A quote has no due date, only an expiry: the due chips would describe
// a payment term the document does not carry.
if (input.validUntil) chips.push({ kind: 'valid_until', date: input.validUntil })
} else if (input.dueDate) {
const days = dueDays(input.invoiceDate, input.dueDate)
if (days !== null && days >= 0) chips.push({ kind: 'due_days', days, date: input.dueDate })
else chips.push({ kind: 'due_date', date: input.dueDate })