diff --git a/app/src/main/groovy/se/alipsa/accounting/domain/LegalForm.groovy b/app/src/main/groovy/se/alipsa/accounting/domain/LegalForm.groovy index 26dd4152..b57c5c10 100644 --- a/app/src/main/groovy/se/alipsa/accounting/domain/LegalForm.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/domain/LegalForm.groovy @@ -4,9 +4,15 @@ import se.alipsa.accounting.support.I18n enum LegalForm { - AKTIEBOLAG, - ENSKILD_FIRMA, - HANDELSBOLAG_KB + AKTIEBOLAG('2099'), + ENSKILD_FIRMA('2019'), + HANDELSBOLAG_KB('2019') + + final String defaultResultAccount + + private LegalForm(String defaultResultAccount) { + this.defaultResultAccount = defaultResultAccount + } String getDisplayName() { I18n.instance.getString("legalForm.${name()}") diff --git a/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy b/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy index 4cdfd78d..d8cc0195 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy @@ -796,7 +796,7 @@ class AccountingMcpTools { private Map previewYearEnd(Map args) { long companyId = requiredLong(args, 'company_id') long fiscalYearId = requiredLong(args, 'fiscal_year_id') - String closingAccount = optionalString(args, 'closing_account', ClosingService.DEFAULT_CLOSING_ACCOUNT) + String closingAccount = optionalString(args, 'closing_account', null) try { long expectedCompanyId = companyService.resolveFromFiscalYear(fiscalYearId) if (expectedCompanyId != companyId) { @@ -812,10 +812,12 @@ class AccountingMcpTools { next_fiscal_year_name: preview.nextFiscalYear?.name, next_fiscal_year_will_be_created: preview.nextFiscalYearWillBeCreated, closing_account: preview.closingAccountNumber, - result_account_count: preview.resultAccountCount, + result_accounts_with_balance_count: preview.resultAccountsWithBalanceCount, income_total: preview.incomeTotal, expense_total: preview.expenseTotal, net_result: preview.netResult, + transferred_result: preview.transferredResult, + remaining_result: preview.remainingResult, blocking_issues: preview.blockingIssues, warnings: preview.warnings, ready_to_close: readyToClose, @@ -829,7 +831,7 @@ class AccountingMcpTools { private Map closeFiscalYear(Map args) { long companyId = requiredLong(args, 'company_id') long fiscalYearId = requiredLong(args, 'fiscal_year_id') - String closingAccount = optionalString(args, 'closing_account', ClosingService.DEFAULT_CLOSING_ACCOUNT) + String closingAccount = optionalString(args, 'closing_account', null) String providedToken = args.get('preview_token') as String if (!providedToken) { return [ok: false, errors: ['preview_token krävs — kör preview_year_end först.']] @@ -840,6 +842,7 @@ class AccountingMcpTools { if (expectedCompanyId != companyId) { return [ok: false, errors: ["Fiscal year ${fiscalYearId} does not belong to company ${companyId}.".toString()]] } + closingAccount = closingAccount == null ? closingService.defaultClosingAccount(fiscalYearId) : closingAccount String expectedToken = yearEndPreviewToken(fiscalYearId, closingAccount) if (providedToken != expectedToken) { return [ok: false, errors: ['preview_token stämmer inte — kör preview_year_end igen.']] @@ -858,10 +861,12 @@ class AccountingMcpTools { next_fiscal_year_name: result.nextFiscalYear?.name, closing_voucher_id: result.closingVoucher?.id, closing_voucher_number: result.closingVoucher?.voucherNumber, - result_account_count: result.resultAccountCount, + result_accounts_with_balance_count: result.resultAccountsWithBalanceCount, opening_balance_count: result.openingBalanceCount, closing_entry_count: result.closingEntryCount, net_result: result.netResult, + transferred_result: result.transferredResult, + remaining_result: result.remainingResult, warnings: result.warnings ] } catch (Exception exception) { diff --git a/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy b/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy index 154984cf..794c7ccf 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy @@ -1,5 +1,7 @@ package se.alipsa.accounting.mcp +import se.alipsa.accounting.domain.LegalForm + /** * Builds MCP tool schemas exposed by the local accounting MCP server. */ @@ -195,24 +197,31 @@ final class McpToolDefinitions { ] } + private static String closingAccountDescription() { + String defaults = LegalForm.values().collect { LegalForm form -> + "${form.name()}: ${form.defaultResultAccount}".toString() + }.join(', ') + "Optional closing account number. Defaults by legal form (${defaults}); an unset legal form uses ${LegalForm.AKTIEBOLAG.defaultResultAccount}." + } + private static List> yearEndToolDefs() { [ toolDef('preview_year_end', - 'Runs year-end closing pre-checks. Returns blocking issues, warnings, totals, net result, and a preview_token.', + 'Runs year-end closing pre-checks. Returns blocking issues, warnings, income_total and expense_total excluding 8999, net_result for the year, transferred_result via 8999, remaining_result to transfer, result_accounts_with_balance_count, and a preview_token.', ['company_id', 'fiscal_year_id'], [ company_id: intParam('Company ID'), fiscal_year_id: intParam('Fiscal year ID to preview'), - closing_account: optStrParam('Optional closing account number. Defaults to "2099".') + closing_account: optStrParam(closingAccountDescription()) ] ), toolDef('close_fiscal_year', - 'Closes the fiscal year. Requires the preview_token returned by preview_year_end for the same fiscal year and closing account.', + 'Closes the fiscal year. Requires the preview_token returned by preview_year_end for the same fiscal year and closing account. Returns the preview\'s net_result, prior transferred_result, remaining_result posted by this closing, and result_accounts_with_balance_count.', ['company_id', 'fiscal_year_id', 'preview_token'], [ company_id: intParam('Company ID'), fiscal_year_id: intParam('Fiscal year ID to close'), - closing_account: optStrParam('Optional closing account number. Defaults to "2099".'), + closing_account: optStrParam(closingAccountDescription()), preview_token: strParam('Token returned by preview_year_end.') ] ), diff --git a/app/src/main/groovy/se/alipsa/accounting/service/ClosingModels.groovy b/app/src/main/groovy/se/alipsa/accounting/service/ClosingModels.groovy index 381dd6d9..c740e73e 100644 --- a/app/src/main/groovy/se/alipsa/accounting/service/ClosingModels.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/service/ClosingModels.groovy @@ -12,10 +12,12 @@ final class YearEndClosingPreview { FiscalYear nextFiscalYear boolean nextFiscalYearWillBeCreated String closingAccountNumber - int resultAccountCount + int resultAccountsWithBalanceCount BigDecimal incomeTotal BigDecimal expenseTotal BigDecimal netResult + BigDecimal transferredResult + BigDecimal remainingResult List blockingIssues = [] List warnings = [] } @@ -26,10 +28,12 @@ final class YearEndClosingResult { FiscalYear closedFiscalYear FiscalYear nextFiscalYear Voucher closingVoucher - int resultAccountCount + int resultAccountsWithBalanceCount int openingBalanceCount int closingEntryCount BigDecimal netResult + BigDecimal transferredResult + BigDecimal remainingResult List warnings = [] } @@ -68,3 +72,13 @@ final class ClosingExecution { int openingBalanceCount int closingEntryCount } + +@Canonical +final class ClosingResultTotals { + + BigDecimal incomeTotal + BigDecimal expenseTotal + BigDecimal netResult + BigDecimal transferredResult + BigDecimal remainingResult +} diff --git a/app/src/main/groovy/se/alipsa/accounting/service/ClosingService.groovy b/app/src/main/groovy/se/alipsa/accounting/service/ClosingService.groovy index 99b85295..79d00a14 100644 --- a/app/src/main/groovy/se/alipsa/accounting/service/ClosingService.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/service/ClosingService.groovy @@ -5,6 +5,7 @@ import groovy.sql.Sql import se.alipsa.accounting.domain.ClosingEntry import se.alipsa.accounting.domain.FiscalYear +import se.alipsa.accounting.domain.LegalForm import se.alipsa.accounting.domain.Voucher import se.alipsa.accounting.domain.VoucherLine import se.alipsa.accounting.support.AmountFormatter @@ -19,7 +20,7 @@ import java.time.LocalDate */ final class ClosingService { - static final String DEFAULT_CLOSING_ACCOUNT = '2099' + static final String DEFAULT_CLOSING_ACCOUNT = LegalForm.AKTIEBOLAG.defaultResultAccount static final String DEFAULT_CLOSING_SERIES = 'YE' static final String RESULT_CLOSING = 'RESULT_CLOSING' static final String OPENING_BALANCE = 'OPENING_BALANCE' @@ -101,7 +102,18 @@ final class ClosingService { this.clock = clock } - YearEndClosingPreview previewClosing(long fiscalYearId, String closingAccountNumber = DEFAULT_CLOSING_ACCOUNT) { + String defaultClosingAccount(long fiscalYearId) { + databaseService.withSql { Sql sql -> + defaultClosingAccount(sql, resolveCompanyId(sql, fiscalYearId)) + } + } + + private static String defaultClosingAccount(Sql sql, long companyId) { + String legalForm = sql.firstRow('select legal_form from company where id = ?', [companyId]).get('legal_form') as String + LegalForm.fromDatabaseValue(legalForm)?.defaultResultAccount ?: DEFAULT_CLOSING_ACCOUNT + } + + YearEndClosingPreview previewClosing(long fiscalYearId, String closingAccountNumber = null) { long companyId = databaseService.withSql { Sql sql -> resolveCompanyId(sql, fiscalYearId) } @@ -111,7 +123,7 @@ final class ClosingService { } } - YearEndClosingResult closeFiscalYear(long fiscalYearId, String closingAccountNumber = DEFAULT_CLOSING_ACCOUNT) { + YearEndClosingResult closeFiscalYear(long fiscalYearId, String closingAccountNumber = null) { long companyId = databaseService.withSql { Sql sql -> resolveCompanyId(sql, fiscalYearId) } @@ -131,10 +143,12 @@ final class ClosingService { nextFiscalYear, false, preview.closingAccountNumber, - preview.resultAccountCount, + preview.resultAccountsWithBalanceCount, preview.incomeTotal, preview.expenseTotal, preview.netResult, + preview.transferredResult, + preview.remainingResult, preview.blockingIssues, preview.warnings ) @@ -144,10 +158,12 @@ final class ClosingService { closedYear, nextFiscalYear, execution.closingVoucher, - executionPreview.resultAccountCount, + executionPreview.resultAccountsWithBalanceCount, execution.openingBalanceCount, execution.closingEntryCount, executionPreview.netResult, + executionPreview.transferredResult, + executionPreview.remainingResult, executionPreview.warnings ) } @@ -181,7 +197,9 @@ final class ClosingService { List integrityProblems ) { FiscalYear fiscalYear = requireFiscalYear(sql, fiscalYearId) - String safeClosingAccount = normalizeAccountNumber(closingAccountNumber) + long companyId = resolveCompanyId(sql, fiscalYear.id) + String safeClosingAccount = normalizeAccountNumber( + closingAccountNumber == null ? defaultClosingAccount(sql, companyId) : closingAccountNumber) List blockers = [] List warnings = [] @@ -196,7 +214,6 @@ final class ClosingService { blockers << ("Integritetskontrollerna måste vara gröna före årsstängning:\n${summary}" as String) } - long companyId = resolveCompanyId(sql, fiscalYear.id) BalanceAccountSeed closingAccount = loadAccount(sql, companyId, safeClosingAccount) if (closingAccount == null) { blockers << ("Resultat förs mot konto ${safeClosingAccount}, men kontot saknas i kontoplanen." as String) @@ -212,22 +229,9 @@ final class ClosingService { appendUnclassifiedAccountBlocker(sql, fiscalYear.id, blockers) Map resultBalances = loadResultBalances(sql, fiscalYear.id) - BigDecimal incomeTotal = resultBalances.values() - .findAll { ResultAccountBalance balance -> balance.accountClass == 'INCOME' } - .sum(BigDecimal.ZERO) { ResultAccountBalance balance -> balance.amount } as BigDecimal - BigDecimal expenseTotal = resultBalances.values() - .findAll { ResultAccountBalance balance -> balance.accountClass == 'EXPENSE' } - .sum(BigDecimal.ZERO) { ResultAccountBalance balance -> balance.amount } as BigDecimal - BigDecimal netResult = scale(incomeTotal - expenseTotal) - - if (resultBalances.isEmpty()) { - warnings << 'Inga resultatkonton med saldo hittades. Bokslutsverifikationen blir tom och hoppas över.' - } - appendAlreadyTransferredResultWarning(resultBalances, netResult, warnings) - LocalDate dueDate = fiscalYear.endDate.plusMonths(6) - if (LocalDate.now(clock).isAfter(dueDate)) { - warnings << ("Bokslutsfristen passerade ${dueDate}. Årsbokslutet borde redan vara upprättat." as String) - } + ClosingResultTotals totals = calculateResultTotals(resultBalances) + appendTransferAccountBlocker(sql, companyId, totals.remainingResult, blockers) + appendClosingWarnings(fiscalYear, resultBalances, totals, warnings) NextFiscalYearPlan nextPlan = planNextFiscalYear(sql, companyId, fiscalYear) if (nextPlan.conflictMessage != null) { @@ -250,34 +254,100 @@ final class ClosingService { nextPlan.willCreate, safeClosingAccount, resultBalances.size(), - scale(incomeTotal), - scale(expenseTotal), - netResult, + totals.incomeTotal, + totals.expenseTotal, + totals.netResult, + totals.transferredResult, + totals.remainingResult, blockers, warnings ) } - private static void appendAlreadyTransferredResultWarning( + private static ClosingResultTotals calculateResultTotals(Map resultBalances) { + Collection operatingBalances = resultBalances.values().findAll { ResultAccountBalance balance -> + balance.accountNumber != '8999' + } + // Derive the totals from the debit/credit direction of the entries so that + // income - expenses = netResult even when an account's normal side contradicts + // its class; a misclassified account would otherwise flip the sign of one total. + BigDecimal incomeTotal = operatingBalances.findAll { ResultAccountBalance balance -> balance.accountClass == 'INCOME' } + .sum(BigDecimal.ZERO) { ResultAccountBalance balance -> -naturalAmount(balance) } as BigDecimal + BigDecimal expenseTotal = operatingBalances.findAll { ResultAccountBalance balance -> balance.accountClass == 'EXPENSE' } + .sum(BigDecimal.ZERO) { ResultAccountBalance balance -> naturalAmount(balance) } as BigDecimal + BigDecimal naturalNet = operatingBalances.sum(BigDecimal.ZERO) { ResultAccountBalance balance -> + naturalAmount(balance) + } as BigDecimal + ResultAccountBalance transfer = resultBalances['8999'] + BigDecimal netResult = scale(-naturalNet) + BigDecimal transferredResult = transfer == null ? BigDecimal.ZERO : naturalAmount(transfer) + new ClosingResultTotals(scale(incomeTotal), scale(expenseTotal), netResult, + scale(transferredResult), scale(netResult - transferredResult)) + } + + private static BigDecimal naturalAmount(ResultAccountBalance balance) { + // amount is signed by the account's normal side, so flipping credit-normal accounts + // yields the debit-minus-credit direction regardless of classification. + balance.normalBalanceSide == 'DEBIT' ? balance.amount : -balance.amount + } + + private void appendClosingWarnings( + FiscalYear fiscalYear, Map resultBalances, - BigDecimal netResult, + ClosingResultTotals totals, List warnings ) { - ResultAccountBalance yearResultTransfer = resultBalances['8999'] - if (yearResultTransfer == null) { + if (totals.remainingResult == BigDecimal.ZERO) { + warnings << 'Inget återstående resultat att överföra. Bokslutsverifikationen hoppas över.' + } + appendMisclassifiedResultAccountWarning(resultBalances, warnings) + appendAlreadyTransferredResultWarning(totals, warnings) + LocalDate dueDate = fiscalYear.endDate.plusMonths(6) + if (LocalDate.now(clock).isAfter(dueDate)) { + warnings << ("Bokslutsfristen passerade ${dueDate}. Årsbokslutet borde redan vara upprättat." as String) + } + } + + private static void appendMisclassifiedResultAccountWarning( + Map resultBalances, + List warnings + ) { + List mismatched = resultBalances.values() + .findAll { ResultAccountBalance balance -> + (balance.accountClass == 'INCOME' && balance.normalBalanceSide == 'DEBIT') || + (balance.accountClass == 'EXPENSE' && balance.normalBalanceSide == 'CREDIT') + } + .sort { ResultAccountBalance balance -> balance.accountNumber } + .collect { ResultAccountBalance balance -> "${balance.accountNumber} (${balance.accountClass}/${balance.normalBalanceSide})" as String } + if (!mismatched.isEmpty()) { + warnings << ("Följande resultatkonton har en normalsida som avviker från kontoklassen: ${mismatched.join(', ')}. " + + 'Resultatöverföringen beräknas från debet/kredit per konto och påverkas inte, men kontona bör rättas i kontoplanen.' as String) + } + } + + private static void appendTransferAccountBlocker(Sql sql, long companyId, BigDecimal remainingResult, List blockers) { + if (remainingResult != BigDecimal.ZERO) { + BalanceAccountSeed transferAccount = loadAccount(sql, companyId, '8999') + if (transferAccount == null || !transferAccount.active || transferAccount.accountClass != 'EXPENSE' || + transferAccount.normalBalanceSide != 'DEBIT') { + blockers << 'Konto 8999 måste finnas, vara aktivt och klassat som kostnad med debet som normalsida för årsbokslut.' + } + } + } + + private static void appendAlreadyTransferredResultWarning(ClosingResultTotals totals, List warnings) { + if (totals.transferredResult == BigDecimal.ZERO) { return } - // Imported years may already contain the year-end transfer (8999 -> 2099). The preview's - // net result then shows what remains to transfer (about 0), not the year's result. - warnings << ("Årets resultat har redan förts över via konto 8999 (${AmountFormatter.format(yearResultTransfer.amount, null)}); " + - "bokslutet överför återstående ${AmountFormatter.format(netResult, null)}." as String) + // Imported years may already contain some or all of the year-end transfer. + warnings << ("Årets resultat har redan förts över via konto 8999 (${AmountFormatter.format(totals.transferredResult, null)}); " + + "bokslutet överför återstående ${AmountFormatter.format(totals.remainingResult, null)}." as String) } private ClosingExecution executeClosing(Sql sql, YearEndClosingPreview preview) { - Map resultBalances = loadResultBalances(sql, preview.fiscalYear.id) - Voucher closingVoucher = resultBalances.isEmpty() + Voucher closingVoucher = preview.remainingResult == BigDecimal.ZERO ? null - : createClosingVoucher(sql, preview.fiscalYear, preview.closingAccountNumber, resultBalances) + : createClosingVoucher(sql, preview.fiscalYear, preview.closingAccountNumber, preview.remainingResult) long companyId = resolveCompanyId(sql, preview.fiscalYear.id) int closingEntryCount = persistResultClosingEntries( @@ -285,7 +355,7 @@ final class ClosingService { preview.fiscalYear.id, closingVoucher?.id, preview.closingAccountNumber, - resultBalances + preview.remainingResult ) Map closingBalances = openingBalanceService.loadBalanceClosingBalances(sql, preview.fiscalYear.id) int openingBalanceCount = openingBalanceService.replaceYearEndClosingBalances( @@ -302,9 +372,9 @@ final class ClosingService { Sql sql, FiscalYear fiscalYear, String closingAccountNumber, - Map resultBalances + BigDecimal remainingResult ) { - List lines = buildClosingVoucherLines(resultBalances, closingAccountNumber) + List lines = buildClosingVoucherLines(remainingResult, closingAccountNumber) voucherService.createVoucherBypassLock( sql, fiscalYear.id, @@ -316,65 +386,19 @@ final class ClosingService { } private static List buildClosingVoucherLines( - Map resultBalances, + BigDecimal remainingResult, String closingAccountNumber ) { - List lines = [] - BigDecimal debitTotal = BigDecimal.ZERO.setScale(AMOUNT_SCALE) - BigDecimal creditTotal = BigDecimal.ZERO.setScale(AMOUNT_SCALE) - int lineIndex = 1 - resultBalances.keySet().sort().each { String accountNumber -> - ResultAccountBalance balance = resultBalances[accountNumber] - BigDecimal amount = scale(balance.amount) - if (amount == BigDecimal.ZERO) { - return - } - BigDecimal debitAmount = BigDecimal.ZERO.setScale(AMOUNT_SCALE) - BigDecimal creditAmount = BigDecimal.ZERO.setScale(AMOUNT_SCALE) - if (amount > BigDecimal.ZERO) { - if (balance.normalBalanceSide == 'DEBIT') { - creditAmount = amount - } else { - debitAmount = amount - } - } else { - BigDecimal absolute = scale(amount.abs()) - if (balance.normalBalanceSide == 'DEBIT') { - debitAmount = absolute - } else { - creditAmount = absolute - } - } - debitTotal = scale(debitTotal + debitAmount) - creditTotal = scale(creditTotal + creditAmount) - lines << new VoucherLine( - null, - null, - lineIndex++, - null, - balance.accountNumber, - balance.accountName, - "Årsbokslut ${balance.accountNumber}", - debitAmount, - creditAmount - ) - } - - BigDecimal difference = scale(debitTotal - creditTotal) - if (difference != BigDecimal.ZERO) { - lines << new VoucherLine( - null, - null, - lineIndex, - null, - closingAccountNumber, - null, - "Årets resultat ${closingAccountNumber}", - difference < BigDecimal.ZERO ? difference.abs() : BigDecimal.ZERO.setScale(AMOUNT_SCALE), - difference > BigDecimal.ZERO ? difference : BigDecimal.ZERO.setScale(AMOUNT_SCALE) - ) - } - lines + // Preserve each operating account; 8999 offsets their aggregate result in the ledger. + BigDecimal zero = BigDecimal.ZERO.setScale(AMOUNT_SCALE) + [ + new VoucherLine(null, null, 1, null, '8999', null, 'Årets resultat', + remainingResult > zero ? remainingResult : zero, + remainingResult < zero ? remainingResult.abs() : zero), + new VoucherLine(null, null, 2, null, closingAccountNumber, null, "Årets resultat ${closingAccountNumber}", + remainingResult < zero ? remainingResult.abs() : zero, + remainingResult > zero ? remainingResult : zero) + ] } private static int persistResultClosingEntries( @@ -382,33 +406,21 @@ final class ClosingService { long fiscalYearId, Long voucherId, String closingAccountNumber, - Map resultBalances + BigDecimal amount ) { - int created = 0 + if (voucherId == null) { + return 0 + } long companyId = resolveCompanyId(sql, fiscalYearId) + long accountId = resolveAccountId(sql, companyId, '8999') long counterAccountId = resolveAccountId(sql, companyId, closingAccountNumber) - resultBalances.keySet().sort().each { String accountNumber -> - ResultAccountBalance balance = resultBalances[accountNumber] - BigDecimal amount = scale(balance.amount) - if (amount == BigDecimal.ZERO) { - return - } - long accountId = resolveAccountId(sql, companyId, balance.accountNumber) - sql.executeInsert(''' - insert into closing_entry ( - fiscal_year_id, - next_fiscal_year_id, - voucher_id, - entry_type, - account_id, - counter_account_id, - amount, - created_at - ) values (?, null, ?, ?, ?, ?, ?, current_timestamp) - ''', [fiscalYearId, voucherId, RESULT_CLOSING, accountId, counterAccountId, amount]) - created++ - } - created + sql.executeInsert(''' + insert into closing_entry ( + fiscal_year_id, next_fiscal_year_id, voucher_id, entry_type, + account_id, counter_account_id, amount, created_at + ) values (?, null, ?, ?, ?, ?, ?, current_timestamp) + ''', [fiscalYearId, voucherId, RESULT_CLOSING, accountId, counterAccountId, amount]) + 1 } private static int persistOpeningBalanceEntries( diff --git a/app/src/main/groovy/se/alipsa/accounting/service/ReportAccountSupport.groovy b/app/src/main/groovy/se/alipsa/accounting/service/ReportAccountSupport.groovy index 22a2d0f4..8dcb10ef 100644 --- a/app/src/main/groovy/se/alipsa/accounting/service/ReportAccountSupport.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/service/ReportAccountSupport.groovy @@ -10,9 +10,9 @@ final class ReportAccountSupport { private ReportAccountSupport() { } - static boolean shouldExcludeFromIncomeStatement(String accountNumber, AccountSubgroup subgroup) { + static boolean shouldExcludeFromIncomeStatement(String accountNumber) { // 8999 = "Årets resultat" (BAS): balance-sheet result transfer, not an income statement line. - subgroup == AccountSubgroup.TAX_AND_RESULT && accountNumber == '8999' + accountNumber == '8999' } static String inferIncomeAccountClass(AccountSubgroup subgroup) { diff --git a/app/src/main/groovy/se/alipsa/accounting/service/ReportDataService.groovy b/app/src/main/groovy/se/alipsa/accounting/service/ReportDataService.groovy index 2f7589fc..0e10c338 100644 --- a/app/src/main/groovy/se/alipsa/accounting/service/ReportDataService.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/service/ReportDataService.groovy @@ -479,7 +479,7 @@ final class ReportDataService { log.warning("Konto ${accountNumber} (${info.accountName}) saknar undergrupp och exkluderas från resultatrapporten.") return } - if (shouldExcludeFromIncomeStatement(accountNumber, subgroup)) { + if (shouldExcludeFromIncomeStatement(accountNumber)) { return } String incomeAccountClass = resolveIncomeAccountClass(accountNumber, info, subgroup) diff --git a/app/src/main/groovy/se/alipsa/accounting/service/SieImportExportService.groovy b/app/src/main/groovy/se/alipsa/accounting/service/SieImportExportService.groovy index af902a2f..28dd290f 100644 --- a/app/src/main/groovy/se/alipsa/accounting/service/SieImportExportService.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/service/SieImportExportService.groovy @@ -902,6 +902,7 @@ final class SieImportExportService { document.setKONTO(konto) document.setIB(buildOpeningBalances(document, openings)) document.setUB(buildClosingBalances(document, closings)) + document.setRES(buildResultBalances(sql, fiscalYearId, document)) document.setVER(buildExportVouchers(document, vouchers)) new ExportPayload( @@ -1033,6 +1034,29 @@ final class SieImportExportService { rows } + private static List buildResultBalances(Sql sql, long fiscalYearId, SieDocument document) { + sql.rows(''' + select vl.account_number as accountNumber, + sum(vl.debit_amount - vl.credit_amount) as amount + from voucher v + join voucher_line vl on vl.voucher_id = v.id + join account a on a.id = vl.account_id + where v.fiscal_year_id = ? + and v.status in ('ACTIVE', 'CORRECTION') + and a.account_class in ('INCOME', 'EXPENSE') + group by vl.account_number + having sum(vl.debit_amount - vl.credit_amount) <> 0 + order by vl.account_number + ''', [fiscalYearId]).collect { GroovyRowResult row -> + SiePeriodValue value = new SiePeriodValue() + value.yearNr = 0 + value.account = document.getKONTO().get(row.get('accountNumber') as String) + value.amount = scale(new BigDecimal(row.get('amount').toString())) + value.token = SIE.RES + value + } + } + private static List buildExportVouchers(SieDocument document, List vouchers) { vouchers.collect { ExportVoucherSeed voucherSeed -> SieVoucher voucher = new SieVoucher() diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/YearEndClosingAccountGuard.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/YearEndClosingAccountGuard.groovy new file mode 100644 index 00000000..acfd393f --- /dev/null +++ b/app/src/main/groovy/se/alipsa/accounting/ui/YearEndClosingAccountGuard.groovy @@ -0,0 +1,37 @@ +package se.alipsa.accounting.ui + +import javax.swing.JButton +import javax.swing.JTextField +import javax.swing.event.DocumentListener + +/** + * Keeps the year-end closing account field and the Execute button in sync. + * Any manual edit of the field disables Execute until the preview is refreshed, + * and execution always uses the account from the last completed preview rather + * than the raw field text, which may be mid-edit. + */ +final class YearEndClosingAccountGuard { + + private final JTextField accountField + private final JButton executeButton + private String previewedAccountNumber + + YearEndClosingAccountGuard(JTextField accountField, JButton executeButton) { + this.accountField = accountField + this.executeButton = executeButton + accountField.document.addDocumentListener([ + insertUpdate: { executeButton.enabled = false }, + removeUpdate: { executeButton.enabled = false }, + changedUpdate: { executeButton.enabled = false } + ] as DocumentListener) + } + + void previewCompleted(String accountNumber) { + previewedAccountNumber = accountNumber + accountField.text = accountNumber + } + + String accountForExecution() { + previewedAccountNumber + } +} diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/YearEndClosingDialog.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/YearEndClosingDialog.groovy index 3aa262c0..906e7fdc 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/YearEndClosingDialog.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/YearEndClosingDialog.groovy @@ -42,6 +42,7 @@ final class YearEndClosingDialog extends JDialog { private final JTextArea messageArea = new JTextArea(6, 48) private final JButton previewButton = new JButton(I18n.instance.getString('yearEndClosingDialog.button.preview')) private final JButton executeButton = new JButton(I18n.instance.getString('yearEndClosingDialog.button.execute')) + private final YearEndClosingAccountGuard accountGuard = new YearEndClosingAccountGuard(closingAccountField, executeButton) private boolean workInProgress YearEndClosingDialog(Frame owner, ClosingService closingService, FiscalYear fiscalYear, Locale locale, Runnable onClosed) { @@ -50,7 +51,6 @@ final class YearEndClosingDialog extends JDialog { this.fiscalYear = fiscalYear this.locale = locale this.onClosed = onClosed ?: ({ } as Runnable) - closingAccountField.text = ClosingService.DEFAULT_CLOSING_ACCOUNT buildUi() reloadPreview() } @@ -138,7 +138,7 @@ final class YearEndClosingDialog extends JDialog { } private void reloadPreview() { - String closingAccountNumber = closingAccountField.text + String closingAccountNumber = closingAccountField.text?.trim() ?: null setWorkingState(true) summaryArea.text = I18n.instance.getString('yearEndClosingDialog.status.runningPreview') messageArea.text = '' @@ -151,8 +151,12 @@ final class YearEndClosingDialog extends JDialog { @Override protected void done() { setWorkingState(false) + executeButton.enabled = false + summaryArea.text = '' try { - renderPreview(get()) + YearEndClosingPreview preview = get() + accountGuard.previewCompleted(preview.closingAccountNumber) + renderPreview(preview) } catch (InterruptedException exception) { Thread.currentThread().interrupt() renderMessage(new Color(153, 27, 27), I18n.instance.getString('yearEndClosingDialog.status.previewInterrupted')) @@ -172,13 +176,7 @@ final class YearEndClosingDialog extends JDialog { ? I18n.instance.format('yearEndClosingDialog.status.nextFiscalYear.creating', preview.nextFiscalYear.name) : I18n.instance.format('yearEndClosingDialog.status.nextFiscalYear.exists', preview.nextFiscalYear.name) - List rows = [ - I18n.instance.format('yearEndClosingDialog.summary.income', AmountFormatter.format(preview.incomeTotal, locale)), - I18n.instance.format('yearEndClosingDialog.summary.expenses', AmountFormatter.format(preview.expenseTotal, locale)), - I18n.instance.format('yearEndClosingDialog.summary.netResult', AmountFormatter.format(preview.netResult, locale)), - I18n.instance.format('yearEndClosingDialog.summary.resultAccounts', preview.resultAccountCount as Object) - ] - summaryArea.text = rows.join('\n') + summaryArea.text = summaryLines(preview, locale).join('\n') if (!preview.blockingIssues.isEmpty()) { executeButton.enabled = false @@ -194,6 +192,17 @@ final class YearEndClosingDialog extends JDialog { } } + static List summaryLines(YearEndClosingPreview preview, Locale locale) { + [ + I18n.instance.format('yearEndClosingDialog.summary.income', AmountFormatter.format(preview.incomeTotal, locale)), + I18n.instance.format('yearEndClosingDialog.summary.expenses', AmountFormatter.format(preview.expenseTotal, locale)), + I18n.instance.format('yearEndClosingDialog.summary.netResult', AmountFormatter.format(preview.netResult, locale)), + I18n.instance.format('yearEndClosingDialog.summary.transferredResult', AmountFormatter.format(preview.transferredResult, locale)), + I18n.instance.format('yearEndClosingDialog.summary.remainingResult', AmountFormatter.format(preview.remainingResult, locale)), + I18n.instance.format('yearEndClosingDialog.summary.resultAccounts', preview.resultAccountsWithBalanceCount as Object) + ] + } + private void executeRequested() { int choice = javax.swing.JOptionPane.showConfirmDialog( this, @@ -205,7 +214,7 @@ final class YearEndClosingDialog extends JDialog { return } - String closingAccountNumber = closingAccountField.text + String closingAccountNumber = accountGuard.accountForExecution() setWorkingState(true) summaryArea.text = I18n.instance.getString('yearEndClosingDialog.status.executing') new SwingWorker() { diff --git a/app/src/main/resources/docs/user-manual.md b/app/src/main/resources/docs/user-manual.md index 7a93c869..44875549 100644 --- a/app/src/main/resources/docs/user-manual.md +++ b/app/src/main/resources/docs/user-manual.md @@ -44,8 +44,10 @@ Programmet kan hantera flera företag i samma installation. Varje företag har s - Lås alla perioder innan årsbokslut genomförs. - Kör `Årsbokslut...` i fliken `Räkenskapsår`. -- Systemet stänger resultatkonton mot konto `2099` som standard och skapar nästa års ingående balanser. -- Förhandsgranskningen visar blockerande fel och varningar innan bokslutet genomförs. +- Systemet överför återstående årsresultat via konto `8999` mot konto `2099` för aktiebolag eller `2019` för enskild firma och handels-/kommanditbolag som standard och skapar nästa års ingående balanser. Konto `8999` måste vara aktivt och klassat som kostnad med debet som normalsida när ett resultat återstår att överföra. Om företagsformen inte är angiven används `2099`. Ett annat eget-kapital-konto kan väljas vid bokslut. +- För HB/KB bokas hela återstående resultatet mot `2019` (Årets resultat, delägare 1). För flera delägare måste resultatet därefter fördelas manuellt till delägarnas konton, till exempel `2029` eller företagets egna kapitalkonton. +- Intäkts- och kostnadskonton behåller sina saldon i det stängda året. Resultaträkningen visar resultatet före överföringen via `8999`; endast balanskonton förs vidare till nästa års ingående balanser. +- Förhandsgranskningen visar årets resultat före överföring, redan överfört belopp via `8999` och återstående belopp att överföra. Överföringen räknas inte som en kostnad i sammanställningen. Blockerande fel och varningar visas innan bokslutet genomförs. - Räkenskapsår kan raderas från fliken `Räkenskapsår` när bevarandespärren har passerat och inga blockerande beroenden finns. Förhandsgranskningen visar hur många verifikationer, bilagor, rapporter, momsperioder och andra poster som tas bort. ## Backup, restore och systeminformation diff --git a/app/src/main/resources/i18n/messages.properties b/app/src/main/resources/i18n/messages.properties index c3c52300..56cc2a63 100644 --- a/app/src/main/resources/i18n/messages.properties +++ b/app/src/main/resources/i18n/messages.properties @@ -543,7 +543,9 @@ yearEndClosingDialog.status.nextFiscalYear.exists={0} (already exists) yearEndClosingDialog.summary.income=Income: {0} yearEndClosingDialog.summary.expenses=Expenses: {0} yearEndClosingDialog.summary.netResult=Net result: {0} -yearEndClosingDialog.summary.resultAccounts=Result accounts to close: {0} +yearEndClosingDialog.summary.transferredResult=Already transferred (8999): {0} +yearEndClosingDialog.summary.remainingResult=Remaining to transfer: {0} +yearEndClosingDialog.summary.resultAccounts=Result accounts with balances: {0} yearEndClosingDialog.confirm.message=Execute year-end closing for {0} and create next year''s opening balances? yearEndClosingDialog.confirm.title=Confirm year-end closing yearEndClosingDialog.status.executing=Executing year-end closing... diff --git a/app/src/main/resources/i18n/messages_sv.properties b/app/src/main/resources/i18n/messages_sv.properties index 0f5c195b..877eb534 100644 --- a/app/src/main/resources/i18n/messages_sv.properties +++ b/app/src/main/resources/i18n/messages_sv.properties @@ -543,7 +543,9 @@ yearEndClosingDialog.status.nextFiscalYear.exists={0} (finns redan) yearEndClosingDialog.summary.income=Intäkter: {0} yearEndClosingDialog.summary.expenses=Kostnader: {0} yearEndClosingDialog.summary.netResult=Årets resultat: {0} -yearEndClosingDialog.summary.resultAccounts=Resultatkonton att stänga: {0} +yearEndClosingDialog.summary.transferredResult=Redan överfört (8999): {0} +yearEndClosingDialog.summary.remainingResult=Återstår att överföra: {0} +yearEndClosingDialog.summary.resultAccounts=Resultatkonton med saldo: {0} yearEndClosingDialog.confirm.message=Genomför årsbokslut för {0} och skapa nästa års ingående balanser? yearEndClosingDialog.confirm.title=Bekräfta årsbokslut yearEndClosingDialog.status.executing=Genomför årsbokslut... diff --git a/app/src/test/groovy/acceptance/se/alipsa/accounting/AcceptanceCriteriaTest.groovy b/app/src/test/groovy/acceptance/se/alipsa/accounting/AcceptanceCriteriaTest.groovy index 78031402..c7fd71d0 100644 --- a/app/src/test/groovy/acceptance/se/alipsa/accounting/AcceptanceCriteriaTest.groovy +++ b/app/src/test/groovy/acceptance/se/alipsa/accounting/AcceptanceCriteriaTest.groovy @@ -258,6 +258,7 @@ class AcceptanceCriteriaTest { insertAccountIfMissing(sql, companyId, '1510', 'Kundfordringar', 'ASSET', 'DEBIT', null) insertAccountIfMissing(sql, companyId, '1930', 'Företagskonto', 'ASSET', 'DEBIT', null) insertAccountIfMissing(sql, companyId, '2099', 'Årets resultat', 'EQUITY', 'CREDIT', null) + insertAccountIfMissing(sql, companyId, '8999', 'Årets resultat', 'EXPENSE', 'DEBIT', null) insertAccountIfMissing(sql, companyId, '2611', 'Utgående moms 25%', 'LIABILITY', 'CREDIT', VatCode.OUTPUT_25.name()) insertAccountIfMissing(sql, companyId, '2650', 'Redovisningskonto för moms', 'LIABILITY', 'CREDIT', null) insertAccountIfMissing(sql, companyId, '3010', 'Försäljning', 'INCOME', 'CREDIT', VatCode.OUTPUT_25.name()) @@ -431,6 +432,8 @@ class AcceptanceCriteriaTest { sheet.createRow(3).with { createCell(0).setCellValue('4010') createCell(1).setCellValue('Varukostnad') + createCell(2).setCellValue('8999') + createCell(3).setCellValue('Årets resultat') } Files.newOutputStream(workbookPath).withCloseable { output -> workbook.write(output) diff --git a/app/src/test/groovy/integration/se/alipsa/accounting/mcp/AccountingMcpToolsTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/mcp/AccountingMcpToolsTest.groovy index 3e2f4eb7..1e42b82b 100644 --- a/app/src/test/groovy/integration/se/alipsa/accounting/mcp/AccountingMcpToolsTest.groovy +++ b/app/src/test/groovy/integration/se/alipsa/accounting/mcp/AccountingMcpToolsTest.groovy @@ -1218,6 +1218,7 @@ class AccountingMcpToolsTest { private void insertClosingAccount() { insertAccount('2099', 'Årets resultat', 'EQUITY', 'CREDIT', null) + insertAccount('8999', 'Årets resultat', 'EXPENSE', 'DEBIT', null) } private long insertAccount( diff --git a/app/src/test/groovy/integration/se/alipsa/accounting/mcp/YearEndLegalFormMcpToolsTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/mcp/YearEndLegalFormMcpToolsTest.groovy new file mode 100644 index 00000000..8f2878bf --- /dev/null +++ b/app/src/test/groovy/integration/se/alipsa/accounting/mcp/YearEndLegalFormMcpToolsTest.groovy @@ -0,0 +1,180 @@ +package se.alipsa.accounting.mcp + +import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertFalse +import static org.junit.jupiter.api.Assertions.assertTrue + +import groovy.sql.Sql + +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource + +import se.alipsa.accounting.domain.Company +import se.alipsa.accounting.domain.LegalForm +import se.alipsa.accounting.domain.VoucherLine +import se.alipsa.accounting.service.AccountService +import se.alipsa.accounting.service.AccountingInstructionService +import se.alipsa.accounting.service.AccountingPeriodService +import se.alipsa.accounting.service.AttachmentService +import se.alipsa.accounting.service.AuditLogService +import se.alipsa.accounting.service.ClosingService +import se.alipsa.accounting.service.CompanyService +import se.alipsa.accounting.service.DatabaseService +import se.alipsa.accounting.service.FiscalYearService +import se.alipsa.accounting.service.ReportDataService +import se.alipsa.accounting.service.ReportIntegrityService +import se.alipsa.accounting.service.SieImportExportService +import se.alipsa.accounting.service.VatService +import se.alipsa.accounting.service.VoucherService +import se.alipsa.accounting.support.AppPaths + +import java.nio.file.Path +import java.time.LocalDate + +class YearEndLegalFormMcpToolsTest { + + @TempDir + Path tempDir + + private DatabaseService databaseService + private CompanyService companyService + private FiscalYearService fiscalYearService + private VoucherService voucherService + private AccountingMcpTools tools + private long fiscalYearId + private String previousHome + + @BeforeEach + void setUp() { + previousHome = System.getProperty(AppPaths.HOME_OVERRIDE_PROPERTY) + System.setProperty(AppPaths.HOME_OVERRIDE_PROPERTY, tempDir.toString()) + databaseService = DatabaseService.newForTesting() + databaseService.initialize() + AuditLogService audit = new AuditLogService(databaseService) + AccountingPeriodService periods = new AccountingPeriodService(databaseService, audit) + companyService = new CompanyService(databaseService) + fiscalYearService = new FiscalYearService(databaseService, periods, audit) + voucherService = new VoucherService(databaseService, audit) + ReportIntegrityService integrity = new ReportIntegrityService(new AttachmentService(databaseService, audit), audit) + tools = new AccountingMcpTools(companyService, fiscalYearService, new AccountService(databaseService), voucherService, + new VatService(databaseService, voucherService, audit), + new ClosingService(databaseService, periods, fiscalYearService, voucherService, integrity), + new ReportDataService(databaseService), + new SieImportExportService(databaseService, periods, voucherService, companyService, integrity, audit, fiscalYearService), + new AccountingInstructionService(databaseService)) + fiscalYearId = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)).id + databaseService.withTransaction { Sql sql -> + insertAccount(sql, '1930', 'Företagskonto', 'ASSET', 'DEBIT') + insertAccount(sql, '2019', 'Årets resultat, delägare 1', 'EQUITY', 'CREDIT') + insertAccount(sql, '2099', 'Årets resultat', 'EQUITY', 'CREDIT') + insertAccount(sql, '3010', 'Försäljning', 'INCOME', 'CREDIT') + insertAccount(sql, '4010', 'Varukostnad', 'EXPENSE', 'DEBIT') + insertAccount(sql, '8999', 'Årets resultat', 'EXPENSE', 'DEBIT') + } + } + + @AfterEach + void tearDown() { + try { + databaseService?.shutdown() + } finally { + if (previousHome == null) { + System.clearProperty(AppPaths.HOME_OVERRIDE_PROPERTY) + } else { + System.setProperty(AppPaths.HOME_OVERRIDE_PROPERTY, previousHome) + } + } + } + + @ParameterizedTest + @CsvSource(['AKTIEBOLAG, 2099,', 'ENSKILD_FIRMA, 2019,', 'HANDELSBOLAG_KB, 2019,', ', 2099,', + 'ENSKILD_FIRMA, 2099, 2099', 'AKTIEBOLAG, 2019, 2019']) + void yearEndUsesLegalFormDefaultAndExplicitOverrides(String legalForm, String expectedAccount, String overrideAccount) { + Company company = companyService.findById(CompanyService.LEGACY_COMPANY_ID) + company.legalForm = LegalForm.fromDatabaseValue(legalForm) + companyService.save(company) + voucherService.createVoucher(fiscalYearId, 'A', LocalDate.of(2026, 3, 1), 'Försäljning', [ + new VoucherLine(null, null, 0, null, '1930', null, null, 100.00G, 0.00G), + new VoucherLine(null, null, 0, null, '3010', null, null, 0.00G, 100.00G) + ]) + Map args = [company_id: (Object) company.id, fiscal_year_id: (Object) fiscalYearId] + + if (overrideAccount != null) { + args.put('closing_account', overrideAccount) + } + Map preview = tools.callTool('preview_year_end', args) + + assertEquals(expectedAccount, preview.get('closing_account')) + assertEquals(true, preview.get('ready_to_close')) + args.put('preview_token', preview.get('preview_token')) + Map result = tools.callTool('close_fiscal_year', args) + assertEquals(true, result.get('ok'), result.toString()) + long voucherId = ((Number) result.get('closing_voucher_id')).longValue() + assertTrue(voucherService.findVoucher(voucherId).lines.any { VoucherLine line -> + line.accountNumber == expectedAccount && line.creditAmount == 100.00G + }) + } + + @Test + void changingLegalFormInvalidatesYearEndPreviewWithADifferentDefault() { + Company company = companyService.findById(CompanyService.LEGACY_COMPANY_ID) + company.legalForm = LegalForm.ENSKILD_FIRMA + companyService.save(company) + Map args = [company_id: (Object) company.id, fiscal_year_id: (Object) fiscalYearId] + Map preview = tools.callTool('preview_year_end', args) + assertEquals('2019', preview.get('closing_account')) + company.legalForm = LegalForm.AKTIEBOLAG + companyService.save(company) + args.put('preview_token', preview.get('preview_token')) + + Map result = tools.callTool('close_fiscal_year', args) + + assertEquals(false, result.get('ok')) + assertTrue(result.get('errors').toString().contains('preview_token')) + assertFalse(fiscalYearService.findById(fiscalYearId).closed) + } + + @Test + void yearEndReportsActualResultAndRemainingTransferSeparately() { + voucherService.createVoucher(fiscalYearId, 'A', LocalDate.of(2026, 12, 31), 'Delvis överfört årsresultat', [ + new VoucherLine(null, null, 0, null, '1930', null, null, 1000.00G, 0.00G), + new VoucherLine(null, null, 0, null, '3010', null, null, 0.00G, 1000.00G), + new VoucherLine(null, null, 0, null, '4010', null, null, 300.00G, 0.00G), + new VoucherLine(null, null, 0, null, '1930', null, null, 0.00G, 300.00G), + new VoucherLine(null, null, 0, null, '8999', null, null, 400.00G, 0.00G), + new VoucherLine(null, null, 0, null, '2099', null, null, 0.00G, 400.00G) + ]) + Map args = [company_id: (Object) CompanyService.LEGACY_COMPANY_ID, fiscal_year_id: (Object) fiscalYearId] + + Map preview = tools.callTool('preview_year_end', args) + + assertEquals(1000.00G, preview.get('income_total')) + assertEquals(300.00G, preview.get('expense_total')) + assertEquals(700.00G, preview.get('net_result')) + assertEquals(400.00G, preview.get('transferred_result')) + assertEquals(300.00G, preview.get('remaining_result')) + assertEquals(3, preview.get('result_accounts_with_balance_count')) + assertFalse(preview.containsKey('result_account_count')) + args.put('preview_token', preview.get('preview_token')) + Map result = tools.callTool('close_fiscal_year', args) + assertEquals(true, result.get('ok'), result.toString()) + assertEquals(700.00G, result.get('net_result')) + assertEquals(400.00G, result.get('transferred_result')) + assertEquals(300.00G, result.get('remaining_result')) + assertEquals(3, result.get('result_accounts_with_balance_count')) + assertFalse(result.containsKey('result_account_count')) + } + + private static void insertAccount(Sql sql, String number, String name, String accountClass, String side) { + sql.executeInsert(''' + insert into account (company_id, account_number, account_name, account_class, normal_balance_side, + active, manual_review_required, created_at, updated_at) + values (?, ?, ?, ?, ?, true, false, current_timestamp, current_timestamp) + ''', [CompanyService.LEGACY_COMPANY_ID, number, name, accountClass, side]) + } +} diff --git a/app/src/test/groovy/integration/se/alipsa/accounting/service/ClosingServiceTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/service/ClosingServiceTest.groovy index 60a2b856..f8605ec5 100644 --- a/app/src/test/groovy/integration/se/alipsa/accounting/service/ClosingServiceTest.groovy +++ b/app/src/test/groovy/integration/se/alipsa/accounting/service/ClosingServiceTest.groovy @@ -14,11 +14,20 @@ import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.CsvSource import se.alipsa.accounting.domain.AuditLogEntry +import se.alipsa.accounting.domain.Company import se.alipsa.accounting.domain.FiscalYear +import se.alipsa.accounting.domain.LegalForm +import se.alipsa.accounting.domain.VatPeriodicity import se.alipsa.accounting.domain.Voucher import se.alipsa.accounting.domain.VoucherLine +import se.alipsa.accounting.domain.report.IncomeStatementRow +import se.alipsa.accounting.domain.report.IncomeStatementRowType +import se.alipsa.accounting.domain.report.ReportSelection +import se.alipsa.accounting.domain.report.ReportType import se.alipsa.accounting.support.AppPaths import java.nio.file.Path @@ -108,17 +117,19 @@ class ClosingServiceTest { def result = closingService.closeFiscalYear(fiscalYear.id) assertEquals('YE-1', result.closingVoucher.voucherNumber) - assertEquals(2, result.resultAccountCount) + assertEquals(2, result.resultAccountsWithBalanceCount) assertEquals(3, result.openingBalanceCount) - assertEquals(5, result.closingEntryCount) + assertEquals(4, result.closingEntryCount) assertTrue(result.closedFiscalYear.closed) assertEquals('2027', result.nextFiscalYear.name) Voucher closingVoucher = voucherService.findVoucher(result.closingVoucher.id) assertNotNull(closingVoucher) assertEquals(LocalDate.of(2026, 12, 31), closingVoucher.accountingDate) - assertEquals(1000.00G, lineForAccount(closingVoucher, '3010').debitAmount) - assertEquals(300.00G, lineForAccount(closingVoucher, '4010').creditAmount) + assertEquals(2, closingVoucher.lines.size()) + assertEquals(700.00G, lineForAccount(closingVoucher, '8999').debitAmount) + assertNull(lineForAccount(closingVoucher, '3010')) + assertNull(lineForAccount(closingVoucher, '4010')) assertEquals(700.00G, lineForAccount(closingVoucher, '2099').creditAmount) databaseService.withSql { Sql sql -> @@ -131,7 +142,7 @@ class ClosingServiceTest { assertTrue(auditEntries.any { AuditLogEntry entry -> entry.eventType == AuditLogService.CLOSE_FISCAL_YEAR && entry.fiscalYearId == fiscalYear.id }) - assertEquals(5, closingService.listClosingEntries(fiscalYear.id).size()) + assertEquals(4, closingService.listClosingEntries(fiscalYear.id).size()) } @Test @@ -288,9 +299,6 @@ class ClosingServiceTest { FiscalYear fiscalYear = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) FiscalYear nextFiscalYear = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2027', LocalDate.of(2027, 1, 1), LocalDate.of(2027, 12, 31)) seedClosingAccounts() - databaseService.withTransaction { Sql sql -> - insertAccount(sql, '8999', 'Årets resultat', 'EXPENSE', 'DEBIT') - } voucherService.createVoucher( fiscalYear.id, 'A', @@ -313,19 +321,15 @@ class ClosingServiceTest { ) def preview = closingService.previewClosing(fiscalYear.id) - assertEquals(0.00G, preview.netResult) + assertEquals(1000.00G, preview.netResult) + assertEquals(0.00G, preview.expenseTotal) + assertEquals(1000.00G, preview.transferredResult) + assertEquals(0.00G, preview.remainingResult) assertTrue(preview.warnings.any { String warning -> warning.contains('förts över via konto 8999') }) def result = closingService.closeFiscalYear(fiscalYear.id) - Voucher closingVoucher = voucherService.findVoucher(result.closingVoucher.id) - // NOTE(issue #130): the assertions below pin down the current closing-entries behaviour, - // which zeroes every result account. When #130 changes the closing to a single 8999 - // transfer, the 3010/8999 assertions here are expected to change; the 2099, - // opening-balance and balance assertions remain valid either way. - assertEquals(1000.00G, lineForAccount(closingVoucher, '3010').debitAmount) - assertEquals(1000.00G, lineForAccount(closingVoucher, '8999').creditAmount) - assertNull(lineForAccount(closingVoucher, '2099')) + assertNull(result.closingVoucher) databaseService.withSql { Sql sql -> // 2099 carries the result exactly once in the next year's opening balances... assertEquals(1000.00G, openingBalanceFor(sql, nextFiscalYear.id, '1510')) @@ -389,6 +393,254 @@ class ClosingServiceTest { } } + @ParameterizedTest + @CsvSource(['1000, 0', '-1000, 0', '1000, 400', '-1000, -400', '1000, 1200', '1000, 1000', '0, 0']) + void closingPreservesReportsWithMisgroupedTransferAccount(BigDecimal earned, BigDecimal transferred) { + FiscalYear year = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + // An explicit subgroup must never turn the transfer account into an operating expense. + databaseService.withTransaction { Sql sql -> + sql.executeUpdate("update account set account_subgroup = 'FINANCIAL_COSTS' where account_number = '8999'") + } + postSignedTransfer(year, '1930', '3010', earned) + if (transferred != 0G) { + postSignedTransfer(year, '8999', '2099', transferred) + } + ReportDataService reports = new ReportDataService(databaseService) + assertEquals(earned, reports.generate(new ReportSelection(ReportType.INCOME_STATEMENT, year.id)).templateModel.result) + + if (earned != 0G) { + assertYearExport(year, earned, transferred) + } + def result = closingService.closeFiscalYear(year.id) + BigDecimal remaining = earned - transferred + assertEquals(earned, result.netResult) + assertEquals(transferred, result.transferredResult) + assertEquals(remaining, result.remainingResult) + if (remaining == 0G) { + assertNull(result.closingVoucher) + } else { + Voucher closing = voucherService.findVoucher(result.closingVoucher.id) + assertEquals(2, closing.lines.size()) + VoucherLine transfer = lineForAccount(closing, '8999') + assertEquals(remaining, transfer.debitAmount - transfer.creditAmount) + assertEquals(1, closingService.listClosingEntries(year.id).count { entry -> entry.entryType == ClosingService.RESULT_CLOSING }) + } + assertEquals(earned, reports.generate(new ReportSelection(ReportType.INCOME_STATEMENT, year.id)).templateModel.result) + def nextReport = reports.generate(new ReportSelection(ReportType.INCOME_STATEMENT, result.nextFiscalYear.id)) + List rows = nextReport.templateModel.typedRows as List + assertEquals(earned == 0G ? null : earned, rows.find { IncomeStatementRow row -> row.rowType == IncomeStatementRowType.GRAND_TOTAL }.previousYearToDateAmount) + databaseService.withSql { Sql sql -> + assertEquals(0, ((Number) sql.firstRow(''' + select count(*) as total from opening_balance ob join account a on a.id = ob.account_id + where ob.fiscal_year_id = ? and a.account_class in ('INCOME', 'EXPENSE') + ''', [result.nextFiscalYear.id]).get('total')).intValue()) + if (earned != 0G) { + assertEquals(earned, openingBalanceFor(sql, result.nextFiscalYear.id, '2099')) + } + } + assertTrue(auditLogService.validateIntegrity(CompanyService.LEGACY_COMPANY_ID).isEmpty()) + if (earned != 0G) { + assertYearExport(year, earned, earned) + } + } + + @ParameterizedTest + @CsvSource(['8998, true, EXPENSE, DEBIT', '8999, false, EXPENSE, DEBIT', + '8999, true, EQUITY, CREDIT', '8999, true, EXPENSE, CREDIT']) + void previewBlocksInvalidTransferAccountBeforeWritingAnything(String number, boolean active, String accountClass, String side) { + FiscalYear year = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + postSignedTransfer(year, '1930', '3010', 100.00G) + databaseService.withTransaction { Sql sql -> + sql.executeUpdate(''' + update account set account_number = ?, active = ?, account_class = ?, normal_balance_side = ? + where account_number = '8999' + ''', [number, active, accountClass, side]) + } + assertTrue(closingService.previewClosing(year.id).blockingIssues.any { String issue -> issue.contains('8999') }) + assertThrows(IllegalStateException) { closingService.closeFiscalYear(year.id) } + assertFalse(fiscalYearService.findById(year.id).closed) + assertEquals(1, voucherService.listVouchers(CompanyService.LEGACY_COMPANY_ID, year.id).size()) + } + + @Test + void closingSupportsSelectedEquityAccount() { + FiscalYear year = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + databaseService.withTransaction { Sql sql -> + insertAccount(sql, '2019', 'Årets resultat, delägare 1', 'EQUITY', 'CREDIT') + } + postSignedTransfer(year, '1930', '3010', 100.00G) + + def result = closingService.closeFiscalYear(year.id, '2019') + + assertEquals(100.00G, lineForAccount(result.closingVoucher, '2019').creditAmount) + assertNull(lineForAccount(result.closingVoucher, '2099')) + databaseService.withSql { Sql sql -> + assertEquals(100.00G, openingBalanceFor(sql, result.nextFiscalYear.id, '2019')) + } + } + + @ParameterizedTest + @CsvSource(['AKTIEBOLAG, 2099', 'ENSKILD_FIRMA, 2019', 'HANDELSBOLAG_KB, 2019', ', 2099']) + void closingDefaultsToTheCompanyLegalForm(String legalForm, String expectedAccount) { + CompanyService companies = new CompanyService(databaseService) + Company company = companies.findById(CompanyService.LEGACY_COMPANY_ID) + company.legalForm = LegalForm.fromDatabaseValue(legalForm) + companies.save(company) + FiscalYear year = fiscalYearService.createFiscalYear(company.id, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + databaseService.withTransaction { Sql sql -> + insertAccount(sql, '2019', 'Årets resultat, delägare 1', 'EQUITY', 'CREDIT') + } + postSignedTransfer(year, '1930', '3010', 100.00G) + + assertEquals(expectedAccount, closingService.defaultClosingAccount(year.id)) + assertEquals(expectedAccount, closingService.previewClosing(year.id).closingAccountNumber) + String overrideAccount = expectedAccount == '2019' ? '2099' : '2019' + assertEquals(overrideAccount, closingService.previewClosing(year.id, overrideAccount).closingAccountNumber) + + def result = closingService.closeFiscalYear(year.id) + + assertEquals(100.00G, lineForAccount(result.closingVoucher, expectedAccount).creditAmount) + assertNull(lineForAccount(result.closingVoucher, overrideAccount)) + databaseService.withSql { Sql sql -> + assertEquals(100.00G, openingBalanceFor(sql, result.nextFiscalYear.id, expectedAccount)) + } + } + + @Test + void missingLegalFormDefaultAccountBlocksClosingInsteadOfFallingBack() { + CompanyService companies = new CompanyService(databaseService) + Company company = companies.findById(CompanyService.LEGACY_COMPANY_ID) + company.legalForm = LegalForm.ENSKILD_FIRMA + companies.save(company) + FiscalYear year = fiscalYearService.createFiscalYear(company.id, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + postSignedTransfer(year, '1930', '3010', 100.00G) + + def preview = closingService.previewClosing(year.id) + + assertEquals('2019', preview.closingAccountNumber) + assertTrue(preview.blockingIssues.any { String issue -> issue.contains('2019') }) + assertThrows(IllegalStateException) { closingService.closeFiscalYear(year.id) } + def result = closingService.closeFiscalYear(year.id, '2099') + assertEquals(100.00G, lineForAccount(result.closingVoucher, '2099').creditAmount) + } + + @ParameterizedTest + @CsvSource(['1000, 300, 0', '1000, 300, 400', '1000, 300, 700', '1000, 300, 900', + '300, 1000, -400', '300, 1000, -700']) + void previewSeparatesOperatingResultFromPriorTransfers(BigDecimal income, BigDecimal expense, BigDecimal transferred) { + FiscalYear year = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + postSignedTransfer(year, '1930', '3010', income) + postSignedTransfer(year, '4010', '1930', expense) + postSignedTransfer(year, '8999', '2099', transferred) + + def preview = closingService.previewClosing(year.id) + + assertEquals(income, preview.incomeTotal) + assertEquals(expense, preview.expenseTotal) + assertEquals(income - expense, preview.netResult) + assertEquals(transferred, preview.transferredResult) + assertEquals(income - expense - transferred, preview.remainingResult) + assertTrue(preview.blockingIssues.isEmpty()) + } + + @Test + void closingComputesResultFromEntryDirectionWhenClassificationContradictsNormalSide() { + // Regression for PR #141: an income account with a debit normal side must not flip the + // sign of the result; the transfer is derived from the debit/credit direction per entry. + FiscalYear year = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + databaseService.withTransaction { Sql sql -> + insertAccount(sql, '3740', 'Övriga inkomster', 'INCOME', 'DEBIT') + } + postSignedTransfer(year, '1510', '3740', 1000.00G) + + def preview = closingService.previewClosing(year.id) + + assertEquals(1000.00G, preview.incomeTotal) + assertEquals(0.00G, preview.expenseTotal) + assertEquals(1000.00G, preview.netResult) + assertEquals(1000.00G, preview.remainingResult) + assertTrue(preview.warnings.any { String warning -> warning.contains('3740') }) + + def result = closingService.closeFiscalYear(year.id) + + assertEquals(1000.00G, lineForAccount(result.closingVoucher, '8999').debitAmount) + assertEquals(0.00G, lineForAccount(result.closingVoucher, '8999').creditAmount) + assertEquals(1000.00G, lineForAccount(result.closingVoucher, '2099').creditAmount) + databaseService.withSql { Sql sql -> + GroovyRowResult netRow = sql.firstRow(''' + select coalesce(sum(vl.debit_amount - vl.credit_amount), 0) as net + from voucher v + join voucher_line vl on vl.voucher_id = v.id + join account a on a.id = vl.account_id + where v.fiscal_year_id = ? + and v.status in ('ACTIVE', 'CORRECTION') + and a.account_class in ('INCOME', 'EXPENSE') + ''', [year.id]) as GroovyRowResult + assertEquals(0.00G, new BigDecimal(netRow.get('net').toString())) + assertEquals(1000.00G, openingBalanceFor(sql, result.nextFiscalYear.id, '2099')) + } + } + + @Test + void fullyReversedActivityDoesNotExportZeroResultBalances() { + FiscalYear year = fiscalYearService.createFiscalYear(CompanyService.LEGACY_COMPANY_ID, '2026', + LocalDate.of(2026, 1, 1), LocalDate.of(2026, 12, 31)) + seedClosingAccounts() + postSignedTransfer(year, '1930', '3010', 100.00G) + postSignedTransfer(year, '1930', '3010', -100.00G) + + assertYearExport(year, 0.00G, 0.00G) + } + + private void postSignedTransfer(FiscalYear year, String debitAccount, String creditAccount, BigDecimal amount) { + if (amount == 0G) { + return + } + voucherService.createVoucher(year.id, 'A', year.endDate, 'Testtransaktion', [ + new VoucherLine(null, null, 0, null, debitAccount, null, null, amount.max(0.00G), (-amount).max(0.00G)), + new VoucherLine(null, null, 0, null, creditAccount, null, null, (-amount).max(0.00G), amount.max(0.00G)) + ]) + } + + private void assertYearExport(FiscalYear year, BigDecimal earned, BigDecimal transferred) { + CompanyService companies = new CompanyService(databaseService) + companies.save(new Company(CompanyService.LEGACY_COMPANY_ID, 'Test AB', '556677-8899', 'SEK', 'sv-SE', + VatPeriodicity.MONTHLY, true, null, null)) + SieImportExportService sie = new SieImportExportService(databaseService, accountingPeriodService, voucherService, + companies, reportIntegrityService, auditLogService, fiscalYearService) + Path target = tempDir.resolve('closed.sie') + sie.exportFiscalYear(year.id, target) + String content = target.toFile().getText('IBM437') + String sales = content.readLines().find { String line -> line.startsWith('#RES 0 3010 ') } + String transfer = content.readLines().find { String line -> line.startsWith('#RES 0 8999 ') } + if (earned == 0G) { + assertNull(sales) + } else { + assertNotNull(sales) + assertEquals(-earned, new BigDecimal(sales.split(/\s+/)[3])) + } + if (transferred == 0G) { + assertNull(transfer) + } else { + assertNotNull(transfer) + assertEquals(transferred, new BigDecimal(transfer.split(/\s+/)[3])) + } + } + private void seedClosingAccounts() { databaseService.withTransaction { Sql sql -> insertAccount(sql, '1510', 'Kundfordringar', 'ASSET', 'DEBIT') @@ -396,6 +648,7 @@ class ClosingServiceTest { insertAccount(sql, '2099', 'Årets resultat', 'EQUITY', 'CREDIT') insertAccount(sql, '3010', 'Försäljning', 'INCOME', 'CREDIT') insertAccount(sql, '4010', 'Varukostnad', 'EXPENSE', 'DEBIT') + insertAccount(sql, '8999', 'Årets resultat', 'EXPENSE', 'DEBIT') } } diff --git a/app/src/test/groovy/integration/se/alipsa/accounting/service/MultiCompanyIsolationTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/service/MultiCompanyIsolationTest.groovy index 74afb27a..3bdd113b 100644 --- a/app/src/test/groovy/integration/se/alipsa/accounting/service/MultiCompanyIsolationTest.groovy +++ b/app/src/test/groovy/integration/se/alipsa/accounting/service/MultiCompanyIsolationTest.groovy @@ -315,6 +315,7 @@ class MultiCompanyIsolationTest { insertAccount(sql, companyId, '1510', 'Kundfordringar', 'ASSET', 'DEBIT', null) insertAccount(sql, companyId, '1930', 'Företagskonto', 'ASSET', 'DEBIT', null) insertAccount(sql, companyId, '2099', 'Årets resultat', 'EQUITY', 'CREDIT', null) + insertAccount(sql, companyId, '8999', 'Årets resultat', 'EXPENSE', 'DEBIT', null) insertAccount(sql, companyId, '3010', 'Försäljning', 'INCOME', 'CREDIT', null) insertAccount(sql, companyId, '4010', 'Varukostnad', 'EXPENSE', 'DEBIT', null) } diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/service/ReportAccountSupportTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/service/ReportAccountSupportTest.groovy index 81f13969..0cee2686 100644 --- a/app/src/test/groovy/unit/se/alipsa/accounting/service/ReportAccountSupportTest.groovy +++ b/app/src/test/groovy/unit/se/alipsa/accounting/service/ReportAccountSupportTest.groovy @@ -14,17 +14,12 @@ class ReportAccountSupportTest { @Test void shouldExclude8999FromIncomeStatement() { - assertTrue(ReportAccountSupport.shouldExcludeFromIncomeStatement('8999', AccountSubgroup.TAX_AND_RESULT)) + assertTrue(ReportAccountSupport.shouldExcludeFromIncomeStatement('8999')) } @Test void shouldNotExclude8910FromIncomeStatement() { - assertFalse(ReportAccountSupport.shouldExcludeFromIncomeStatement('8910', AccountSubgroup.TAX_AND_RESULT)) - } - - @Test - void shouldNotExclude8999WithOtherSubgroup() { - assertFalse(ReportAccountSupport.shouldExcludeFromIncomeStatement('8999', AccountSubgroup.FINANCIAL_COSTS)) + assertFalse(ReportAccountSupport.shouldExcludeFromIncomeStatement('8910')) } @Test diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/ui/YearEndClosingDialogTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/ui/YearEndClosingDialogTest.groovy new file mode 100644 index 00000000..777bcd5a --- /dev/null +++ b/app/src/test/groovy/unit/se/alipsa/accounting/ui/YearEndClosingDialogTest.groovy @@ -0,0 +1,58 @@ +package se.alipsa.accounting.ui + +import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertFalse + +import org.junit.jupiter.api.Test + +import se.alipsa.accounting.service.YearEndClosingPreview +import se.alipsa.accounting.support.I18n + +import javax.swing.JButton +import javax.swing.JTextField + +class YearEndClosingDialogTest { + + @Test + void summaryDistinguishesAnnualResultFromAnExistingTransfer() { + Locale previousLocale = I18n.instance.locale + Locale locale = Locale.forLanguageTag('sv-SE') + try { + I18n.instance.locale = locale + YearEndClosingPreview preview = new YearEndClosingPreview( + incomeTotal: 1000.00G, expenseTotal: 300.00G, netResult: 700.00G, + transferredResult: 400.00G, remainingResult: 300.00G, resultAccountsWithBalanceCount: 3) + + List lines = YearEndClosingDialog.summaryLines(preview, locale).collect { String line -> + line.replace('\u00a0', ' ') + } + + assertEquals([ + 'Intäkter: 1 000,00', + 'Kostnader: 300,00', + 'Årets resultat: 700,00', + 'Redan överfört (8999): 400,00', + 'Återstår att överföra: 300,00', + 'Resultatkonton med saldo: 3' + ], lines) + } finally { + I18n.instance.locale = previousLocale + } + } + + @Test + void executionUsesPreviewedAccountEvenWhenFieldTextWasEdited() { + JTextField accountField = new JTextField(8) + JButton executeButton = new JButton() + YearEndClosingAccountGuard guard = new YearEndClosingAccountGuard(accountField, executeButton) + guard.previewCompleted('2099') + assertEquals('2099', accountField.text) + // renderPreview re-enables Execute after the previewed account is applied. + executeButton.enabled = true + + accountField.text = '2019' + + assertFalse(executeButton.enabled) + assertEquals('2099', guard.accountForExecution()) + } +} diff --git a/docs/screenshots/pr-141-closing-ab.png b/docs/screenshots/pr-141-closing-ab.png new file mode 100644 index 00000000..e998ee96 Binary files /dev/null and b/docs/screenshots/pr-141-closing-ab.png differ diff --git a/docs/screenshots/pr-141-closing-ef.png b/docs/screenshots/pr-141-closing-ef.png new file mode 100644 index 00000000..438ed307 Binary files /dev/null and b/docs/screenshots/pr-141-closing-ef.png differ diff --git a/docs/screenshots/pr-141-closing-existing-transfer.png b/docs/screenshots/pr-141-closing-existing-transfer.png new file mode 100644 index 00000000..f8f17733 Binary files /dev/null and b/docs/screenshots/pr-141-closing-existing-transfer.png differ diff --git a/docs/screenshots/pr-141-closing-hb-kb.png b/docs/screenshots/pr-141-closing-hb-kb.png new file mode 100644 index 00000000..49b71e1e Binary files /dev/null and b/docs/screenshots/pr-141-closing-hb-kb.png differ diff --git a/docs/screenshots/pr-141-closing-preview-error.png b/docs/screenshots/pr-141-closing-preview-error.png new file mode 100644 index 00000000..92788393 Binary files /dev/null and b/docs/screenshots/pr-141-closing-preview-error.png differ diff --git a/req/issue-130-year-end-closing.md b/req/issue-130-year-end-closing.md new file mode 100644 index 00000000..4c0cfa09 --- /dev/null +++ b/req/issue-130-year-end-closing.md @@ -0,0 +1,57 @@ +# Year-end result transfer — issue 130 + +Related: [GitHub issue 130](https://github.com/Alipsa/accounting/issues/130). + +Closing now posts only the remaining result between 8999 and the selected equity +account. A profit debits 8999 and credits the equity account; a loss reverses those +sides. Existing transfers through 8999 reduce the amount still to transfer. A zero +remaining result produces no closing voucher. The result-closing metadata describes +the actual 8999 transfer rather than individual operating accounts. + +Individual income and expense accounts retain their balances. The income statement +already excludes 8999, including in comparison figures. SIE export now includes +natural-sign `#RES` records for income and expense accounts, including 8999; these +reconcile to the exported vouchers. Only balance-sheet accounts carry forward. +There is no schema migration. + +## Existing closed years: correction plan + +This change applies to future closings. It does not rewrite historical vouchers, +closing entries, opening balances, or audit hashes. Historical corrections require +a separate, reviewed application workflow: + +1. Identify the original closing voucher from closing metadata and inspect its + operating-account reversals. Do not infer a faulty closing from series YE alone. +2. Back up the company and validate audit integrity. Preview the proposed correction, + the restored account balances, and the effects on later years and archived reports. +3. Through domain operations, append a correction voucher referencing and reversing + the faulty closing, then post the proper remaining-result transfer through 8999. + An explicitly authorized reopening workflow is needed for a closed year; direct + SQL edits and hash-chain rebuilding are not acceptable substitutes. +4. Verify the income statement, comparisons, balance sheet, SIE export, and audit + chain. Preserve the original voucher and correction references. Reconcile later + opening balances through audited domain operations only if the equity total changes. +5. Prevent duplicate remediation and retain evidence of the user's approval and reason. + +## Separate equity workflows + +The selectable equity account defaults to 2099 for AB and to 2019 for EF/HB/KB, +in the service, closing dialog, and MCP tools. An unset legal form retains the +2099 fallback. Explicit account selections override the default. New-year transfers +(2099 to 2098 for AB, or 2019/2013/2018 to 2010 for a sole proprietorship) should be +implemented in a separate previewable, audited workflow. Opening balances must +continue to match the preceding year's closing balances; reallocations belong in +new-year vouchers. Later allocations to retained earnings or dividends require +the applicable profit-allocation decision and must not be inferred by year closing. + +## Preview and MCP amounts + +The preview separates operating income and expenses (excluding 8999), the actual +annual result (`net_result`), prior transfers (`transferred_result`), and the amount +still to post (`remaining_result`). Both preview and closing responses use +`result_accounts_with_balance_count` for the count of nonzero result-account balances, +including 8999 when nonzero. The closing response retains the preview figures: `remaining_result` is the amount +posted by that operation. The former `result_account_count` field is removed. +The dialog resolves its default account inside the preview worker and displays errors +without enabling closing. Account 8999 is excluded from the income statement regardless +of its subgroup. SIE result records omit zero balances. diff --git a/skill/accounting-mcp.md b/skill/accounting-mcp.md index 51f63b2a..bd852384 100644 --- a/skill/accounting-mcp.md +++ b/skill/accounting-mcp.md @@ -104,7 +104,7 @@ Only call write tools after the user explicitly confirms the proposed action. 1. Call `list_fiscal_years` and confirm the year is open. 2. Call `preview_year_end`. -3. Show `blocking_issues`, `warnings`, `net_result`, and whether the next fiscal year will be created automatically. +3. Show `blocking_issues`, `warnings`, the year’s result (`net_result`), the amount already transferred via 8999 (`transferred_result`), the remaining transfer (`remaining_result`), and whether the next fiscal year will be created automatically. `income_total` and `expense_total` exclude 8999; `result_accounts_with_balance_count` counts result accounts with nonzero balances. 4. If `ready_to_close` is false or `preview_token` is missing, explain the blockers and do not call `close_fiscal_year`. 5. If `ready_to_close` is true, ask the user to confirm closing the year. 6. Only call `close_fiscal_year` after confirmation, passing the returned `preview_token`.