bettersight-statement-extra.../frontend/src/composables/useBatchExtraction.js

240 lines
12 KiB
JavaScript

/**
* Orchestrates the Extract button for one or more files: runs them
* SEQUENTIALLY (not parallel - one request at a time, each awaited
* before the next starts), driving the processing-phase indicator per
* file and writing each completed result into the extraction store as
* it finishes. A failed file doesn't abort the batch - its error is
* collected and the loop continues, so one bad file in a multi-select
* doesn't block the rest.
*/
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import { useProjectsStore } from '../stores/projectsStore'
import { useUsageStore } from '../stores/usageStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import * as layoutMappingsService from '../services/layoutMappingsService'
import * as formatService from '../services/formatService'
import { useProcessingPhases } from './useProcessingPhases'
import { useLayoutMapping } from './useLayoutMapping'
const IMAGE_FILE_RE = /\.(jpe?g|png)$/i
/**
* `confirmMappingFn` - layout mapper work, passed straight through to
* useLayoutMapping.js's own `confirmFn` (see that file) - omit for the
* default "always decline a stale/near match" behavior.
*/
export function useBatchExtraction(confirmMappingFn) {
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const projectsStore = useProjectsStore()
const usageStore = useUsageStore()
const { isProcessing, phaseText, start, stop } = useProcessingPhases()
const { resolveNeedsMapping } = useLayoutMapping(confirmMappingFn)
/**
* Persists a statement that needs manual mapping/value confirmation
* as a real PocketBase document record (no `result` yet), then adds
* the matching placeholder to extractionStore's own document queue
* with that record's real pbId - the raw `File` is kept in
* `pendingMapping.file` too, same as before, so clicking "Map now"
* later in THIS session doesn't need to re-fetch it from R2 first (a
* reload is what loses that in-memory copy - see useDocuments.js's
* own handling of a `needsMapping` record for that case).
*/
async function addPendingMappingDoc(file, { fingerprint, fingerprintHash, needsValueConfirmation, candidateRow, fieldOrder }, openingBalanceInput, closingBalanceInput) {
const docKey = extractionService.docKeyFor(file)
const record = await documentsService.savePendingMappingDocument({
docKey, fileName: file.name, sourceFile: file,
project: projectsStore.activeProjectId,
openingBalanceInput, closingBalanceInput,
fingerprint, fingerprintHash, needsValueConfirmation, candidateRow, fieldOrder,
})
projectsStore.addDocumentToCache(record.project, record)
extractionStore.addPendingMappingDocument({
pbId: record.id,
docKey, fileName: file.name, project: record.project,
previewUrl: URL.createObjectURL(file),
isImage: IMAGE_FILE_RE.test(file.name),
openingBalanceInput, closingBalanceInput,
pendingMapping: { file, fingerprint, fingerprintHash, needsValueConfirmation, candidateRow, fieldOrder },
})
}
/**
* Submits every chosen file for extraction, one at a time.
*
* Data flow:
* files (File[])
* openingBalanceInput (string) - raw text from the opening balance field,
* applied to every file in the batch the same way
* closingBalanceInput (string) - raw text from the closing balance field
*/
async function runBatch(files, openingBalanceInput, closingBalanceInput) {
if (!files || !files.length) return
extractionStore.clearError()
extractionStore.startBatch(files.length)
const openingBalance = formatService.parseNum(openingBalanceInput)
const closingBalance = formatService.parseNum(closingBalanceInput)
const failures = []
for (const [i, file] of files.entries()) {
extractionStore.advanceBatch(i + 1, file.name)
start()
try {
let result = await extractionService.process(file, openingBalance, closingBalance)
let usedMapping = null
// Captured from the FIRST (needs_mapping) response, before
// `result` is overwritten below - a successful forced-mapping
// retry's own response is a normal pipeline result, which never
// carries fingerprintHash at all (that field only exists on the
// 422 needs_mapping response). Found this by re-reading the
// code, not by it failing a test: the line below used to read
// `result.fingerprintHash` AFTER the reassignment, which would
// always have been undefined - documents.layoutFingerprintHash
// would have silently never been set for an applied mapping.
let usedFingerprintHash = null
// Layout mapper work: neither the keyword detector nor the
// layout_quirks fallback could resolve this statement's columns
// - look for a stored mapping (exact match applies silently; a
// stale exact match or a near match needs confirmation) before
// giving up. See useLayoutMapping.js's own docstring.
if (result.needs_mapping) {
const resolved = await resolveNeedsMapping({ fingerprint: result.fingerprint, fingerprintHash: result.fingerprintHash })
if (resolved.applied) {
usedFingerprintHash = result.fingerprintHash
result = await extractionService.process(file, openingBalance, closingBalance, resolved.forcedMapping)
usedMapping = resolved.mapping
} else if (resolved.reason === 'no_match') {
// No stored mapping resolves this - persisted to PocketBase
// (savePendingMappingDocument, pb_migrations/12) as a real
// document record with its own sourceFile, not just an
// in-memory placeholder - a real reported gap: the earlier,
// memory-only version disappeared on a page reload mid-
// session, forcing a full re-upload. Added to the ordinary
// document queue (addPendingMappingDocument) the same way
// either way - a second needs-mapping file in the same
// batch no longer stomps the first's pending state the way
// the original single-slot layoutMapperStore.pendingFile
// design once did (a separate, earlier reported bug).
await addPendingMappingDoc(file, {
fingerprint: resolved.fingerprint, fingerprintHash: resolved.fingerprintHash,
needsValueConfirmation: false, candidateRow: null, fieldOrder: null,
}, openingBalanceInput, closingBalanceInput)
result = null
} else {
result = { error: 'Mapping declined - extraction skipped for this file.' }
}
} else if (result.needs_value_confirmation) {
// A narrower sibling of needs_mapping above (value-pattern
// mapping work) - the columns resolved fine, only the raw
// VALUES in them didn't parse. Same exact/near-match lookup
// (resolveNeedsMapping doesn't care WHY a fingerprint needed
// resolving), differing only in what happens on 'no_match':
// the candidate row the backend already read is persisted on
// the placeholder too, so ManualMappingView.vue can show a
// correction form instead of the from-scratch region-drawing
// UI, since the column positions are already known - even
// after a reload, with no need to re-run extraction first.
const resolved = await resolveNeedsMapping({ fingerprint: result.fingerprint, fingerprintHash: result.fingerprintHash })
if (resolved.applied) {
usedFingerprintHash = result.fingerprintHash
result = await extractionService.process(file, openingBalance, closingBalance, resolved.forcedMapping)
usedMapping = resolved.mapping
} else if (resolved.reason === 'no_match') {
await addPendingMappingDoc(file, {
fingerprint: resolved.fingerprint, fingerprintHash: resolved.fingerprintHash,
needsValueConfirmation: true, candidateRow: result.candidateRow, fieldOrder: result.fieldOrder,
}, openingBalanceInput, closingBalanceInput)
result = null
} else {
result = { error: 'Mapping declined - extraction skipped for this file.' }
}
}
if (result === null) {
// Queued as a placeholder document above - nothing more to do
// for this file right now, move on to the next one.
} else if (result.error) {
failures.push(`${file.name}: ${result.error}`)
} else {
const docKey = extractionService.docKeyFor(file)
// Persisted to PocketBase BEFORE it's added to the store, so
// every in-view document always has a real pbId to save row
// edits against - a save failure here is treated the same as
// an extraction failure (the file's own entry in `failures`),
// not shown with no way to ever persist an edit to it.
const record = await documentsService.saveDocument({
docKey, fileName: file.name, sourceFile: file, result,
// Whichever project is active in the sidebar, if any - falls
// back to the user's default "General" project inside
// saveDocument itself when this is null (nothing selected,
// "All" view).
project: projectsStore.activeProjectId,
openingBalanceInput, closingBalanceInput,
layoutMappingUsed: usedMapping?.id,
layoutMappingVersionUsed: usedMapping?.version,
layoutApplied: usedMapping ? 'mapping' : 'auto',
layoutFingerprintHash: usedMapping ? usedFingerprintHash : undefined,
})
// A mapping that was actually applied gets its usage recorded
// for drift detection regardless of whether the save above
// succeeded - best-effort, never blocks showing the result.
// (Unrelated to usageStore.recordExtraction below, despite the
// similar name - this one tracks a MAPPING's own pass/fail
// history, not billable page usage.)
if (usedMapping) {
layoutMappingsService.recordUsage(usedMapping.id, { success: layoutMappingsService.checksPassed(result) }).catch(() => {})
}
// Billing/usage-tracking foundation - one real extraction just
// got delivered to the user, so it counts, regardless of
// whether auto-detection or a saved mapping produced it.
// page_reports is populated identically across every
// extraction path (dual-engine text PDF, OCR-only, forced-
// mapping retry), so this is a reliable page count regardless
// of which one actually ran. Best-effort internally (see
// usageStore.js), never blocks the result being shown.
usageStore.recordExtraction(record.id, result.page_reports?.length || 0)
// Keeps the sidebar's own per-project document list live if
// that project is currently expanded there - a no-op otherwise
// (see projectsStore.js's own comment on why this cache exists).
projectsStore.addDocumentToCache(record.project, record)
extractionStore.addDocument({
pbId: record.id,
docKey,
fileName: file.name,
project: record.project,
previewUrl: URL.createObjectURL(file),
isImage: IMAGE_FILE_RE.test(file.name),
result,
// Seed each new document with what was typed for the whole
// batch, so a later Recheck Balance on any of them starts
// from that value instead of blank, until edited per-document.
openingBalanceInput,
closingBalanceInput,
// Layout mapper work (L.7) - carried onto the in-memory
// document too, not just the PocketBase record, so a later
// recheck (useRowEditing.js/TransactionRow.vue) knows
// whether THIS document used a mapping and should feed its
// own drift-detection signal back into recordUsage().
layoutMappingUsed: usedMapping?.id ?? null,
layoutMappingVersionUsed: usedMapping?.version ?? null,
})
}
} catch (e) {
failures.push(`${file.name}: ${e.message}`)
}
stop()
}
if (failures.length) extractionStore.setError(failures.join('; '))
uiStore.closeResultsOpen()
extractionStore.endBatch()
}
return { isProcessing, phaseText, runBatch }
}