Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,17 @@ 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
* and write tools (see McpOperationCoordinator.WRITE_TOOLS for the write set).
*/
class AccountingMcpTools {

private static final Logger log = Logger.getLogger(AccountingMcpTools.name)

private final CompanyService companyService
private final FiscalYearService fiscalYearService
private final AccountService accountService
Expand Down Expand Up @@ -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<String, Object> getActiveVoucherDraft() {
if (voucherDraftAccess == null) {
return voucherEditorUnavailable()
}
Map<String, Object> draft = voucherDraftAccess.getVoucherDraft()
Map<String, Object> 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<String, Object> payload = new LinkedHashMap<>(draft)
boolean editing = payload.remove('editing') == true
[ok: true, saved: false, has_unsaved_changes: true, editing: editing, draft: payload]
}

private Map<String, Object> setActiveVoucherDraft(Map<String, Object> args) {
Expand Down Expand Up @@ -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]
}

Expand Down Expand Up @@ -1071,7 +1090,7 @@ class AccountingMcpTools {
}

private static Map<String, Object> 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.')
]
),
Expand Down
Original file line number Diff line number Diff line change
@@ -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.')
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Object> getVoucherDraft()
/** Refuses to discard unsaved content unless draft.replace_unsaved is explicitly true. */
void setVoucherDraft(Map<String, Object> draft)
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -34,6 +35,11 @@ final class VoucherDraftEditorAccess implements VoucherDraftAccess {
@Override
void setVoucherDraft(Map<String, Object> 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)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -10,11 +11,13 @@ final class VoucherNavigation {
private List<Voucher> vouchers = []
private int currentIndex = -1
private VoucherDraftMapper.VoucherDraft draft
private LocalDate draftBaselineDate
private String draftBaselineSeriesCode

void reset(List<Voucher> values) {
vouchers = values
currentIndex = -1
draft = null
clearDraft()
}

List<Voucher> getVouchers() {
Expand All @@ -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() {
Expand Down
45 changes: 42 additions & 3 deletions app/src/main/groovy/se/alipsa/accounting/ui/VoucherPanel.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) }
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<String, Object> 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<String, Object> draft = snapshotDraft()
draft.editing = lineTable.editing
draft
}

private Map<String, Object> snapshotDraft() {
String seriesCode = (seriesComboBox.selectedItem as VoucherSeries)?.seriesCode
VoucherDraftMapper.toDraft(datePicker.date, descriptionField.text, seriesCode, lineTableModel.toVoucherLines(),
Expand All @@ -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
Expand All @@ -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() {
Expand All @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -809,9 +811,7 @@ class AccountingMcpToolsTest {
List<Map<String, Object>> appliedLines = (List<Map<String, Object>>) 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<String, Object> getVoucherDraft() { noDraft ? null : [:] }
Expand All @@ -820,6 +820,15 @@ class AccountingMcpToolsTest {
Map<String, Object> 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<String, Object> 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
Expand Down
Loading
Loading