323 lines
14 KiB
JavaScript
323 lines
14 KiB
JavaScript
/**
|
|
* Global state for every loaded statement result - a list of documents
|
|
* (each the full server response plus its own PocketBase record id,
|
|
* owning project id, balance-input text, and flagged-row set) rather
|
|
* than a single one, so multiple files from one upload batch (or
|
|
* restored/filtered from a client project) can coexist and be browsed
|
|
* via activeIndex. pbId is what documentsService.updateDocument/
|
|
* moveToProject target; `project` is purely a local mirror of the
|
|
* PocketBase record's own field, for ProjectSidebar.vue's "Move to
|
|
* project" control to know (and show) which project a document is
|
|
* currently in without a refetch. Kept as one cohesive array of mostly-
|
|
* server-shaped objects rather than over-normalized, same discipline
|
|
* the old single-document shape had.
|
|
*/
|
|
import { defineStore } from 'pinia'
|
|
import { parseNum } from '../services/formatService'
|
|
import { effectiveBalance } from '../services/extractionService'
|
|
|
|
/**
|
|
* Flagged transaction indexes for a given result - every check's own
|
|
* mismatches/issues list carries {index, ...} entries for the specific
|
|
* rows it flagged. A plain function, not a store method, so it can
|
|
* compute flags for ANY document (the one just added, not only
|
|
* whichever happens to be active) - addDocument needs this for a
|
|
* document that ISN'T becoming active (see its own comment).
|
|
*/
|
|
function computeFlags(result) {
|
|
const flagged = new Set()
|
|
for (const check of result?.checks || []) {
|
|
for (const item of check.mismatches || check.issues || []) {
|
|
if (item.index !== undefined) flagged.add(item.index)
|
|
}
|
|
}
|
|
return flagged
|
|
}
|
|
|
|
export const useExtractionStore = defineStore('extraction', {
|
|
state: () => ({
|
|
documents: [],
|
|
activeIndex: 0,
|
|
errorMessage: '',
|
|
// Opening/closing balance text typed BEFORE any document exists yet
|
|
// (no activeDocument to hold it) - submitted with every file in the
|
|
// next batch (ExtractorView reads these directly), and seeded onto
|
|
// each new document's OWN openingBalanceInput/closingBalanceInput as
|
|
// it's added, so post-extraction recheck naturally starts from what
|
|
// was typed instead of blank. Once at least one document exists, the
|
|
// balance fields in TransactionsTable.vue read/write the ACTIVE
|
|
// document's own fields instead of these - see
|
|
// effectiveOpeningBalance/setOpeningBalanceInput below. Known,
|
|
// accepted gap: staging a SECOND batch while earlier documents are
|
|
// still loaded won't route through these pending fields again (the
|
|
// visible inputs are already showing the active document's own
|
|
// field by then) - not something the current ask requires.
|
|
pendingOpeningBalance: '',
|
|
pendingClosingBalance: '',
|
|
// Batch-progress fields live here, not in a composable-local ref -
|
|
// ephemeral, never itself written to PocketBase (only `documents`'
|
|
// own fields are, via documentsService), and being store state (not
|
|
// composable-local) is what lets TransactionsTable's Download button
|
|
// react to isBatchProcessing without a prop from a sibling component.
|
|
isBatchProcessing: false,
|
|
batchTotal: 0,
|
|
batchCurrentIndex: 0,
|
|
batchCurrentFileName: '',
|
|
}),
|
|
getters: {
|
|
activeDocument(state) {
|
|
return state.documents[state.activeIndex] ?? null
|
|
},
|
|
/** The active document's full server response, or null if none loaded yet. */
|
|
currentResult(state) {
|
|
return state.documents[state.activeIndex]?.result ?? null
|
|
},
|
|
/** The active document's localStorage key. */
|
|
currentDocKey(state) {
|
|
return state.documents[state.activeIndex]?.docKey ?? null
|
|
},
|
|
/** The active document's flagged-row indexes. */
|
|
flaggedIndexes(state) {
|
|
return state.documents[state.activeIndex]?.flaggedIndexes ?? new Set()
|
|
},
|
|
/** The active document's typed opening balance, or its own auto-detected figure if blank. */
|
|
effectiveOpeningBalance(state) {
|
|
const doc = state.documents[state.activeIndex]
|
|
return effectiveBalance(parseNum(doc?.openingBalanceInput), doc?.result?.opening_balance)
|
|
},
|
|
/** The active document's typed closing balance, or its own auto-detected figure if blank. */
|
|
effectiveClosingBalance(state) {
|
|
const doc = state.documents[state.activeIndex]
|
|
return effectiveBalance(parseNum(doc?.closingBalanceInput), doc?.result?.closing_balance)
|
|
},
|
|
/** Whatever the opening-balance field should currently show - the active document's own typed text, or the pre-extraction pending text if no document exists yet. */
|
|
openingBalanceInputDisplay(state) {
|
|
const doc = state.documents[state.activeIndex]
|
|
return doc ? doc.openingBalanceInput : state.pendingOpeningBalance
|
|
},
|
|
/** Same as openingBalanceInputDisplay, for the closing balance field. */
|
|
closingBalanceInputDisplay(state) {
|
|
const doc = state.documents[state.activeIndex]
|
|
return doc ? doc.closingBalanceInput : state.pendingClosingBalance
|
|
},
|
|
},
|
|
actions: {
|
|
/**
|
|
* Appends a freshly-extracted (or restored) document. Only moves
|
|
* activeIndex to it when the list was empty beforehand - the very
|
|
* first result has to become visible (there's nothing else on
|
|
* screen yet), but every document after that leaves activeIndex
|
|
* alone, so a later file finishing mid-batch never yanks the user
|
|
* away from whatever they're currently reviewing or editing. Flags
|
|
* are computed directly here (not via recomputeFlags(), which only
|
|
* ever targets the ACTIVE document) since a document added while
|
|
* focus stays elsewhere would otherwise never get its own flags
|
|
* computed at all - nothing re-triggers it later on prev/next either.
|
|
*/
|
|
addDocument({ pbId, docKey, fileName, project, previewUrl, isImage, result, openingBalanceInput, closingBalanceInput }) {
|
|
const wasEmpty = this.documents.length === 0
|
|
this.documents.push({
|
|
pbId, docKey, fileName, project, previewUrl, isImage, result,
|
|
flaggedIndexes: computeFlags(result),
|
|
openingBalanceInput: openingBalanceInput || '',
|
|
closingBalanceInput: closingBalanceInput || '',
|
|
})
|
|
if (wasEmpty) this.activeIndex = 0
|
|
},
|
|
|
|
startBatch(total) {
|
|
this.isBatchProcessing = true
|
|
this.batchTotal = total
|
|
this.batchCurrentIndex = 0
|
|
this.batchCurrentFileName = ''
|
|
},
|
|
advanceBatch(index, fileName) {
|
|
this.batchCurrentIndex = index
|
|
this.batchCurrentFileName = fileName
|
|
},
|
|
endBatch() {
|
|
this.isBatchProcessing = false
|
|
},
|
|
|
|
setActiveIndex(i) {
|
|
if (!this.documents.length) return
|
|
this.activeIndex = Math.max(0, Math.min(i, this.documents.length - 1))
|
|
},
|
|
next() {
|
|
this.setActiveIndex(this.activeIndex + 1)
|
|
},
|
|
prev() {
|
|
this.setActiveIndex(this.activeIndex - 1)
|
|
},
|
|
|
|
/** Writes to the active document's own field, or the pre-extraction pending field if no document exists yet. */
|
|
setOpeningBalanceInput(value) {
|
|
const doc = this.activeDocument
|
|
if (doc) doc.openingBalanceInput = value
|
|
else this.pendingOpeningBalance = value
|
|
},
|
|
setClosingBalanceInput(value) {
|
|
const doc = this.activeDocument
|
|
if (doc) doc.closingBalanceInput = value
|
|
else this.pendingClosingBalance = value
|
|
},
|
|
|
|
/**
|
|
* Updates just the status/checks/suggestions portion of the ACTIVE
|
|
* document after a recheck - mirrors the server's own recheck
|
|
* response shape {status, checks, suggestions}. suggestions is
|
|
* re-applied every time (not just set once after a suggested fix is
|
|
* accepted) so it stays in sync with whatever the CURRENT data
|
|
* actually needs - a stale suggestion a manual edit already resolved
|
|
* a different way disappears on its own next recheck, same as a
|
|
* stale flag would.
|
|
*/
|
|
applyCheckResults(checkResult) {
|
|
const doc = this.activeDocument
|
|
if (!doc) return
|
|
doc.result.status = checkResult.status
|
|
doc.result.checks = checkResult.checks
|
|
doc.result.suggestions = checkResult.suggestions ?? []
|
|
this.recomputeFlags()
|
|
},
|
|
|
|
/** Rebuilds the active document's flaggedIndexes from its current checks. */
|
|
recomputeFlags() {
|
|
const doc = this.activeDocument
|
|
if (!doc) return
|
|
doc.flaggedIndexes = computeFlags(doc.result)
|
|
},
|
|
|
|
/** Applies a saved row edit's fields to the transaction at idx, in the active document. */
|
|
saveRowEdit(idx, fields) {
|
|
const doc = this.activeDocument
|
|
if (!doc) return
|
|
Object.assign(doc.result.transactions[idx], fields)
|
|
},
|
|
|
|
// ── Structural row edits (review screen R.4) ──────────────────────
|
|
// Each one mutates currentResult.transactions only - TransactionRow.vue
|
|
// is the one place that calls these, always followed by the same
|
|
// persist+recheck round trip saveRowEdit's own callers already use
|
|
// (not duplicated per action - see TransactionRow.vue's own
|
|
// persistAndRecheck()). /api/recheck already accepts a transactions
|
|
// array of any length, so none of this needed a new backend endpoint.
|
|
|
|
/** "Flip debit/credit" - negates a row's own amount in place. */
|
|
flipTransactionSign(index) {
|
|
const doc = this.activeDocument
|
|
const t = doc?.result.transactions[index]
|
|
if (t && t.amount !== null && t.amount !== undefined) t.amount = Math.round(-t.amount * 100) / 100
|
|
},
|
|
|
|
/** Removes transaction `index` outright - e.g. an accidental duplicate row. */
|
|
deleteTransaction(index) {
|
|
const doc = this.activeDocument
|
|
if (!doc) return
|
|
doc.result.transactions.splice(index, 1)
|
|
this.recomputeFlags()
|
|
},
|
|
|
|
/**
|
|
* Inserts a new row right after `index` - blank (for a row the
|
|
* extractor genuinely missed, the user fills in what the source
|
|
* shows) or seeded from `template` (TransactionRow.vue's own "Split
|
|
* this row" passes the CURRENT row's own values, so splitting one
|
|
* printed line into two starts from a duplicate the user then
|
|
* divides manually, rather than guessing how to split the amount
|
|
* itself - the spec's own "never silently correct" rule applies
|
|
* here too, this doesn't invent a split point).
|
|
*/
|
|
insertTransactionAfter(index, template = {}) {
|
|
const doc = this.activeDocument
|
|
if (!doc) return
|
|
const txns = doc.result.transactions
|
|
txns.splice(index + 1, 0, {
|
|
date: template.date ?? txns[index]?.date ?? '',
|
|
description: template.description ?? '',
|
|
amount: template.amount ?? null,
|
|
balance: template.balance ?? null,
|
|
status: template.status ?? 'Posted',
|
|
source_page: template.source_page ?? null,
|
|
source_bbox: template.source_bbox ?? null,
|
|
})
|
|
this.recomputeFlags()
|
|
},
|
|
|
|
/**
|
|
* Folds transaction `index + 1` into `index` - descriptions
|
|
* concatenated, amounts summed (one real transaction that printed
|
|
* as two lines), the LATER row's own balance kept (it reflects the
|
|
* cumulative state after both), and source_bbox unioned (so "Show
|
|
* on source" still boxes the full merged area, not just the first
|
|
* row's own original position) when both rows share a page.
|
|
*/
|
|
mergeWithNext(index) {
|
|
const doc = this.activeDocument
|
|
if (!doc) return
|
|
const txns = doc.result.transactions
|
|
if (index < 0 || index + 1 >= txns.length) return
|
|
const a = txns[index]
|
|
const b = txns[index + 1]
|
|
a.description = [a.description, b.description].filter(Boolean).join(' ')
|
|
if (a.amount !== null && b.amount !== null) a.amount = Math.round((a.amount + b.amount) * 100) / 100
|
|
else if (b.amount !== null) a.amount = b.amount
|
|
if (b.balance !== null && b.balance !== undefined) a.balance = b.balance
|
|
if (a.source_bbox && b.source_bbox && a.source_page === b.source_page) {
|
|
a.source_bbox = {
|
|
x0: Math.min(a.source_bbox.x0, b.source_bbox.x0),
|
|
x1: Math.max(a.source_bbox.x1, b.source_bbox.x1),
|
|
top: Math.min(a.source_bbox.top, b.source_bbox.top),
|
|
bottom: Math.max(a.source_bbox.bottom, b.source_bbox.bottom),
|
|
}
|
|
}
|
|
txns.splice(index + 1, 1)
|
|
this.recomputeFlags()
|
|
},
|
|
|
|
/** Updates the active document's own `project` after a successful ProjectSidebar.vue "Move to project." */
|
|
setActiveDocumentProject(projectId) {
|
|
const doc = this.activeDocument
|
|
if (doc) doc.project = projectId
|
|
},
|
|
|
|
/** Updates the active document's own `fileName` after a successful DocumentOptionsModal rename. */
|
|
setActiveDocumentFileName(fileName) {
|
|
const doc = this.activeDocument
|
|
if (doc) doc.fileName = fileName
|
|
},
|
|
|
|
/**
|
|
* Removes a document (by its PocketBase id) after a successful
|
|
* delete, and re-settles activeIndex to keep pointing at a sensible
|
|
* document rather than an out-of-range or stale one: everything
|
|
* after the removed slot shifts left by one, so an EARLIER removal
|
|
* decrements activeIndex to track the same logical document; a
|
|
* removal at or after activeIndex leaves the number alone (it now
|
|
* naturally points at whichever document shifted into that slot, or
|
|
* needs clamping if the removed one was active and last).
|
|
*/
|
|
removeDocument(pbId) {
|
|
const idx = this.documents.findIndex((d) => d.pbId === pbId)
|
|
if (idx === -1) return
|
|
this.documents.splice(idx, 1)
|
|
if (idx < this.activeIndex) this.activeIndex -= 1
|
|
this.activeIndex = this.documents.length ? Math.min(this.activeIndex, this.documents.length - 1) : 0
|
|
},
|
|
|
|
/** Clears every loaded document from view, back to the empty state. */
|
|
clearAll() {
|
|
this.documents = []
|
|
this.activeIndex = 0
|
|
},
|
|
|
|
setError(message) {
|
|
this.errorMessage = message
|
|
},
|
|
|
|
clearError() {
|
|
this.errorMessage = ''
|
|
},
|
|
},
|
|
})
|