* feat(company): ideell förening as a third legal form, behind a flag (#2072 step 1) Why the problem occurred: the legal form was modelled as a binary flag in ~300 files. `EntityType` was a two-member union, but nothing dispatched on it exhaustively: 28 sites defaulted `?? 'enskild_firma'` (invoice, categorize, match, stripe, invoice-inbox) or `?? 'aktiebolag'` (year-end, bokslut, MCP), and every form-dependent choice was an `=== 'aktiebolag' ? A : B` ternary. Widening the union compiled everywhere and changed nothing, so a förening would have booked as an enskild firma in the app and as an aktiebolag in bokslut and MCP, with no error anywhere. The lookup refused föreningar at the door (mapEntityType returned null), which is what the tester hit. What was removed or simplified: the silent defaults. One module, lib/company/entity-type.ts, now holds the list (ENTITY_TYPES), the parser (never defaults), the resolver (settings hint, then companies.entity_type, then throw) and `byEntityType`, whose Record arms make the compiler refuse the next widening until each site has an answer. The form-dependent facts (closing account, owner settlement account, calendar-year lock, default method, K1/K2 label, personnummer vs 16-prefix) live there once instead of in the ternaries. On the SQL side supported_entity_types() replaces four copies of the literal list in the create RPCs. Why this shape and not the proposed one: the tracker asked for the enum widening plus a chart; that alone was the dangerous version (compiles, books wrong). Bundling stiftelse was considered and dropped: identical plumbing but no chart block. Creation sits behind NEXT_PUBLIC_IDEELL_FORENING_ENABLED so the CHECK, RPCs and seed can ship now and the first partner is switched on without a migration; the flag goes when Phase 2 (packs, INK3, årsbokslut, Swish) lands on the tracker. Domain choices (DECISIONS.md 2026-09-08, verify with an accountant before Phase 2): result closes to 2069 with 2068 as prior-year carry; no owner accounts, member settlement on 2890; accrual default; brutet räkenskapsår allowed; K1 label for the 5 000 kr accrual threshold (BFNAR 2010:1); org number gets the 16 prefix. Migration 20260908110835 widens the three CHECK constraints, adds supported_entity_types(), re-creates the three create RPCs with the widened guard and adds the förening block to seed_chart_of_accounts. Applied to staging and covered by ideell-forening-entity-type.pg.test.ts. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * fix(company): close the förening paths the skeptic refuted (#2072) Five refutations from the /skeptic pass on 7a05c54d2, each fixed at the shared definition rather than the reported site: 1. Privately paid supplier invoices and the utlägg dialog resolved the owner account in lib/expenses/payer.ts with its own AB/EF ternary, so a förening member's invoice was built on 2893 and then refused by the expense-claim service (which already said 2890), burning an ankomstnummer. The helper now uses ownerSettlementAccount. 2. Booking templates substitute their `_ab` accounts only for an aktiebolag; the `private_expense` template kept its base 2013 for a förening. Template accounts now resolve through templateAccountForForm: EF base, AB override, förening base with owner accounts translated to 2890 (booking-templates.ts and proposal-lines.ts share it). 3. A VAT-registered förening with helårsmoms got no momsdeklaration deadline: the annual VAT rule bailed on anything but AB/EF. A förening is a juridisk person and follows the räkenskapsår schedule (SFL 26 kap 33 §), so the rule now keys on fiscalYearLockedToCalendar instead of the two literals; same in the MCP VAT report. 4. 2069 would have accumulated across years: the year-open omföring was AB-only with 2099/2098 hard-coded. planResultAppropriation now takes the pair from resultClosingAccounts (AB 2099 -> 2098, förening 2069 -> 2068) and skips forms with no carry (EF). 5. With the flag off, a registry lookup that returned "Ideell förening" was prefilled into the onboarding journey, the form picker was skipped and the create step answered "Ogiltig företagsform" with no way back. The journey, the BankID picker, the onboarding page and the MCP lookup now use mapSetupEntityType, which maps only creatable forms, so a flagged-off form falls through to the picker as before. Also: form picker keeps its AB-first order; tests for each fix. Part of #2072 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(migrations): move ideell förening migration after main's latest version (20260908143051) Two migrations landed on main after the branch forked; a lower version would be skipped by the merge-time apply. Staging history row renamed to match. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh * chore(skills): regenerate accounted-api reference for the widened entity_type enum Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PdGafpUA7jVV1oYjkwfQCh --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
190 lines
7.0 KiB
TypeScript
190 lines
7.0 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
import { resolveCompanyEntityType } from '@/lib/company/entity-type'
|
|
import { ensureInitialized } from '@/lib/init'
|
|
import { withRouteContext } from '@/lib/api/with-route-context'
|
|
import { validateBody } from '@/lib/api/validate'
|
|
import { InvoicesBulkBookSchema } from '@/lib/api/schemas'
|
|
import { issueAndBookInvoice, type IssuableInvoice } from '@/lib/invoices/issue-and-book-invoice'
|
|
import { booksInvoicesOnIssue } from '@/lib/bookkeeping/booking-mode'
|
|
import {
|
|
bookInvoiceDeferred,
|
|
INVOICE_BOOKABLE_STATUSES,
|
|
} from '@/lib/invoices/book-invoice-deferred'
|
|
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
|
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
|
import { getErrorEntry } from '@/lib/errors/structured-errors'
|
|
import type { CompanySettings, EntityType } from '@/types'
|
|
|
|
ensureInitialized()
|
|
|
|
interface BulkBookItemResult {
|
|
id: string
|
|
status: 'booked' | 'failed'
|
|
journal_entry_id?: string | null
|
|
error_code?: string
|
|
/** Swedish user-facing message; raw errors stay in logs. */
|
|
error?: string
|
|
}
|
|
|
|
function failItem(id: string, errorCode: string): BulkBookItemResult {
|
|
return {
|
|
id,
|
|
status: 'failed',
|
|
error_code: errorCode,
|
|
error: getErrorEntry(errorCode)?.message_sv ?? 'Något gick fel. Försök igen.',
|
|
}
|
|
}
|
|
|
|
/**
|
|
* POST /api/invoices/bulk-book
|
|
*
|
|
* One "Bokför" click for many customer invoices (MCP-created invoices land as
|
|
* drafts that used to need individual issuance). Per invoice:
|
|
* - draft → issueAndBookInvoice(): F-number + mark sent (NO
|
|
* email) + revenue verifikat. Exactly the mark-sent
|
|
* semantics; only when the company books at issue,
|
|
* deferred-booking companies get a per-item error
|
|
* instead of a silent issuance.
|
|
* - sent/overdue,
|
|
* unbooked → bookInvoiceDeferred(): the /book semantics
|
|
* (CAS-guarded claim).
|
|
* - anything else → per-item error.
|
|
*
|
|
* The loop is sequential on purpose: commit_journal_entry assigns voucher
|
|
* numbers atomically per call, so a serial loop keeps them gap-free and in
|
|
* order. Failures never abort the batch; each item reports its own outcome.
|
|
*/
|
|
export const POST = withRouteContext(
|
|
'invoice.bulk_book',
|
|
async (request, { user, supabase, companyId, log, requestId }) => {
|
|
const validated = await validateBody(request, InvoicesBulkBookSchema)
|
|
if (!validated.success) return validated.response
|
|
const { ids } = validated.data
|
|
|
|
// One settings read for the whole batch: issuance needs the full row
|
|
// (payment accounts + PDF branding), booking needs method + entity type.
|
|
const { data: settings, error: settingsError } = await supabase
|
|
.from('company_settings')
|
|
.select('*')
|
|
.eq('company_id', companyId)
|
|
.single()
|
|
if (settingsError || !settings) {
|
|
return errorResponseFromCode('INVOICE_SEND_COMPANY_SETTINGS_MISSING', log, { requestId })
|
|
}
|
|
// Under kontantmetoden nothing books before payment, so the whole request
|
|
// is a no-op: reject it instead of issuing drafts nobody asked to send.
|
|
if ((settings.accounting_method || 'accrual') !== 'accrual') {
|
|
return errorResponseFromCode('INVOICE_BOOK_CASH_METHOD', log, { requestId })
|
|
}
|
|
const entityType = await resolveCompanyEntityType(
|
|
supabase,
|
|
companyId,
|
|
(settings as Partial<CompanySettings>).entity_type,
|
|
)
|
|
|
|
const { data: invoices, error: fetchError } = await supabase
|
|
.from('invoices')
|
|
.select('*, customer:customers(*), items:invoice_items(*)')
|
|
.in('id', ids)
|
|
.eq('company_id', companyId)
|
|
if (fetchError) {
|
|
log.error('failed to fetch invoices for bulk book', fetchError)
|
|
return errorResponseFromCode('INTERNAL_ERROR', log, { requestId })
|
|
}
|
|
|
|
const invoicesById = new Map(
|
|
((invoices ?? []) as IssuableInvoice[]).map((invoice) => [invoice.id, invoice]),
|
|
)
|
|
const results: BulkBookItemResult[] = []
|
|
|
|
// Dedupe: the loop's already-booked checks read the pre-loop snapshot, so
|
|
// a repeated id would pass them twice and commit a second voucher that the
|
|
// CAS claim then cancels (a cancelled verifikat + gap explanation per
|
|
// duplicate). Each unique id is processed exactly once.
|
|
const uniqueIds = [...new Set(ids)]
|
|
|
|
for (const id of uniqueIds) {
|
|
const invoice = invoicesById.get(id)
|
|
if (!invoice) {
|
|
results.push(failItem(id, 'INVOICE_NOT_FOUND'))
|
|
continue
|
|
}
|
|
|
|
const isRealInvoice = !invoice.document_type || invoice.document_type === 'invoice'
|
|
if (!isRealInvoice || invoice.credited_invoice_id) {
|
|
results.push(failItem(id, 'INVOICE_BOOK_NOT_BOOKABLE'))
|
|
continue
|
|
}
|
|
|
|
if (invoice.status === 'draft') {
|
|
// Deferred-booking companies (#967) issue via mark-sent and book via
|
|
// the explicit /book step. issueAndBookInvoice would consume an
|
|
// F-number and flip the draft to sent WITHOUT booking anything, an
|
|
// irreversible side effect nobody asked for, so the item fails
|
|
// before the invoice is touched.
|
|
if (!booksInvoicesOnIssue(settings)) {
|
|
results.push(failItem(id, 'INVOICE_BOOK_DEFERRED_DRAFT'))
|
|
continue
|
|
}
|
|
const result = await issueAndBookInvoice({
|
|
supabase,
|
|
companyId,
|
|
userId: user.id,
|
|
invoice,
|
|
settings: settings as CompanySettings,
|
|
log,
|
|
})
|
|
if (!result.ok) {
|
|
results.push(failItem(id, result.errorCode))
|
|
} else {
|
|
results.push({ id, status: 'booked', journal_entry_id: result.journalEntryId })
|
|
}
|
|
continue
|
|
}
|
|
|
|
if (INVOICE_BOOKABLE_STATUSES.includes(invoice.status)) {
|
|
// Worklist-canonical unbooked predicate: journal_entry_id IS NULL.
|
|
if (invoice.journal_entry_id) {
|
|
results.push(failItem(id, 'INVOICE_BOOK_ALREADY_BOOKED'))
|
|
continue
|
|
}
|
|
const result = await bookInvoiceDeferred({
|
|
supabase,
|
|
companyId,
|
|
userId: user.id,
|
|
invoice,
|
|
entityType,
|
|
log,
|
|
})
|
|
if (!result.ok) {
|
|
if (result.kind === 'domain') {
|
|
const code = (result.error as { code?: string } | null)?.code
|
|
results.push({
|
|
id,
|
|
status: 'failed',
|
|
...(code ? { error_code: code } : {}),
|
|
error: getErrorMessage(result.error),
|
|
})
|
|
} else {
|
|
results.push(failItem(id, result.errorCode))
|
|
}
|
|
} else {
|
|
results.push({ id, status: 'booked', journal_entry_id: result.journalEntryId })
|
|
}
|
|
continue
|
|
}
|
|
|
|
results.push(failItem(id, 'INVOICE_BOOK_INVALID_STATUS'))
|
|
}
|
|
|
|
const summary = {
|
|
total: results.length,
|
|
booked: results.filter((r) => r.status === 'booked').length,
|
|
failed: results.filter((r) => r.status === 'failed').length,
|
|
}
|
|
|
|
return NextResponse.json({ data: { results, summary } })
|
|
},
|
|
{ requireWrite: true },
|
|
)
|