From 8dc2e07dab1a9cd1eb0bcf2381660ed69611e77b Mon Sep 17 00:00:00 2001 From: Per Nyfelt Date: Fri, 13 Nov 2026 19:49:42 +0100 Subject: [PATCH 1/5] =?UTF-8?q?Skydda=20osparade=20verifikationer=20fr?= =?UTF-8?q?=C3=A5n=20MCP-=C3=B6verskrivning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../accounting/mcp/AccountingMcpTools.groovy | 10 +- .../accounting/mcp/McpToolDefinitions.groovy | 5 +- .../accounting/mcp/VoucherDraftAccess.groovy | 2 + .../ui/VoucherDraftEditorAccess.groovy | 8 +- .../alipsa/accounting/ui/VoucherPanel.groovy | 27 +++- .../mcp/AccountingMcpToolsTest.groovy | 16 ++- .../ui/VoucherDraftProtectionTest.groovy | 115 ++++++++++++++++++ .../ui/VoucherDraftEditorAccessTest.groovy | 33 +++++ skill/accounting-mcp.md | 2 +- 9 files changed, 207 insertions(+), 11 deletions(-) create mode 100644 app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy 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 84ea6763..ea37fc7f 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy @@ -237,9 +237,9 @@ class AccountingMcpTools { } Map draft = voucherDraftAccess.getVoucherDraft() if (draft == null || draft.isEmpty()) { - return [ok: false, errors: ['No unsaved voucher draft is active.']] + return [ok: false, has_unsaved_changes: false, errors: ['No unsaved voucher draft is active.']] } - [ok: true, saved: false, draft: draft] + [ok: true, saved: false, has_unsaved_changes: true, draft: draft] } private Map setActiveVoucherDraft(Map args) { @@ -273,7 +273,11 @@ class AccountingMcpTools { } draft.lines = enrichedLines } - voucherDraftAccess.setVoucherDraft(draft) + try { + voucherDraftAccess.setVoucherDraft(draft) + } catch (IllegalArgumentException exception) { + return [ok: false, errors: [exception.message]] + } [ok: true, saved: false, awaiting_user_save: true] } 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 75608843..7d7f48ca 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy @@ -140,17 +140,18 @@ final class McpToolDefinitions { ] ), toolDef('get_active_voucher_draft', - 'Gets the unsaved voucher currently displayed in the desktop application.', + 'Gets the unsaved voucher draft, including a draft retained while browsing saved vouchers. Returns has_unsaved_changes; a blank editor with only date/series defaults has no unsaved changes.', [], [:] ), toolDef('set_active_voucher_draft', - 'Replaces the unsaved GUI voucher draft. This never saves; the user must review and press Save in the application. Resolve account numbers through list_accounts before calling this tool. If attachment_path is provided, the file is validated immediately and shown in the draft\'s Attachments tab; it is automatically registered when the user saves the voucher.', + 'Fills the GUI voucher draft. Refuses to overwrite unsaved content unless replace_unsaved is true. This never saves; the user must review and press Save in the application. Resolve account numbers through list_accounts before calling this tool. If attachment_path is provided, the file is validated immediately and shown in the draft\'s Attachments tab; it is automatically registered when the user saves the voucher.', ['accounting_date', 'description', 'lines'], [ accounting_date: strParam('Accounting date in ISO format YYYY-MM-DD'), description: strParam('Voucher description'), series_code: optStrParam('Voucher series code. Defaults to A.'), lines: voucherLinesParam(), + replace_unsaved: optBoolParam('Explicitly allow replacing unsaved editor content. Defaults to false.'), attachment_path: optStrParam('Optional absolute path to a receipt/invoice file. Validated immediately and shown in the draft Attachments tab; registered when the user saves the voucher.') ] ), diff --git a/app/src/main/groovy/se/alipsa/accounting/mcp/VoucherDraftAccess.groovy b/app/src/main/groovy/se/alipsa/accounting/mcp/VoucherDraftAccess.groovy index 295831c7..7ae1b8e0 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/VoucherDraftAccess.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/VoucherDraftAccess.groovy @@ -2,6 +2,8 @@ package se.alipsa.accounting.mcp /** EDT-safe bridge between MCP worker threads and the unsaved voucher editor. */ interface VoucherDraftAccess { + /** Returns an empty map when there is no meaningful unsaved content. */ Map getVoucherDraft() + /** Refuses to discard unsaved content unless draft.replace_unsaved is explicitly true. */ void setVoucherDraft(Map draft) } diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy index 6cce1496..6815f59a 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy @@ -34,6 +34,12 @@ final class VoucherDraftEditorAccess implements VoucherDraftAccess { @Override void setVoucherDraft(Map draft) { VoucherDraftMapper.VoucherDraft voucherDraft = VoucherDraftMapper.fromDraft(draft) - SwingThreading.runOnEdt { draftConsumer.accept(voucherDraft) } + SwingThreading.runOnEdt { + if (unsavedDraftSupplier.get() && draft.get('replace_unsaved') != Boolean.TRUE) { + throw new IllegalArgumentException( + 'The voucher editor has unsaved changes. Save or clear them first, or pass replace_unsaved: true.') + } + draftConsumer.accept(voucherDraft) + } } } diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy index 944034bf..1ba96d67 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy @@ -190,7 +190,7 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste lineTable = new JTable(lineTableModel) registerListenersOnce() buildUi() - mcpVoucherDraftAccess = new VoucherDraftEditorAccess(this::snapshotDraft, { currentVoucher == null }, this::applyDraft) + mcpVoucherDraftAccess = new VoucherDraftEditorAccess(this::snapshotMcpDraft, this::hasUnsavedDraftContent, this::applyDraft) VoucherOperations voucherOperations = new VoucherOperations() { @Override Voucher createVoucher(long fiscalYearId, String seriesCode, LocalDate accountingDate, @@ -1009,6 +1009,28 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste } } + private boolean hasUnsavedDraftContent() { + if (currentVoucher != null) { + VoucherDraftMapper.VoucherDraft draft = navigation.draft() + return draft != null && (hasText(draft.description) || hasText(draft.attachmentPath) || !draft.lines.isEmpty()) + } + // An active cell editor may contain text that has not reached the table model yet. + lineTable.editing || hasText(descriptionField.text) || hasText(pendingAttachmentPath) || + lineTableModel.rows.any { LineEntry row -> isRowFilled(row) } + } + + private Map snapshotMcpDraft() { + if (currentVoucher != null) { + VoucherDraftMapper.VoucherDraft draft = navigation.draft() + return VoucherDraftMapper.toDraft(draft.accountingDate, draft.description, draft.seriesCode, draft.lines, + draft.attachmentPath) + } + if (lineTable.editing && !lineTable.cellEditor.stopCellEditing()) { + throw new IllegalArgumentException('Finish editing the voucher line before reading the draft.') + } + snapshotDraft() + } + private Map snapshotDraft() { String seriesCode = (seriesComboBox.selectedItem as VoucherSeries)?.seriesCode VoucherDraftMapper.toDraft(datePicker.date, descriptionField.text, seriesCode, lineTableModel.toVoucherLines(), @@ -1034,6 +1056,9 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste AttachmentMetadata attachmentPreview = voucherDraft.attachmentPath ? attachmentService.previewAttachment(Path.of(voucherDraft.attachmentPath)) : null + if (lineTable.editing) { + lineTable.cellEditor.cancelCellEditing() + } showBlankVoucher() datePicker.date = voucherDraft.accountingDate descriptionField.text = voucherDraft.description 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 f567c3da..b6fd35a8 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 @@ -22,6 +22,8 @@ import se.alipsa.accounting.service.VatService import se.alipsa.accounting.service.VoucherService import se.alipsa.accounting.support.AppPaths import se.alipsa.accounting.support.I18n +import se.alipsa.accounting.ui.VoucherDraftEditorAccess +import se.alipsa.accounting.ui.VoucherDraftMapper import java.nio.file.Files import java.nio.file.Path @@ -809,9 +811,8 @@ class AccountingMcpToolsTest { List> appliedLines = (List>) appliedDraft[0].lines assertEquals('Företagskonto', appliedLines.first().account_name) assertEquals('Leverantörsskulder', appliedLines.last().account_name) - assertThrows(IllegalArgumentException) { - tools.callTool('set_active_voucher_draft', [description: 'invalid', lines: []]) - } + assertEquals([ok: false, errors: ['accounting_date must be an ISO date (YYYY-MM-DD).']], + tools.callTool('set_active_voucher_draft', [description: 'invalid', lines: []])) boolean noDraft = true tools.setVoucherDraftAccess(new VoucherDraftAccess() { @Override Map getVoucherDraft() { noDraft ? null : [:] } @@ -820,6 +821,15 @@ class AccountingMcpToolsTest { Map missingDraft = tools.callTool('get_active_voucher_draft', [:]) assertFalse((boolean) missingDraft.get('ok')) assertEquals(['No unsaved voucher draft is active.'], missingDraft.get('errors')) + assertEquals(false, missingDraft.has_unsaved_changes) + tools.setVoucherDraftAccess(new VoucherDraftEditorAccess({ existingDraft }, { true }, + { VoucherDraftMapper.VoucherDraft draft -> appliedDraft[0] = [description: draft.description] })) + Map rejected = tools.callTool('set_active_voucher_draft', replacement) + assertEquals(false, rejected.ok) + assertTrue(rejected.errors.toString().contains('replace_unsaved: true')) + replacement.replace_unsaved = true + assertEquals(true, tools.callTool('set_active_voucher_draft', replacement).ok) + assertEquals('Prepared by AI', appliedDraft[0].description) } @Test diff --git a/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy new file mode 100644 index 00000000..726fab3b --- /dev/null +++ b/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy @@ -0,0 +1,115 @@ +package se.alipsa.accounting.ui + +import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertFalse +import static org.junit.jupiter.api.Assertions.assertThrows +import static org.junit.jupiter.api.Assertions.assertTrue + +import org.junit.jupiter.api.Test + +import se.alipsa.accounting.domain.VoucherLine +import se.alipsa.accounting.support.I18n + +import java.awt.Container +import java.nio.file.Files +import java.time.LocalDate + +import javax.swing.JButton +import javax.swing.JTable +import javax.swing.JTextField + +final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { + + @Test + void blankEditorAcceptsDraftButAnotherDraftRequiresExplicitReplacement() { + assertEquals([:], panel.mcpVoucherDraftAccess.getVoucherDraft()) + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal()) + Map before = panel.mcpVoucherDraftAccess.getVoucherDraft() + + assertReplacementRefused() + assertEquals(before, panel.mcpVoucherDraftAccess.getVoucherDraft()) + + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal([description: 'Replacement', replace_unsaved: true])) + assertEquals('Replacement', panel.mcpVoucherDraftAccess.getVoucherDraft().description) + } + + @Test + void descriptionOnlyAndIncompleteLineContentAreProtected() { + JTextField description = findComponent(panel, JTextField) { JTextField field -> field.columns == 30 } + onEdt { description.text = 'Manual work' } + assertReplacementRefused() + assertEquals('Manual work', onEdt { description.text }) + + onEdt { + description.text = '' + panel.lineTableModel.rows[0].description = 'Unfinished line' + } + assertReplacementRefused() + assertEquals('Unfinished line', onEdt { panel.lineTableModel.rows[0].description }) + } + + @Test + void activeCellEditorIsProtectedBeforeItsTextReachesTheModel() { + JTable table = findComponent(panel, JTable) { JTable candidate -> candidate.model == panel.lineTableModel } + onEdt { + assertTrue(table.editCellAt(0, 4)) + ((JTextField) table.editorComponent).text = 'Still typing' + } + assertReplacementRefused() + assertEquals('Still typing', onEdt { ((JTextField) table.editorComponent).text }) + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal([replace_unsaved: true])) + assertFalse(onEdt { table.editing }) + assertEquals([], panel.mcpVoucherDraftAccess.getVoucherDraft().lines) + } + + @Test + void attachmentOnlyDraftIsProtected() { + def receipt = tempDir.resolve('receipt.txt') + Files.writeString(receipt, 'Receipt') + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal([description: '', attachment_path: receipt.toString()])) + assertReplacementRefused() + assertEquals(receipt.toString(), panel.mcpVoucherDraftAccess.getVoucherDraft().attachment_path) + } + + @Test + void rememberedDraftIsProtectedWhileBrowsingReadOnlySavedVoucher() { + voucherService.createVoucher(fiscalYear.id, 'A', LocalDate.of(2030, 3, 15), 'Saved voucher', + [voucherLine('1510', 'Kundfordringar', 'Saved line', 100.00G, 0.00G), + voucherLine('3010', 'Försäljning', 'Saved line', 0.00G, 100.00G)]) + panel.dispose() + panel = buildPanel() + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal()) + onEdt { clickButtonWithTooltip(panel, I18n.instance.getString('voucherPanel.button.prev')) } + + assertEquals('AI proposal', panel.mcpVoucherDraftAccess.getVoucherDraft().description) + assertReplacementRefused() + onEdt { clickButtonWithTooltip(panel, I18n.instance.getString('voucherPanel.button.next')) } + assertEquals('AI proposal', panel.mcpVoucherDraftAccess.getVoucherDraft().description) + } + + private void assertReplacementRefused() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException) { + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal()) + } + assertTrue(exception.message.contains('replace_unsaved: true')) + assertThrows(IllegalArgumentException) { + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal([replace_unsaved: false])) + } + } + + private static Map proposal(Map overrides = [:]) { + Map draft = [accounting_date: '2030-03-15', description: 'AI proposal', lines: []] + draft.putAll(overrides) + draft + } + + private static VoucherLine voucherLine(String accountNumber, String accountName, String description, + BigDecimal debit, BigDecimal credit) { + new VoucherLine(null, null, 0, null, accountNumber, accountName, description, debit, credit) + } + + private static void clickButtonWithTooltip(Container root, String tooltip) { + JButton button = findComponent(root, JButton) { JButton candidate -> candidate.toolTipText == tooltip } + button.doClick() + } +} diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy index 7243ae0d..44c61c23 100644 --- a/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy +++ b/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy @@ -1,6 +1,8 @@ package se.alipsa.accounting.ui import static org.junit.jupiter.api.Assertions.assertEquals +import static org.junit.jupiter.api.Assertions.assertFalse +import static org.junit.jupiter.api.Assertions.assertThrows import static org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test @@ -11,6 +13,37 @@ import javax.swing.SwingUtilities final class VoucherDraftEditorAccessTest { + @Test + void checksForUnsavedContentAndAppliesReplacementTogetherOnTheEventDispatchThread() { + AtomicBoolean dirty = new AtomicBoolean(true) + AtomicBoolean applied = new AtomicBoolean(false) + Map existingDraft = [description: 'Manual work'] + VoucherDraftEditorAccess access = new VoucherDraftEditorAccess( + { existingDraft }, + { assertTrue(SwingUtilities.isEventDispatchThread()); dirty.get() }, + { VoucherDraftMapper.VoucherDraft ignored -> + assertTrue(SwingUtilities.isEventDispatchThread()) + applied.set(true) + } + ) + Map draft = [accounting_date: '2030-03-15', description: 'AI proposal', lines: []] + + assertThrows(IllegalArgumentException) { access.setVoucherDraft(draft) } + assertFalse(applied.get()) + draft.replace_unsaved = 'true' + assertThrows(IllegalArgumentException) { access.setVoucherDraft(draft) } + draft.replace_unsaved = true + access.setVoucherDraft(draft) + assertTrue(applied.get()) + + draft.remove('replace_unsaved') + dirty.set(false) + applied.set(false) + assertEquals([:], access.getVoucherDraft()) + access.setVoucherDraft(draft) + assertTrue(applied.get()) + } + @Test void readsDraftStateAndSnapshotTogetherOnTheEventDispatchThread() { AtomicBoolean stateReadOnEdt = new AtomicBoolean(false) diff --git a/skill/accounting-mcp.md b/skill/accounting-mcp.md index 29c2e1e7..8c057dae 100644 --- a/skill/accounting-mcp.md +++ b/skill/accounting-mcp.md @@ -69,7 +69,7 @@ Only call write tools after the user explicitly confirms the proposed action. Summarize the voucher to the user: date, description, and lines with account numbers and amounts. Call `preview_voucher` and show resolved account names plus any errors or warnings. Do not proceed if `ok` is false. 5. Place the draft for review. - Ask the user whether to prepare the proposed voucher. Call `set_active_voucher_draft`, then tell the user to review and save it in the desktop application. Never claim it was posted or saved. + Ask the user whether to prepare the proposed voucher. Call `set_active_voucher_draft`, then tell the user to review and save it in the desktop application. Never claim it was posted or saved. The tool refuses to replace unsaved content (including a draft retained while browsing saved vouchers). Ask the user to save or clear it first; pass `replace_unsaved: true` only when the user intends to discard it. `get_active_voucher_draft` returns `has_unsaved_changes`; date/series defaults alone do not count as unsaved content. 6. Correct posted vouchers through corrections. Direct edits and deletes are not exposed. If a posted voucher is wrong, explain that the permitted path is `create_correction_voucher`. From 60472b6899f77ae30a8cf8db88a1a683ed7fc22e Mon Sep 17 00:00:00 2001 From: Per Nyfelt Date: Fri, 13 Nov 2026 20:06:33 +0100 Subject: [PATCH 2/5] =?UTF-8?q?Bevara=20p=C3=A5g=C3=A5ende=20cellredigerin?= =?UTF-8?q?g=20vid=20l=C3=A4sning=20av=20MCP-utkast?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../accounting/mcp/AccountingMcpTools.groovy | 16 +++-- .../accounting/mcp/McpToolDefinitions.groovy | 4 +- .../mcp/UnsavedVoucherDraftException.groovy | 9 +++ .../ui/VoucherDraftEditorAccess.groovy | 4 +- .../accounting/ui/VoucherDraftMapper.groovy | 10 ++- .../alipsa/accounting/ui/VoucherPanel.groovy | 21 +++++-- .../mcp/AccountingMcpToolsTest.groovy | 5 +- .../ui/VoucherDraftProtectionTest.groovy | 62 +++++++++++++++++++ .../mcp/VoucherDraftToolErrorsTest.groovy | 55 ++++++++++++++++ .../ui/VoucherDraftMapperTest.groovy | 9 +++ skill/accounting-mcp.md | 2 +- 11 files changed, 175 insertions(+), 22 deletions(-) create mode 100644 app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy create mode 100644 app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy 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 ea37fc7f..e265eca1 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy @@ -235,11 +235,17 @@ class AccountingMcpTools { if (voucherDraftAccess == null) { return voucherEditorUnavailable() } - Map draft = voucherDraftAccess.getVoucherDraft() + Map draft + try { + draft = voucherDraftAccess.getVoucherDraft() + } catch (IllegalArgumentException ignored) { + return [ok: false, has_unsaved_changes: null, error_code: 'draft_unavailable', + errors: ['The voucher draft could not be read. Finish editing it in the application and try again.']] + } if (draft == null || draft.isEmpty()) { return [ok: false, has_unsaved_changes: false, errors: ['No unsaved voucher draft is active.']] } - [ok: true, saved: false, has_unsaved_changes: true, draft: draft] + [ok: true, saved: false, has_unsaved_changes: true, editing: draft.get('editing') == true, draft: draft] } private Map setActiveVoucherDraft(Map args) { @@ -275,8 +281,8 @@ class AccountingMcpTools { } try { voucherDraftAccess.setVoucherDraft(draft) - } catch (IllegalArgumentException exception) { - return [ok: false, errors: [exception.message]] + } catch (UnsavedVoucherDraftException exception) { + return [ok: false, has_unsaved_changes: true, error_code: 'unsaved_changes', errors: [exception.message]] } [ok: true, saved: false, awaiting_user_save: true] } @@ -1075,7 +1081,7 @@ class AccountingMcpTools { } private static Map voucherEditorUnavailable() { - [ok: false, errors: ['Voucher editor is not available.']] + [ok: false, has_unsaved_changes: null, error_code: 'editor_unavailable', errors: ['Voucher editor is not available.']] } private static String yearEndPreviewToken(long fiscalYearId, String closingAccount) { 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 7d7f48ca..154984cf 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/McpToolDefinitions.groovy @@ -140,11 +140,11 @@ final class McpToolDefinitions { ] ), toolDef('get_active_voucher_draft', - 'Gets the unsaved voucher draft, including a draft retained while browsing saved vouchers. Returns has_unsaved_changes; a blank editor with only date/series defaults has no unsaved changes.', + 'Reads the unsaved voucher draft without changing the editor, including a draft retained while browsing saved vouchers. Returns has_unsaved_changes (null if unavailable). When editing is true, draft lines contain committed model values only; in-progress cell text is not included. Initial date/series defaults alone are blank; deliberate changes count as unsaved content.', [], [:] ), toolDef('set_active_voucher_draft', - 'Fills the GUI voucher draft. Refuses to overwrite unsaved content unless replace_unsaved is true. This never saves; the user must review and press Save in the application. Resolve account numbers through list_accounts before calling this tool. If attachment_path is provided, the file is validated immediately and shown in the draft\'s Attachments tab; it is automatically registered when the user saves the voucher.', + 'Fills the GUI voucher draft. Refuses to overwrite unsaved content unless replace_unsaved is true; refusal returns error_code: unsaved_changes and has_unsaved_changes: true. This never saves; the user must review and press Save in the application. Resolve account numbers through list_accounts before calling this tool. If attachment_path is provided, the file is validated immediately and shown in the draft\'s Attachments tab; it is automatically registered when the user saves the voucher.', ['accounting_date', 'description', 'lines'], [ accounting_date: strParam('Accounting date in ISO format YYYY-MM-DD'), diff --git a/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy b/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy new file mode 100644 index 00000000..09f55ae3 --- /dev/null +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy @@ -0,0 +1,9 @@ +package se.alipsa.accounting.mcp + +/** A state conflict, distinct from invalid MCP arguments. */ +final class UnsavedVoucherDraftException extends IllegalArgumentException { + + UnsavedVoucherDraftException() { + super('The voucher editor has unsaved changes. Save or clear them first, or pass replace_unsaved: true.') + } +} diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy index 6815f59a..8f637ebb 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy @@ -1,5 +1,6 @@ package se.alipsa.accounting.ui +import se.alipsa.accounting.mcp.UnsavedVoucherDraftException import se.alipsa.accounting.mcp.VoucherDraftAccess import java.util.function.Consumer @@ -36,8 +37,7 @@ final class VoucherDraftEditorAccess implements VoucherDraftAccess { VoucherDraftMapper.VoucherDraft voucherDraft = VoucherDraftMapper.fromDraft(draft) SwingThreading.runOnEdt { if (unsavedDraftSupplier.get() && draft.get('replace_unsaved') != Boolean.TRUE) { - throw new IllegalArgumentException( - 'The voucher editor has unsaved changes. Save or clear them first, or pass replace_unsaved: true.') + throw new UnsavedVoucherDraftException() } draftConsumer.accept(voucherDraft) } diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftMapper.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftMapper.groovy index 028c4634..32cd34f8 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftMapper.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftMapper.groovy @@ -36,7 +36,7 @@ final class VoucherDraftMapper { } Map line = (Map) value lines << new VoucherLine(null, null, index, null, line.account_number as String, line.account_name as String, - line.description as String, decimal(line.debit), decimal(line.credit)) + line.description as String, decimal(line.debit, 'debit', index), decimal(line.credit, 'credit', index)) } LocalDate accountingDate try { @@ -48,8 +48,12 @@ final class VoucherDraftMapper { (draft.get('attachment_path') as String)?.trim() ?: null) } - private static BigDecimal decimal(Object value) { - value == null || value.toString().trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(value.toString()) + private static BigDecimal decimal(Object value, String field, int index) { + try { + value == null || value.toString().trim().isEmpty() ? BigDecimal.ZERO : new BigDecimal(value.toString()) + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("Line ${index + 1}: ${field} must be a valid amount.", exception) + } } static final class VoucherDraft { diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy index 1ba96d67..492db2c3 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy @@ -156,6 +156,8 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste private final JTable auditLogTable = new JTable(auditLogTableModel) private Voucher currentVoucher + private LocalDate blankDraftDate + private String blankDraftSeriesCode private String pendingAttachmentPath private AttachmentMetadata pendingAttachmentPreview private final VoucherNavigation navigation = new VoucherNavigation() @@ -824,6 +826,8 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste datePicker.date = defaultDate() ensureDefaultSeriesForNewVoucher() VoucherSeries selectedSeries = seriesComboBox.selectedItem as VoucherSeries + blankDraftDate = datePicker.date + blankDraftSeriesCode = selectedSeries?.seriesCode String nextNumber = selectedSeries != null ? previewNextVoucherNumber(selectedSeries.seriesCode) : '' voucherNumberLabel.text = nextNumber unsavedLabel.visible = true @@ -1012,10 +1016,15 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste private boolean hasUnsavedDraftContent() { if (currentVoucher != null) { VoucherDraftMapper.VoucherDraft draft = navigation.draft() - return draft != null && (hasText(draft.description) || hasText(draft.attachmentPath) || !draft.lines.isEmpty()) + return draft != null && (hasText(draft.description) || hasText(draft.attachmentPath) || !draft.lines.isEmpty() || + draft.accountingDate != blankDraftDate || draft.seriesCode != blankDraftSeriesCode) } // An active cell editor may contain text that has not reached the table model yet. - lineTable.editing || hasText(descriptionField.text) || hasText(pendingAttachmentPath) || + boolean editorHasText = lineTable.editing && lineTable.editorComponent instanceof javax.swing.text.JTextComponent && + hasText(((javax.swing.text.JTextComponent) lineTable.editorComponent).text) + editorHasText || datePicker.date != blankDraftDate || + (seriesComboBox.selectedItem as VoucherSeries)?.seriesCode != blankDraftSeriesCode || + hasText(descriptionField.text) || hasText(pendingAttachmentPath) || lineTableModel.rows.any { LineEntry row -> isRowFilled(row) } } @@ -1025,10 +1034,10 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste return VoucherDraftMapper.toDraft(draft.accountingDate, draft.description, draft.seriesCode, draft.lines, draft.attachmentPath) } - if (lineTable.editing && !lineTable.cellEditor.stopCellEditing()) { - throw new IllegalArgumentException('Finish editing the voucher line before reading the draft.') - } - snapshotDraft() + // Reading must leave the user's active cell editor and its listeners untouched. + Map draft = snapshotDraft() + draft.editing = lineTable.editing + draft } private Map snapshotDraft() { 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 b6fd35a8..3e2f4eb7 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 @@ -811,8 +811,7 @@ class AccountingMcpToolsTest { List> appliedLines = (List>) appliedDraft[0].lines assertEquals('Företagskonto', appliedLines.first().account_name) assertEquals('Leverantörsskulder', appliedLines.last().account_name) - assertEquals([ok: false, errors: ['accounting_date must be an ISO date (YYYY-MM-DD).']], - tools.callTool('set_active_voucher_draft', [description: 'invalid', lines: []])) + assertThrows(IllegalArgumentException) { tools.callTool('set_active_voucher_draft', [description: 'invalid', lines: []]) } boolean noDraft = true tools.setVoucherDraftAccess(new VoucherDraftAccess() { @Override Map getVoucherDraft() { noDraft ? null : [:] } @@ -826,7 +825,7 @@ class AccountingMcpToolsTest { { VoucherDraftMapper.VoucherDraft draft -> appliedDraft[0] = [description: draft.description] })) Map rejected = tools.callTool('set_active_voucher_draft', replacement) assertEquals(false, rejected.ok) - assertTrue(rejected.errors.toString().contains('replace_unsaved: true')) + assertEquals('unsaved_changes', rejected.error_code) replacement.replace_unsaved = true assertEquals(true, tools.callTool('set_active_voucher_draft', replacement).ok) assertEquals('Prepared by AI', appliedDraft[0].description) diff --git a/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy index 726fab3b..6bf887fc 100644 --- a/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy +++ b/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy @@ -2,19 +2,24 @@ package se.alipsa.accounting.ui import static org.junit.jupiter.api.Assertions.assertEquals import static org.junit.jupiter.api.Assertions.assertFalse +import static org.junit.jupiter.api.Assertions.assertSame import static org.junit.jupiter.api.Assertions.assertThrows import static org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import se.alipsa.accounting.domain.VoucherLine +import se.alipsa.accounting.domain.VoucherSeries import se.alipsa.accounting.support.I18n +import se.alipsa.datepicker.DatePicker import java.awt.Container import java.nio.file.Files import java.time.LocalDate +import java.util.concurrent.atomic.AtomicInteger import javax.swing.JButton +import javax.swing.JComboBox import javax.swing.JTable import javax.swing.JTextField @@ -62,6 +67,63 @@ final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { assertEquals([], panel.mcpVoucherDraftAccess.getVoucherDraft().lines) } + @Test + void readingAnActiveCellLeavesTextModelAndListenersUntouched() { + JTable table = findComponent(panel, JTable) { JTable candidate -> candidate.model == panel.lineTableModel } + for (int column : [0, 2]) { + onEdt { + assertTrue(table.editCellAt(0, column)) + ((JTextField) table.editorComponent).text = column == 0 ? '19' : '12,' + } + def editor = onEdt { table.editorComponent } + AtomicInteger events = new AtomicInteger() + panel.lineTableModel.addTableModelListener { events.incrementAndGet() } + int rowCount = onEdt { table.rowCount } + Map draft = panel.mcpVoucherDraftAccess.getVoucherDraft() + assertEquals(true, draft.editing) + assertEquals([], draft.lines) + assertTrue(onEdt { table.editing }) + assertSame(editor, onEdt { table.editorComponent }) + assertEquals(column == 0 ? '19' : '12,', onEdt { ((JTextField) table.editorComponent).text }) + assertEquals(rowCount, onEdt { table.rowCount }) + assertEquals(0, events.get()) + onEdt { table.cellEditor.cancelCellEditing() } + } + } + + @Test + void emptyActiveCellDoesNotCountAsUnsavedContentOrGetCommittedByReading() { + JTable table = findComponent(panel, JTable) { JTable candidate -> candidate.model == panel.lineTableModel } + onEdt { assertTrue(table.editCellAt(0, 4)) } + assertEquals([:], panel.mcpVoucherDraftAccess.getVoucherDraft()) + assertTrue(onEdt { table.editing }) + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal()) + assertFalse(onEdt { table.editing }) + assertEquals('AI proposal', panel.mcpVoucherDraftAccess.getVoucherDraft().description) + } + + @Test + void deliberateDateAndSeriesChangesAreProtectedButInitialDefaultsAreBlank() { + voucherService.ensureSeries(fiscalYear.id, 'B') + panel.dispose() + panel = buildPanel() + DatePicker picker = findComponent(panel, DatePicker) { true } + JComboBox series = findComponent(panel, JComboBox) { JComboBox candidate -> + candidate.itemCount > 0 && candidate.getItemAt(0) instanceof VoucherSeries + } + LocalDate initialDate = onEdt { picker.date } + assertEquals([:], panel.mcpVoucherDraftAccess.getVoucherDraft()) + onEdt { picker.date = initialDate.plusDays(1) } + assertReplacementRefused() + assertEquals(initialDate.plusDays(1).toString(), panel.mcpVoucherDraftAccess.getVoucherDraft().accounting_date) + onEdt { + picker.date = initialDate + series.selectedIndex = 1 + } + assertReplacementRefused() + assertEquals('B', panel.mcpVoucherDraftAccess.getVoucherDraft().series_code) + } + @Test void attachmentOnlyDraftIsProtected() { def receipt = tempDir.resolve('receipt.txt') diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy new file mode 100644 index 00000000..b6509cd2 --- /dev/null +++ b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy @@ -0,0 +1,55 @@ +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.assertNull +import static org.junit.jupiter.api.Assertions.assertThrows +import static org.junit.jupiter.api.Assertions.assertTrue + +import org.junit.jupiter.api.Test + +import se.alipsa.accounting.ui.VoucherDraftEditorAccess +import se.alipsa.accounting.ui.VoucherDraftMapper + +final class VoucherDraftToolErrorsTest { + + private final AccountingMcpTools tools = new AccountingMcpTools(null, null, null, null, null, null, null, null, null) + + @Test + void unavailableEditorReportsUnknownUnsavedState() { + Map result = tools.callTool('get_active_voucher_draft', [:]) + assertEquals(false, result.ok) + assertEquals('editor_unavailable', result.error_code) + assertTrue(result.containsKey('has_unsaved_changes')) + assertNull(result.has_unsaved_changes) + } + + @Test + void readFailureIsAToolResultWithoutRawExceptionText() { + tools.setVoucherDraftAccess(new VoucherDraftAccess() { + @Override Map getVoucherDraft() { throw new IllegalArgumentException('Internal detail') } + @Override void setVoucherDraft(Map ignored) { } + }) + Map result = tools.callTool('get_active_voucher_draft', [:]) + assertEquals(false, result.ok) + assertEquals('draft_unavailable', result.error_code) + assertFalse(result.errors.toString().contains('Internal detail')) + } + + @Test + void stateConflictsHaveStructuredFieldsWhileBadArgumentsStillThrow() { + Map draft = [description: 'Manual work', lines: [], editing: true] + tools.setVoucherDraftAccess(new VoucherDraftEditorAccess({ draft }, { true }, + { VoucherDraftMapper.VoucherDraft ignored -> })) + Map result = tools.callTool('set_active_voucher_draft', + [accounting_date: '2030-03-15', description: 'AI proposal', lines: []]) + assertEquals(false, result.ok) + assertEquals('unsaved_changes', result.error_code) + assertEquals(true, result.has_unsaved_changes) + assertEquals(true, tools.callTool('get_active_voucher_draft', [:]).editing) + + assertThrows(IllegalArgumentException) { + tools.callTool('set_active_voucher_draft', [accounting_date: 'invalid', lines: []]) + } + } +} diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftMapperTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftMapperTest.groovy index df147a51..801cf980 100644 --- a/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftMapperTest.groovy +++ b/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftMapperTest.groovy @@ -37,6 +37,15 @@ final class VoucherDraftMapperTest { assertEquals('/tmp/receipt.jpg', draft.attachmentPath) } + @Test + void invalidAmountsHaveActionableErrorsInsteadOfJdkMessages() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException) { + VoucherDraftMapper.fromDraft([accounting_date: '2030-03-15', + lines: [[account_number: '1930', debit: 'abc']]]) + } + assertEquals('Line 1: debit must be a valid amount.', exception.message) + } + @Test void rejectsMalformedDraftValuesWithActionableErrors() { IllegalArgumentException missingLines = assertThrows(IllegalArgumentException) { diff --git a/skill/accounting-mcp.md b/skill/accounting-mcp.md index 8c057dae..51f63b2a 100644 --- a/skill/accounting-mcp.md +++ b/skill/accounting-mcp.md @@ -69,7 +69,7 @@ Only call write tools after the user explicitly confirms the proposed action. Summarize the voucher to the user: date, description, and lines with account numbers and amounts. Call `preview_voucher` and show resolved account names plus any errors or warnings. Do not proceed if `ok` is false. 5. Place the draft for review. - Ask the user whether to prepare the proposed voucher. Call `set_active_voucher_draft`, then tell the user to review and save it in the desktop application. Never claim it was posted or saved. The tool refuses to replace unsaved content (including a draft retained while browsing saved vouchers). Ask the user to save or clear it first; pass `replace_unsaved: true` only when the user intends to discard it. `get_active_voucher_draft` returns `has_unsaved_changes`; date/series defaults alone do not count as unsaved content. + Ask the user whether to prepare the proposed voucher. Call `set_active_voucher_draft`, then tell the user to review and save it in the desktop application. Never claim it was posted or saved. The tool refuses to replace unsaved content (including a draft retained while browsing saved vouchers) with `error_code: unsaved_changes` and `has_unsaved_changes: true`. Ask the user to save or clear it first; pass `replace_unsaved: true` only when the user intends to discard it. `get_active_voucher_draft` returns `has_unsaved_changes` (null if unavailable). Initial date/series defaults alone are blank, but deliberate changes are protected. Reading leaves active cell editors untouched; when `editing: true`, the returned lines contain committed model values and exclude in-progress cell text. Invalid draft parameters retain their JSON-RPC invalid-parameters error behavior. 6. Correct posted vouchers through corrections. Direct edits and deletes are not exposed. If a posted voucher is wrong, explain that the permitted path is `create_correction_voucher`. From 299cc078c137c0a9210e62f3393c2f39b8dd6662 Mon Sep 17 00:00:00 2001 From: Per Nyfelt Date: Fri, 13 Nov 2026 20:34:34 +0100 Subject: [PATCH 3/5] =?UTF-8?q?Bevara=20utkastets=20basv=C3=A4rden=20vid?= =?UTF-8?q?=20navigering=20mellan=20serier?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../accounting/mcp/AccountingMcpTools.groovy | 15 ++- .../mcp/UnsavedVoucherDraftException.groovy | 2 +- .../accounting/ui/SwingThreading.groovy | 6 +- .../accounting/ui/VoucherNavigation.groovy | 19 ++- .../alipsa/accounting/ui/VoucherPanel.groovy | 11 +- .../ui/VoucherDraftProtectionTest.groovy | 119 +++++++++++++++--- .../mcp/VoucherDraftToolErrorsTest.groovy | 53 ++++++-- .../ui/VoucherDraftEditorAccessTest.groovy | 6 +- 8 files changed, 194 insertions(+), 37 deletions(-) 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 e265eca1..8b6c85ff 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy @@ -42,6 +42,8 @@ import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.util.concurrent.ConcurrentHashMap +import java.util.logging.Level +import java.util.logging.Logger /** * Registry and implementation entrypoint for MCP tools, covering both read-only @@ -49,6 +51,8 @@ import java.util.concurrent.ConcurrentHashMap */ class AccountingMcpTools { + private static final Logger log = Logger.getLogger(AccountingMcpTools.name) + private final CompanyService companyService private final FiscalYearService fiscalYearService private final AccountService accountService @@ -231,6 +235,8 @@ class AccountingMcpTools { [ok: false, error: 'No active company or fiscal year is selected.'] } + // This parameterless read boundary logs unexpected EDT failures and returns a tool error. + @SuppressWarnings('CatchRuntimeException') private Map getActiveVoucherDraft() { if (voucherDraftAccess == null) { return voucherEditorUnavailable() @@ -238,14 +244,17 @@ class AccountingMcpTools { Map draft try { draft = voucherDraftAccess.getVoucherDraft() - } catch (IllegalArgumentException ignored) { + } catch (RuntimeException exception) { + log.log(Level.WARNING, 'Could not read the voucher draft.', exception) return [ok: false, has_unsaved_changes: null, error_code: 'draft_unavailable', errors: ['The voucher draft could not be read. Finish editing it in the application and try again.']] } if (draft == null || draft.isEmpty()) { - return [ok: false, has_unsaved_changes: false, errors: ['No unsaved voucher draft is active.']] + return [ok: false, has_unsaved_changes: false, error_code: 'no_draft', errors: ['No unsaved voucher draft is active.']] } - [ok: true, saved: false, has_unsaved_changes: true, editing: draft.get('editing') == true, draft: draft] + Map payload = new LinkedHashMap<>(draft) + boolean editing = payload.remove('editing') == true + [ok: true, saved: false, has_unsaved_changes: true, editing: editing, draft: payload] } private Map setActiveVoucherDraft(Map args) { diff --git a/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy b/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy index 09f55ae3..cffc8014 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy @@ -1,7 +1,7 @@ package se.alipsa.accounting.mcp /** A state conflict, distinct from invalid MCP arguments. */ -final class UnsavedVoucherDraftException extends IllegalArgumentException { +final class UnsavedVoucherDraftException extends IllegalStateException { UnsavedVoucherDraftException() { super('The voucher editor has unsaved changes. Save or clear them first, or pass replace_unsaved: true.') diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/SwingThreading.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/SwingThreading.groovy index b9c73c68..9e32d981 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/SwingThreading.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/SwingThreading.groovy @@ -2,7 +2,7 @@ package se.alipsa.accounting.ui import javax.swing.SwingUtilities -/** Runs UI mutations on the Event Dispatch Thread while preserving validation errors. */ +/** Runs actions on the Event Dispatch Thread while preserving runtime exception types. */ final class SwingThreading { static void runOnEdt(Closure action) { @@ -14,8 +14,8 @@ final class SwingThreading { SwingUtilities.invokeAndWait(action as Runnable) } catch (java.lang.reflect.InvocationTargetException exception) { Throwable cause = exception.cause - if (cause instanceof IllegalArgumentException) { - throw (IllegalArgumentException) cause + if (cause instanceof RuntimeException) { + throw (RuntimeException) cause } throw new IllegalStateException(cause?.message ?: exception.message, cause) } diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherNavigation.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherNavigation.groovy index 9342656b..e04cb93c 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherNavigation.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherNavigation.groovy @@ -2,6 +2,7 @@ package se.alipsa.accounting.ui import se.alipsa.accounting.domain.Voucher +import java.time.LocalDate import java.util.function.Consumer /** Keeps voucher navigation state separate from the editor's Swing controls. */ @@ -10,11 +11,13 @@ final class VoucherNavigation { private List vouchers = [] private int currentIndex = -1 private VoucherDraftMapper.VoucherDraft draft + private LocalDate draftBaselineDate + private String draftBaselineSeriesCode void reset(List values) { vouchers = values currentIndex = -1 - draft = null + clearDraft() } List getVouchers() { @@ -25,14 +28,26 @@ final class VoucherNavigation { currentIndex < 0 } - void rememberDraft(VoucherDraftMapper.VoucherDraft value) { + void rememberDraft(VoucherDraftMapper.VoucherDraft value, LocalDate baselineDate, String baselineSeriesCode) { if (isOnDraft()) { draft = value + draftBaselineDate = baselineDate + draftBaselineSeriesCode = baselineSeriesCode } } void clearDraft() { draft = null + draftBaselineDate = null + draftBaselineSeriesCode = null + } + + LocalDate getDraftBaselineDate() { + draftBaselineDate + } + + String getDraftBaselineSeriesCode() { + draftBaselineSeriesCode } void showDraft() { diff --git a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy index 492db2c3..5cbf52b3 100644 --- a/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy @@ -298,6 +298,7 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste } private void addDescriptionHeaderField(JPanel panel, GridBagConstraints constraints) { + descriptionCaptionLabel.labelFor = descriptionField constraints.gridx++ panel.add(descriptionCaptionLabel, constraints) descriptionField.addActionListener { moveCursorToCell(0, 0) } @@ -1017,7 +1018,7 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste if (currentVoucher != null) { VoucherDraftMapper.VoucherDraft draft = navigation.draft() return draft != null && (hasText(draft.description) || hasText(draft.attachmentPath) || !draft.lines.isEmpty() || - draft.accountingDate != blankDraftDate || draft.seriesCode != blankDraftSeriesCode) + draft.accountingDate != navigation.draftBaselineDate || draft.seriesCode != navigation.draftBaselineSeriesCode) } // An active cell editor may contain text that has not reached the table model yet. boolean editorHasText = lineTable.editing && lineTable.editorComponent instanceof javax.swing.text.JTextComponent && @@ -1089,7 +1090,7 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste if (lineTable.editing) { lineTable.cellEditor.stopCellEditing() } - navigation.rememberDraft(VoucherDraftMapper.fromDraft(snapshotDraft())) + navigation.rememberDraft(VoucherDraftMapper.fromDraft(snapshotDraft()), blankDraftDate, blankDraftSeriesCode) } private void restoreNavigationDraft() { @@ -1098,8 +1099,12 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste showEmptyVoucher() return } + LocalDate baselineDate = navigation.draftBaselineDate + String baselineSeriesCode = navigation.draftBaselineSeriesCode try { applyDraft(draft) + blankDraftDate = baselineDate + blankDraftSeriesCode = baselineSeriesCode } catch (IllegalArgumentException exception) { // This draft was populated by snapshotDraft() moments earlier in the same fiscal year, so // its series and date should both resolve - the date was already accepted by the picker @@ -1122,7 +1127,7 @@ final class VoucherPanel extends JPanel implements PropertyChangeListener, Liste */ @PackageScope void rememberDraftForTest(VoucherDraftMapper.VoucherDraft draft) { - navigation.rememberDraft(draft) + navigation.rememberDraft(draft, blankDraftDate, blankDraftSeriesCode) } /** Lets tests simulate exactly what createNewSeries() does once NewVoucherSeriesDialog diff --git a/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy index 6bf887fc..fdaead66 100644 --- a/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy +++ b/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test import se.alipsa.accounting.domain.VoucherLine import se.alipsa.accounting.domain.VoucherSeries +import se.alipsa.accounting.mcp.UnsavedVoucherDraftException import se.alipsa.accounting.support.I18n import se.alipsa.datepicker.DatePicker @@ -20,8 +21,10 @@ import java.util.concurrent.atomic.AtomicInteger import javax.swing.JButton import javax.swing.JComboBox +import javax.swing.JLabel import javax.swing.JTable import javax.swing.JTextField +import javax.swing.event.TableModelListener final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { @@ -40,7 +43,7 @@ final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { @Test void descriptionOnlyAndIncompleteLineContentAreProtected() { - JTextField description = findComponent(panel, JTextField) { JTextField field -> field.columns == 30 } + JTextField description = descriptionEditor() onEdt { description.text = 'Manual work' } assertReplacementRefused() assertEquals('Manual work', onEdt { description.text }) @@ -77,17 +80,24 @@ final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { } def editor = onEdt { table.editorComponent } AtomicInteger events = new AtomicInteger() - panel.lineTableModel.addTableModelListener { events.incrementAndGet() } - int rowCount = onEdt { table.rowCount } - Map draft = panel.mcpVoucherDraftAccess.getVoucherDraft() - assertEquals(true, draft.editing) - assertEquals([], draft.lines) - assertTrue(onEdt { table.editing }) - assertSame(editor, onEdt { table.editorComponent }) - assertEquals(column == 0 ? '19' : '12,', onEdt { ((JTextField) table.editorComponent).text }) - assertEquals(rowCount, onEdt { table.rowCount }) - assertEquals(0, events.get()) - onEdt { table.cellEditor.cancelCellEditing() } + TableModelListener listener = { events.incrementAndGet() } as TableModelListener + onEdt { panel.lineTableModel.addTableModelListener(listener) } + try { + int rowCount = onEdt { table.rowCount } + Map draft = panel.mcpVoucherDraftAccess.getVoucherDraft() + assertEquals(true, draft.editing) + assertEquals([], draft.lines) + assertTrue(onEdt { table.editing }) + assertSame(editor, onEdt { table.editorComponent }) + assertEquals(column == 0 ? '19' : '12,', onEdt { ((JTextField) table.editorComponent).text }) + assertEquals(rowCount, onEdt { table.rowCount }) + assertEquals(0, events.get()) + } finally { + onEdt { + panel.lineTableModel.removeTableModelListener(listener) + table.cellEditor.cancelCellEditing() + } + } } } @@ -111,6 +121,7 @@ final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { JComboBox series = findComponent(panel, JComboBox) { JComboBox candidate -> candidate.itemCount > 0 && candidate.getItemAt(0) instanceof VoucherSeries } + String changedSeries = onEdt { (series.selectedItem as VoucherSeries).seriesCode == 'A' ? 'B' : 'A' } LocalDate initialDate = onEdt { picker.date } assertEquals([:], panel.mcpVoucherDraftAccess.getVoucherDraft()) onEdt { picker.date = initialDate.plusDays(1) } @@ -118,10 +129,10 @@ final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { assertEquals(initialDate.plusDays(1).toString(), panel.mcpVoucherDraftAccess.getVoucherDraft().accounting_date) onEdt { picker.date = initialDate - series.selectedIndex = 1 + selectSeries(changedSeries) } assertReplacementRefused() - assertEquals('B', panel.mcpVoucherDraftAccess.getVoucherDraft().series_code) + assertEquals(changedSeries, panel.mcpVoucherDraftAccess.getVoucherDraft().series_code) } @Test @@ -149,12 +160,88 @@ final class VoucherDraftProtectionTest extends VoucherPanelTestSupport { assertEquals('AI proposal', panel.mcpVoucherDraftAccess.getVoucherDraft().description) } + @Test + void blankDraftStaysBlankAcrossBrowsingAnotherSeries() { + prepareCrossSeriesVoucher() + assertEquals([:], panel.mcpVoucherDraftAccess.getVoucherDraft()) + browse('prev') + assertEquals([:], panel.mcpVoucherDraftAccess.getVoucherDraft()) + browse('next') + assertEquals([:], panel.mcpVoucherDraftAccess.getVoucherDraft()) + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal()) + assertEquals('AI proposal', panel.mcpVoucherDraftAccess.getVoucherDraft().description) + } + + @Test + void deliberateSeriesChoiceRemainsProtectedWhileBrowsingAndAfterRepeatedReturns() { + String savedSeries = prepareCrossSeriesVoucher() + onEdt { selectSeries(savedSeries) } + 2.times { + assertReplacementRefused() + browse('prev') + assertReplacementRefused() + assertEquals(savedSeries, panel.mcpVoucherDraftAccess.getVoucherDraft().series_code) + browse('next') + assertReplacementRefused() + assertEquals(savedSeries, panel.mcpVoucherDraftAccess.getVoucherDraft().series_code) + } + } + + @Test + void deliberateDateRemainsProtectedWhileBrowsingAndAfterReturning() { + prepareCrossSeriesVoucher() + DatePicker picker = findComponent(panel, DatePicker) { true } + LocalDate changedDate = onEdt { picker.date.plusDays(1) } + onEdt { picker.date = changedDate } + browse('prev') + assertReplacementRefused() + assertEquals(changedDate.toString(), panel.mcpVoucherDraftAccess.getVoucherDraft().accounting_date) + browse('next') + assertReplacementRefused() + assertEquals(changedDate.toString(), panel.mcpVoucherDraftAccess.getVoucherDraft().accounting_date) + } + + private String prepareCrossSeriesVoucher() { + voucherService.ensureSeries(fiscalYear.id, 'B') + onEdt { panel.applyVoucherSortOrderPreference() } + JComboBox series = seriesCombo() + String otherSeries = onEdt { (series.selectedItem as VoucherSeries).seriesCode == 'A' ? 'B' : 'A' } + voucherService.createVoucher(fiscalYear.id, otherSeries, LocalDate.of(2030, 3, 15), 'Other series', + [voucherLine('1510', 'Kundfordringar', 'Saved line', 100.00G, 0.00G), + voucherLine('3010', 'Försäljning', 'Saved line', 0.00G, 100.00G)]) + onEdt { panel.applyVoucherSortOrderPreference() } + otherSeries + } + + private void browse(String direction) { + onEdt { clickButtonWithTooltip(panel, I18n.instance.getString('voucherPanel.button.' + direction)) } + } + + private JComboBox seriesCombo() { + findComponent(panel, JComboBox) { JComboBox candidate -> + candidate.itemCount > 0 && candidate.getItemAt(0) instanceof VoucherSeries + } + } + + private void selectSeries(String code) { + JComboBox series = seriesCombo() + series.selectedItem = (0.. series.getItemAt(index) } + .find { Object item -> (item as VoucherSeries).seriesCode == code } + } + + private JTextField descriptionEditor() { + JLabel label = findComponent(panel, JLabel) { JLabel candidate -> + candidate.text == I18n.instance.getString('voucherPanel.label.description') + } + label.labelFor as JTextField + } + private void assertReplacementRefused() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException) { + UnsavedVoucherDraftException exception = assertThrows(UnsavedVoucherDraftException) { panel.mcpVoucherDraftAccess.setVoucherDraft(proposal()) } assertTrue(exception.message.contains('replace_unsaved: true')) - assertThrows(IllegalArgumentException) { + assertThrows(UnsavedVoucherDraftException) { panel.mcpVoucherDraftAccess.setVoucherDraft(proposal([replace_unsaved: false])) } } diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy index b6509cd2..844a3188 100644 --- a/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy +++ b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy @@ -3,6 +3,7 @@ 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.assertNull +import static org.junit.jupiter.api.Assertions.assertSame import static org.junit.jupiter.api.Assertions.assertThrows import static org.junit.jupiter.api.Assertions.assertTrue @@ -11,6 +12,10 @@ import org.junit.jupiter.api.Test import se.alipsa.accounting.ui.VoucherDraftEditorAccess import se.alipsa.accounting.ui.VoucherDraftMapper +import java.util.logging.Handler +import java.util.logging.LogRecord +import java.util.logging.Logger + final class VoucherDraftToolErrorsTest { private final AccountingMcpTools tools = new AccountingMcpTools(null, null, null, null, null, null, null, null, null) @@ -26,14 +31,33 @@ final class VoucherDraftToolErrorsTest { @Test void readFailureIsAToolResultWithoutRawExceptionText() { - tools.setVoucherDraftAccess(new VoucherDraftAccess() { - @Override Map getVoucherDraft() { throw new IllegalArgumentException('Internal detail') } - @Override void setVoucherDraft(Map ignored) { } - }) + NullPointerException failure = new NullPointerException('Internal detail') + tools.setVoucherDraftAccess(new VoucherDraftEditorAccess({ throw failure }, { true }, + { VoucherDraftMapper.VoucherDraft ignored -> })) + List records = [] + Handler handler = new RecordingHandler(records) + Logger logger = Logger.getLogger(AccountingMcpTools.name) + logger.addHandler(handler) + try { + Map result = tools.callTool('get_active_voucher_draft', [:]) + assertEquals(false, result.ok) + assertEquals('draft_unavailable', result.error_code) + assertFalse(result.errors.toString().contains('Internal detail')) + assertSame(failure, records.last().thrown) + } finally { + logger.removeHandler(handler) + } + } + + @Test + void absentDraftHasAStableErrorCode() { + Map emptyDraft = [:] + tools.setVoucherDraftAccess(new VoucherDraftEditorAccess({ emptyDraft }, { false }, + { VoucherDraftMapper.VoucherDraft ignored -> })) Map result = tools.callTool('get_active_voucher_draft', [:]) assertEquals(false, result.ok) - assertEquals('draft_unavailable', result.error_code) - assertFalse(result.errors.toString().contains('Internal detail')) + assertEquals(false, result.has_unsaved_changes) + assertEquals('no_draft', result.error_code) } @Test @@ -46,10 +70,25 @@ final class VoucherDraftToolErrorsTest { assertEquals(false, result.ok) assertEquals('unsaved_changes', result.error_code) assertEquals(true, result.has_unsaved_changes) - assertEquals(true, tools.callTool('get_active_voucher_draft', [:]).editing) + Map readResult = tools.callTool('get_active_voucher_draft', [:]) + assertEquals(true, readResult.editing) + assertFalse(((Map) readResult.draft).containsKey('editing')) + assertEquals(true, draft.editing) assertThrows(IllegalArgumentException) { tools.callTool('set_active_voucher_draft', [accounting_date: 'invalid', lines: []]) } } + + private static final class RecordingHandler extends Handler implements AutoCloseable { + private final List records + + RecordingHandler(List records) { + this.records = records + } + + @Override void publish(LogRecord record) { records.add(record) } + @Override void flush() { } + @Override void close() { } + } } diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy index 44c61c23..b05ac53d 100644 --- a/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy +++ b/app/src/test/groovy/unit/se/alipsa/accounting/ui/VoucherDraftEditorAccessTest.groovy @@ -7,6 +7,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test +import se.alipsa.accounting.mcp.UnsavedVoucherDraftException + import java.util.concurrent.atomic.AtomicBoolean import javax.swing.SwingUtilities @@ -28,10 +30,10 @@ final class VoucherDraftEditorAccessTest { ) Map draft = [accounting_date: '2030-03-15', description: 'AI proposal', lines: []] - assertThrows(IllegalArgumentException) { access.setVoucherDraft(draft) } + assertThrows(UnsavedVoucherDraftException) { access.setVoucherDraft(draft) } assertFalse(applied.get()) draft.replace_unsaved = 'true' - assertThrows(IllegalArgumentException) { access.setVoucherDraft(draft) } + assertThrows(UnsavedVoucherDraftException) { access.setVoucherDraft(draft) } draft.replace_unsaved = true access.setVoucherDraft(draft) assertTrue(applied.get()) From 2ce8390054248a808ded07c92ea74e7b1c98eaae Mon Sep 17 00:00:00 2001 From: Per Nyfelt Date: Fri, 13 Nov 2026 20:46:14 +0100 Subject: [PATCH 4/5] =?UTF-8?q?F=C3=B6rtydliga=20l=C3=A4sfel=20och=20f?= =?UTF-8?q?=C3=B6renkla=20loggtest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../accounting/mcp/AccountingMcpTools.groovy | 2 +- .../mcp/VoucherDraftToolErrorsTest.groovy | 21 ++++++++----------- 2 files changed, 10 insertions(+), 13 deletions(-) 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 8b6c85ff..4cdfd78d 100644 --- a/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy +++ b/app/src/main/groovy/se/alipsa/accounting/mcp/AccountingMcpTools.groovy @@ -247,7 +247,7 @@ class AccountingMcpTools { } catch (RuntimeException exception) { log.log(Level.WARNING, 'Could not read the voucher draft.', exception) return [ok: false, has_unsaved_changes: null, error_code: 'draft_unavailable', - errors: ['The voucher draft could not be read. Finish editing it in the application and try again.']] + errors: ['An unexpected error occurred while reading the voucher draft; see the application log.']] } if (draft == null || draft.isEmpty()) { return [ok: false, has_unsaved_changes: false, error_code: 'no_draft', errors: ['No unsaved voucher draft is active.']] diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy index 844a3188..6fb30c21 100644 --- a/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy +++ b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy @@ -12,9 +12,11 @@ import org.junit.jupiter.api.Test import se.alipsa.accounting.ui.VoucherDraftEditorAccess import se.alipsa.accounting.ui.VoucherDraftMapper +import java.util.logging.Formatter import java.util.logging.Handler import java.util.logging.LogRecord import java.util.logging.Logger +import java.util.logging.StreamHandler final class VoucherDraftToolErrorsTest { @@ -35,7 +37,12 @@ final class VoucherDraftToolErrorsTest { tools.setVoucherDraftAccess(new VoucherDraftEditorAccess({ throw failure }, { true }, { VoucherDraftMapper.VoucherDraft ignored -> })) List records = [] - Handler handler = new RecordingHandler(records) + Handler handler = new StreamHandler(OutputStream.nullOutputStream(), new Formatter() { + @Override String format(LogRecord record) { + records.add(record) + '' + } + }) Logger logger = Logger.getLogger(AccountingMcpTools.name) logger.addHandler(handler) try { @@ -46,6 +53,7 @@ final class VoucherDraftToolErrorsTest { assertSame(failure, records.last().thrown) } finally { logger.removeHandler(handler) + handler.close() } } @@ -80,15 +88,4 @@ final class VoucherDraftToolErrorsTest { } } - private static final class RecordingHandler extends Handler implements AutoCloseable { - private final List records - - RecordingHandler(List records) { - this.records = records - } - - @Override void publish(LogRecord record) { records.add(record) } - @Override void flush() { } - @Override void close() { } - } } From 406c0388845a3f6edb368b5e2531155f22184007 Mon Sep 17 00:00:00 2001 From: Per Nyfelt Date: Fri, 13 Nov 2026 21:13:53 +0100 Subject: [PATCH 5/5] =?UTF-8?q?F=C3=B6renkla=20loggf=C3=A5ngst=20med=20en?= =?UTF-8?q?=20tydlig=20testhandler?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mcp/VoucherDraftToolErrorsTest.groovy | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy index 6fb30c21..ffd1ee84 100644 --- a/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy +++ b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy @@ -12,11 +12,10 @@ import org.junit.jupiter.api.Test import se.alipsa.accounting.ui.VoucherDraftEditorAccess import se.alipsa.accounting.ui.VoucherDraftMapper -import java.util.logging.Formatter import java.util.logging.Handler +import java.util.logging.Level import java.util.logging.LogRecord import java.util.logging.Logger -import java.util.logging.StreamHandler final class VoucherDraftToolErrorsTest { @@ -37,12 +36,7 @@ final class VoucherDraftToolErrorsTest { tools.setVoucherDraftAccess(new VoucherDraftEditorAccess({ throw failure }, { true }, { VoucherDraftMapper.VoucherDraft ignored -> })) List records = [] - Handler handler = new StreamHandler(OutputStream.nullOutputStream(), new Formatter() { - @Override String format(LogRecord record) { - records.add(record) - '' - } - }) + Handler handler = new RecordingHandler(records) Logger logger = Logger.getLogger(AccountingMcpTools.name) logger.addHandler(handler) try { @@ -88,4 +82,25 @@ final class VoucherDraftToolErrorsTest { } } + private static final class RecordingHandler extends Handler { + private final List records + + RecordingHandler(List records) { + this.records = records + level = Level.ALL + } + + @Override + void publish(LogRecord record) { + if (isLoggable(record)) { + records.add(record) + } + } + + @Override void flush() { } + + // Handler requires close() without implementing Closeable or AutoCloseable. + @SuppressWarnings('CloseWithoutCloseable') + @Override void close() { } + } }