143 lines
6.7 KiB
JavaScript
143 lines
6.7 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 * 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
|
|
|
|
/** Whether a (possibly mapping-forced) extraction's own checks actually passed - the drift-detection signal a used mapping's usageCount/failureCount tracks (see layoutMappingsService.recordUsage). */
|
|
function checksPassed(result) {
|
|
const balanceCheck = result.checks?.find((c) => c.name === 'statement_balance')
|
|
const runningCheck = result.checks?.find((c) => c.name === 'running_balance')
|
|
return balanceCheck?.outcome !== 'fail' && !(runningCheck?.mismatches?.length)
|
|
}
|
|
|
|
/**
|
|
* `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 { isProcessing, phaseText, start, stop } = useProcessingPhases()
|
|
const { resolveNeedsMapping } = useLayoutMapping(confirmMappingFn)
|
|
|
|
/**
|
|
* 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
|
|
|
|
// 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) {
|
|
result = await extractionService.process(file, openingBalance, closingBalance, resolved.forcedMapping)
|
|
usedMapping = resolved.mapping
|
|
} else if (resolved.reason === 'no_match') {
|
|
result = { error: "This statement's layout isn't recognized yet and needs manual mapping (not available yet)." }
|
|
} else {
|
|
result = { error: 'Mapping declined - extraction skipped for this file.' }
|
|
}
|
|
}
|
|
|
|
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 ? result.fingerprintHash : 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.
|
|
if (usedMapping) {
|
|
layoutMappingsService.recordUsage(usedMapping.id, { success: checksPassed(result) }).catch(() => {})
|
|
}
|
|
// 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,
|
|
})
|
|
}
|
|
} catch (e) {
|
|
failures.push(`${file.name}: ${e.message}`)
|
|
}
|
|
stop()
|
|
}
|
|
|
|
if (failures.length) extractionStore.setError(failures.join('; '))
|
|
uiStore.closeResultsOpen()
|
|
extractionStore.endBatch()
|
|
}
|
|
|
|
return { isProcessing, phaseText, runBatch }
|
|
}
|