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..4cdfd78d 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,15 +235,26 @@ 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() } - Map draft = voucherDraftAccess.getVoucherDraft() + Map draft + try { + draft = voucherDraftAccess.getVoucherDraft() + } 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: ['An unexpected error occurred while reading the voucher draft; see the application log.']] + } if (draft == null || draft.isEmpty()) { - return [ok: 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, 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) { @@ -273,7 +288,11 @@ class AccountingMcpTools { } draft.lines = enrichedLines } - voucherDraftAccess.setVoucherDraft(draft) + try { + voucherDraftAccess.setVoucherDraft(draft) + } 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] } @@ -1071,7 +1090,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 75608843..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,17 +140,18 @@ final class McpToolDefinitions { ] ), toolDef('get_active_voucher_draft', - 'Gets the unsaved voucher currently displayed in the desktop application.', + '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', - '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; 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'), 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/UnsavedVoucherDraftException.groovy b/app/src/main/groovy/se/alipsa/accounting/mcp/UnsavedVoucherDraftException.groovy new file mode 100644 index 00000000..cffc8014 --- /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 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/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/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/VoucherDraftEditorAccess.groovy b/app/src/main/groovy/se/alipsa/accounting/ui/VoucherDraftEditorAccess.groovy index 6cce1496..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 @@ -34,6 +35,11 @@ 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 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/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 944034bf..5cbf52b3 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() @@ -190,7 +192,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, @@ -296,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) } @@ -824,6 +827,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 @@ -1009,6 +1014,33 @@ 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() || + 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 && + 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) } + } + + private Map snapshotMcpDraft() { + if (currentVoucher != null) { + VoucherDraftMapper.VoucherDraft draft = navigation.draft() + return VoucherDraftMapper.toDraft(draft.accountingDate, draft.description, draft.seriesCode, draft.lines, + draft.attachmentPath) + } + // Reading must leave the user's active cell editor and its listeners untouched. + Map draft = snapshotDraft() + draft.editing = lineTable.editing + draft + } + private Map snapshotDraft() { String seriesCode = (seriesComboBox.selectedItem as VoucherSeries)?.seriesCode VoucherDraftMapper.toDraft(datePicker.date, descriptionField.text, seriesCode, lineTableModel.toVoucherLines(), @@ -1034,6 +1066,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 @@ -1055,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() { @@ -1064,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 @@ -1088,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/mcp/AccountingMcpToolsTest.groovy b/app/src/test/groovy/integration/se/alipsa/accounting/mcp/AccountingMcpToolsTest.groovy index f567c3da..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 @@ -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,7 @@ 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: []]) - } + assertThrows(IllegalArgumentException) { tools.callTool('set_active_voucher_draft', [description: 'invalid', lines: []]) } boolean noDraft = true tools.setVoucherDraftAccess(new VoucherDraftAccess() { @Override Map getVoucherDraft() { noDraft ? null : [:] } @@ -820,6 +820,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) + 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) } @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..fdaead66 --- /dev/null +++ b/app/src/test/groovy/integration/se/alipsa/accounting/ui/VoucherDraftProtectionTest.groovy @@ -0,0 +1,264 @@ +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.mcp.UnsavedVoucherDraftException +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.JLabel +import javax.swing.JTable +import javax.swing.JTextField +import javax.swing.event.TableModelListener + +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 = descriptionEditor() + 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 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() + 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() + } + } + } + } + + @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 + } + 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) } + assertReplacementRefused() + assertEquals(initialDate.plusDays(1).toString(), panel.mcpVoucherDraftAccess.getVoucherDraft().accounting_date) + onEdt { + picker.date = initialDate + selectSeries(changedSeries) + } + assertReplacementRefused() + assertEquals(changedSeries, panel.mcpVoucherDraftAccess.getVoucherDraft().series_code) + } + + @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) + } + + @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() { + UnsavedVoucherDraftException exception = assertThrows(UnsavedVoucherDraftException) { + panel.mcpVoucherDraftAccess.setVoucherDraft(proposal()) + } + assertTrue(exception.message.contains('replace_unsaved: true')) + assertThrows(UnsavedVoucherDraftException) { + 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/mcp/VoucherDraftToolErrorsTest.groovy b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy new file mode 100644 index 00000000..ffd1ee84 --- /dev/null +++ b/app/src/test/groovy/unit/se/alipsa/accounting/mcp/VoucherDraftToolErrorsTest.groovy @@ -0,0 +1,106 @@ +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 + +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.Level +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) + + @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() { + 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) + handler.close() + } + } + + @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(false, result.has_unsaved_changes) + assertEquals('no_draft', result.error_code) + } + + @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) + 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 { + 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() { } + } +} 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..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 @@ -1,16 +1,51 @@ 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.mcp.UnsavedVoucherDraftException + import java.util.concurrent.atomic.AtomicBoolean 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(UnsavedVoucherDraftException) { access.setVoucherDraft(draft) } + assertFalse(applied.get()) + draft.replace_unsaved = 'true' + assertThrows(UnsavedVoucherDraftException) { 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/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 29c2e1e7..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. + 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`.