bettersight-statement-extra.../frontend/src/components/TransactionsTable.vue

512 lines
24 KiB
Vue

<script setup>
/**
* TransactionsTable.vue
*
* Opening/closing balance inputs + their calculated readouts, the
* Hide/Show Source Doc toggle, and the transactions table itself. Always
* rendered (not gated on an extraction result existing) so the balance
* fields are enterable BEFORE clicking Extract, since they're submitted
* as part of that same request - the table itself shows an empty state
* until there's a result to display.
*
* The opening-balance readout is deliberately a snapshot of the
* ORIGINAL extraction's own opening_balance - the backend never returns
* a new one on recheck (only status/checks change), so this stays
* correct without needing special-casing; only its green/not-green
* "match" state follows the live statement_balance check outcome, same
* asymmetry the original vanilla-JS version had (confirmed by reading
* it: openingCalc's text is set once in renderResult and never touched
* again by applyCheckResults, while closingCalc's text IS recomputed on
* every recheck).
*/
import { ref, computed, watch } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import { useProjectsStore } from '../stores/projectsStore'
import { fmtMoney, parseNum } from '../services/formatService'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import { useTransactionFilters } from '../composables/useTransactionFilters'
import TransactionRow from './TransactionRow.vue'
import DocumentNavBar from './DocumentNavBar.vue'
import ConfirmModal from './ConfirmModal.vue'
import DownloadChoiceModal from './DownloadChoiceModal.vue'
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const projectsStore = useProjectsStore()
// ── Results dropdown + Download (formerly ResultCard.vue - moved into
// this top bar alongside DocumentNavBar per explicit request, rather
// than its own separate card further down the page). ──────────────────
const result = computed(() => extractionStore.currentResult)
const statusClass = computed(() => 'status-banner ' + (result.value?.status || '').replace(' ', '-'))
const statusDotClass = computed(() => 'results-status-dot ' + (result.value?.status || '').replace(' ', '-'))
const periodText = computed(() => (result.value?.period ? `Statement period: ${result.value.period}` : ''))
const statusIcon = computed(() => {
const s = result.value?.status
if (s === 'Verified') return 'fa-circle-check'
if (s === 'Needs review') return 'fa-triangle-exclamation'
if (s === 'Failed') return 'fa-circle-xmark'
return 'fa-circle-info'
})
const outcomeIcon = {
pass: 'fa-check', fail: 'fa-xmark', needs_review: 'fa-triangle-exclamation', not_available: 'fa-minus',
}
// Click opens the dropdown; moving the mouse off the whole trigger+panel
// zone closes it again (mouseleave on the wrapper only fires once the
// pointer truly leaves both, not when moving from the button onto the
// panel beneath it) - "stays open while hovered, closes when you move
// away," per the explicit ask. uiStore.resultsOpen (not a local ref) so
// useBatchExtraction.js can still reset it closed after every fresh
// extraction, same as it always has.
function toggleResults() {
if (!result.value) return
uiStore.toggleResultsOpen()
}
const downloading = ref(false)
const showDownloadChoice = ref(false)
/**
* Triggers one browser save for a given {pbId, result, openingBalance,
* closingBalance}, then best-effort persists the SAME blob to R2 (via
* PocketBase's own file storage - documentsService.saveExportFile,
* overwriting whatever export was there before, see that function's own
* comment for why only the latest). The Blob is immutable and reusable,
* so the one fetch serves both the browser download and the R2 upload -
* no second request. A failure saving to R2 is reported but never
* blocks or undoes the download the user actually asked for.
*/
async function downloadOne({ pbId, result: r, openingBalance, closingBalance }) {
const blob = await extractionService.exportWorkbook(r, openingBalance, closingBalance)
const fileName = (r.title || 'Statement_Extraction').replace(/\.pdf$/i, '') + '.xlsx'
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
try {
await documentsService.saveExportFile(pbId, blob, fileName)
} catch (e) {
extractionStore.setError('Downloaded, but could not save a copy for later: ' + e.message)
}
}
/** The currently active document's export, via /api/export + a browser save. */
async function handleDownloadCurrent() {
if (!result.value) return
downloading.value = true
extractionStore.clearError()
try {
await downloadOne({
pbId: extractionStore.activeDocument?.pbId,
result: result.value,
openingBalance: extractionStore.effectiveOpeningBalance,
closingBalance: extractionStore.effectiveClosingBalance,
})
} catch (e) {
extractionStore.setError('Could not generate the export: ' + e.message)
}
downloading.value = false
}
/**
* Exports every loaded document in turn - the same per-document export
* call handleDownloadCurrent makes, just looped. Each document's own
* typed balance inputs (not just the active one's) are used, same
* fallback logic as effectiveOpeningBalance/effectiveClosingBalance.
* Triggers N sequential browser downloads, not a zip - some browsers
* prompt to allow multiple downloads from one click, a minor known
* wrinkle, not a reason to stand up a zip-export endpoint for this.
*/
async function handleDownloadAll() {
downloading.value = true
extractionStore.clearError()
const failures = []
for (const doc of extractionStore.documents) {
try {
await downloadOne({
pbId: doc.pbId,
result: doc.result,
openingBalance: extractionService.effectiveBalance(
parseNum(doc.openingBalanceInput), doc.result?.opening_balance,
),
closingBalance: extractionService.effectiveBalance(
parseNum(doc.closingBalanceInput), doc.result?.closing_balance,
),
})
} catch (e) {
failures.push(`${doc.fileName}: ${e.message}`)
}
}
if (failures.length) extractionStore.setError('Could not generate every export: ' + failures.join('; '))
downloading.value = false
}
/**
* The single Download button's own click: with only one document loaded
* there's nothing to choose between, so it downloads immediately, same
* as before. With more than one, asks which via DownloadChoiceModal -
* replaces the old separate "Download All" button (one button, one
* choice step, instead of two buttons competing for space).
*/
function handleDownloadClick() {
if (!result.value) return
// Only offers the "all documents" choice once a batch has actually
// finished - mid-batch, documents.length already grows as each file
// completes, so asking "all" too early would silently leave out
// whatever's still processing. Same gate the old standalone Download
// All button used.
if (!extractionStore.isBatchProcessing && extractionStore.documents.length > 1) {
showDownloadChoice.value = true
} else {
handleDownloadCurrent()
}
}
function handleDownloadChoiceCurrent() {
showDownloadChoice.value = false
handleDownloadCurrent()
}
function handleDownloadChoiceAll() {
showDownloadChoice.value = false
handleDownloadAll()
}
// Reassigns the ACTIVE document to a different project - independent of
// DocumentNavBar's own visibility (that's gated on there being more than
// one document; moving a single document to a project should still work
// with just one). Only touches the document's own `project` field, both
// remotely and in extractionStore - doesn't remove it from the current
// view even if it no longer matches an active project filter (a known,
// accepted simplification - the next reload/filter change will reflect
// it correctly).
//
// The <select> is driven by its own local v-model (selectedProjectId),
// not a direct :value binding straight to the document's own project -
// a plain :value binding wouldn't let a cancelled move revert the
// dropdown's visible selection (the browser already shows the clicked
// option; Vue only re-syncs a <select>'s displayed value through
// v-model, not a bare :value). Picking a different project opens a
// confirm step (ConfirmModal) rather than moving immediately - one
// misclick on the dropdown used to silently relocate a document with no
// feedback at all.
const movingProject = ref(false)
const selectedProjectId = ref(extractionStore.activeDocument?.project ?? '')
watch(
() => extractionStore.activeDocument?.project,
(v) => { selectedProjectId.value = v ?? '' },
)
const showMoveConfirm = ref(false)
const pendingProjectId = ref(null)
const pendingProjectName = computed(
() => projectsStore.projects.find((p) => p.id === pendingProjectId.value)?.name ?? '',
)
const moveConfirmNote = ref('')
let moveConfirmNoteTimer = null
function handleSelectChange() {
const doc = extractionStore.activeDocument
if (!doc || !selectedProjectId.value || selectedProjectId.value === doc.project) return
pendingProjectId.value = selectedProjectId.value
showMoveConfirm.value = true
}
function cancelMove() {
showMoveConfirm.value = false
pendingProjectId.value = null
// Revert the dropdown back to the document's actual, unchanged project.
selectedProjectId.value = extractionStore.activeDocument?.project ?? ''
}
async function confirmMove() {
const doc = extractionStore.activeDocument
const projectId = pendingProjectId.value
const projectName = pendingProjectName.value
showMoveConfirm.value = false
if (!doc || !projectId) return
movingProject.value = true
extractionStore.clearError()
try {
await documentsService.moveToProject(doc.pbId, projectId)
// Keeps the sidebar's own per-project document lists live if either
// the old or new project is currently expanded there (each a no-op
// otherwise) - same reasoning as useBatchExtraction.js's own call.
projectsStore.moveDocumentInCache(doc.project, projectId, { id: doc.pbId, fileName: doc.fileName })
extractionStore.setActiveDocumentProject(projectId)
clearTimeout(moveConfirmNoteTimer)
moveConfirmNote.value = `Moved to ${projectName}`
moveConfirmNoteTimer = setTimeout(() => { moveConfirmNote.value = '' }, 3500)
} catch (err) {
extractionStore.setError('Could not move this document: ' + err.message)
selectedProjectId.value = doc.project
}
pendingProjectId.value = null
movingProject.value = false
}
const transactions = computed(() => result.value?.transactions || [])
// openingBalanceInput/closingBalanceInput now live per-document
// (extractionStore.activeDocument) once one exists, or as pending
// pre-extraction state before that - these writable computeds let the
// template keep plain v-model bindings either way; the store's own
// getters/actions pick the right target (see extractionStore.js).
const openingBalanceInput = computed({
get: () => extractionStore.openingBalanceInputDisplay,
set: (v) => extractionStore.setOpeningBalanceInput(v),
})
const closingBalanceInput = computed({
get: () => extractionStore.closingBalanceInputDisplay,
set: (v) => extractionStore.setClosingBalanceInput(v),
})
const { sortKey, sortDir, setSort, filters, clearFilters, hasActiveFilters, statusOptions, visibleRows } =
useTransactionFilters(transactions)
const balanceCheck = computed(() => result.value?.checks?.find((c) => c.name === 'statement_balance'))
const balanceMatches = computed(() => balanceCheck.value?.outcome === 'pass')
const openingCalcText = computed(() => {
const v = result.value?.opening_balance
return v !== null && v !== undefined ? 'Calculated: ' + fmtMoney(v) : ''
})
const closingCalcText = computed(() => {
const v = balanceCheck.value?.calculated_closing
return v !== undefined && v !== null ? 'Calculated: ' + fmtMoney(v) : ''
})
const toggleLabel = computed(() => (uiStore.pdfColHidden ? 'Show Source Doc' : 'Hide Source Doc'))
// The grey (non-matching) calc-readout on its own doesn't say WHY -
// surface the statement_balance check's own detail text (it already
// has the full math and the "off by $X" amount, no need to re-derive
// that client-side) right under the fields where the mismatch is
// actually visible, instead of leaving the user to find the same line
// in the (collapsed-by-default) checks list elsewhere on the page.
// Also covers "not_available" (neither a typed nor an auto-detected
// balance exists at all) - that outcome has its own explanatory detail
// text too and was previously left just as silent as "fail" used to be.
const balanceMismatchText = computed(() => {
const check = balanceCheck.value
return check?.outcome === 'fail' || check?.outcome === 'not_available' ? check.detail : ''
})
// "fail" gets a leading "Balance doesn't match the statement —" since the
// detail text itself is just the raw math; "not_available"'s own detail
// text already reads as a complete sentence, so it needs no prefix.
const balanceMismatchPrefix = computed(() => (balanceCheck.value?.outcome === 'fail' ? "Balance doesn't match the statement — " : ''))
// ── Balance recheck ──────────────────────────────────────────────────
// Entering opening/closing balance AFTER extraction (e.g. the user
// forgot to type it before clicking Extract) doesn't update anything on
// its own - typing alone was never wired to a recheck, same as the
// original vanilla-JS version (it only rechecked on a row save or a
// download). This button is the explicit, deliberate trigger - same
// recheck-only (no re-extraction) call a row Save already makes.
const rechecking = ref(false)
async function handleRecheck() {
if (!result.value || rechecking.value) return
rechecking.value = true
extractionStore.clearError()
try {
const checkResult = await extractionService.recheck(
result.value,
extractionStore.effectiveOpeningBalance,
extractionStore.effectiveClosingBalance,
)
if (checkResult.error) {
extractionStore.setError(checkResult.error)
} else {
extractionStore.applyCheckResults(checkResult)
}
} catch (e) {
extractionStore.setError('Network error: ' + e.message)
}
rechecking.value = false
}
</script>
<template>
<!--
The former ResultCard.vue, merged into this top bar: a Results
toggle (left) opens a hover-sticky dropdown with the status/checks
detail; DocumentNavBar (center, truly centered via the grid below
regardless of how wide the left/right content is) carries the active
document's filename - click it to rename or delete; Download (right)
exports the current document, or opens DownloadChoiceModal to ask
"current vs. all" once more than one document is loaded.
-->
<div v-if="extractionStore.documents.length > 0" class="txn-top-bar">
<div class="results-trigger-wrap" @mouseleave="uiStore.closeResultsOpen">
<button type="button" class="results-toggle" :disabled="!result" @click="toggleResults">
<span v-if="result" :class="statusDotClass"></span>
<span>Results</span>
<i class="fa-solid fa-chevron-down" :class="{ open: uiStore.resultsOpen }"></i>
</button>
<div v-if="uiStore.resultsOpen && result" class="results-dropdown">
<div class="results-dropdown-inner card">
<div :class="statusClass"><i class="fa-solid" :class="statusIcon"></i>{{ result.status }}</div>
<div class="period-note">{{ periodText }}</div>
<ul class="checks-list">
<li v-for="check in result.checks" :key="check.name">
<span class="tag" :class="check.outcome"><i class="fa-solid" :class="outcomeIcon[check.outcome]"></i>{{ check.outcome.replace('_', ' ') }}</span>
<span><strong>{{ check.name.replace(/_/g, ' ') }}</strong> — {{ check.detail }}</span>
</li>
</ul>
</div>
</div>
</div>
<DocumentNavBar />
<button type="button" class="btn-toggle txn-download-btn" :disabled="!result || downloading" @click="handleDownloadClick">
<i class="fa-solid" :class="downloading ? 'fa-spinner fa-spin' : 'fa-file-excel'"></i>
{{ downloading ? 'Preparing…' : 'Download' }}
</button>
</div>
<DownloadChoiceModal
:visible="showDownloadChoice"
:count="extractionStore.documents.length"
@current="handleDownloadChoiceCurrent"
@all="handleDownloadChoiceAll"
@cancel="showDownloadChoice = false"
/>
<div v-if="result" class="move-to-project">
<label><i class="fa-solid fa-folder-open"></i>Move to project</label>
<select v-model="selectedProjectId" :disabled="movingProject" @change="handleSelectChange">
<option v-for="p in projectsStore.projects" :key="p.id" :value="p.id">{{ p.name }}</option>
</select>
<span v-if="moveConfirmNote" class="move-confirm-note"><i class="fa-solid fa-circle-check"></i>{{ moveConfirmNote }}</span>
</div>
<ConfirmModal
:visible="showMoveConfirm"
title="Move document?"
title-icon="fa-folder-open"
:message="`Move “${extractionStore.activeDocument?.fileName}” to “${pendingProjectName}”?`"
confirm-label="Move"
confirm-icon="fa-folder-open"
@confirm="confirmMove"
@cancel="cancelMove"
/>
<div class="txn-col-head">
<h2>Transactions</h2>
<button class="btn-toggle" type="button" @click="uiStore.togglePdfCol">
<i class="fa-solid" :class="uiStore.pdfColHidden ? 'fa-eye' : 'fa-eye-slash'"></i>
{{ toggleLabel }}
</button>
</div>
<div class="fields-row">
<div class="fields">
<div>
<label>Opening balance (optional)</label>
<input v-model="openingBalanceInput" type="text" inputmode="decimal" placeholder="e.g. 90,569.13">
<div class="calc-readout" :class="{ match: balanceMatches }">{{ openingCalcText }}</div>
</div>
<div>
<label>Closing balance (optional)</label>
<input v-model="closingBalanceInput" type="text" inputmode="decimal" placeholder="e.g. 88,479.50">
<div class="calc-readout" :class="{ match: balanceMatches }">{{ closingCalcText }}</div>
</div>
</div>
<div class="recheck-wrap">
<label class="recheck-spacer">&nbsp;</label>
<button class="btn-toggle btn-recheck" type="button" :disabled="!result || rechecking" @click="handleRecheck">
<i class="fa-solid" :class="rechecking ? 'fa-spinner fa-spin' : 'fa-rotate'"></i>
{{ rechecking ? 'Checking…' : 'Recheck Balance' }}
</button>
</div>
</div>
<div v-if="balanceMismatchText" class="error-note visible">{{ balanceMismatchPrefix }}{{ balanceMismatchText }}</div>
<div class="note">This statement format may not print a clean opening/closing balance — enter them here to run the full statement balance check; otherwise it's marked "not available" rather than guessed.</div>
<div v-if="!result" class="empty-panel empty-panel-table">
<p>No Transactions to Display.<br>Upload a source document to get started.</p>
</div>
<div v-else class="table-wrap">
<table>
<colgroup>
<col style="width:34px">
<col style="width:120px">
<col>
<col style="width:120px">
<col style="width:135px">
<col style="width:95px">
</colgroup>
<thead>
<tr>
<th></th>
<th>
Date
<span class="sort-arrows">
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'date' && sortDir === 'asc' }" title="Sort by date, oldest first" @click="setSort('date', 'asc')"><i class="fa-solid fa-sort-up"></i></button>
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'date' && sortDir === 'desc' }" title="Sort by date, newest first" @click="setSort('date', 'desc')"><i class="fa-solid fa-sort-down"></i></button>
</span>
</th>
<th>
Description
<span class="sort-arrows">
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'description' && sortDir === 'asc' }" title="Sort A-Z" @click="setSort('description', 'asc')"><i class="fa-solid fa-sort-up"></i></button>
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'description' && sortDir === 'desc' }" title="Sort Z-A" @click="setSort('description', 'desc')"><i class="fa-solid fa-sort-down"></i></button>
</span>
</th>
<th class="amt">
Amount
<span class="sort-arrows">
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'amount' && sortDir === 'asc' }" title="Sort lowest first" @click="setSort('amount', 'asc')"><i class="fa-solid fa-sort-up"></i></button>
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'amount' && sortDir === 'desc' }" title="Sort highest first" @click="setSort('amount', 'desc')"><i class="fa-solid fa-sort-down"></i></button>
</span>
</th>
<th class="amt">
Balance
<span class="sort-arrows">
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'balance' && sortDir === 'asc' }" title="Sort lowest first" @click="setSort('balance', 'asc')"><i class="fa-solid fa-sort-up"></i></button>
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'balance' && sortDir === 'desc' }" title="Sort highest first" @click="setSort('balance', 'desc')"><i class="fa-solid fa-sort-down"></i></button>
</span>
</th>
<th>
Status
<span class="sort-arrows">
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'status' && sortDir === 'asc' }" title="Sort A-Z" @click="setSort('status', 'asc')"><i class="fa-solid fa-sort-up"></i></button>
<button type="button" class="sort-arrow" :class="{ active: sortKey === 'status' && sortDir === 'desc' }" title="Sort Z-A" @click="setSort('status', 'desc')"><i class="fa-solid fa-sort-down"></i></button>
</span>
</th>
</tr>
<tr class="filter-row">
<th class="row-actions">
<button v-if="hasActiveFilters" type="button" class="clear-filters-btn" title="Clear all filters" @click="clearFilters"><i class="fa-solid fa-filter-circle-xmark"></i></button>
</th>
<th><input v-model="filters.date" type="text" class="filter-input" placeholder="Filter…"></th>
<th><input v-model="filters.description" type="text" class="filter-input" placeholder="Search description…"></th>
<th class="amt"><input v-model="filters.amount" type="text" class="filter-input" placeholder="Filter…"></th>
<th class="amt"><input v-model="filters.balance" type="text" class="filter-input" placeholder="Filter…"></th>
<th>
<select v-model="filters.status" class="filter-input filter-select">
<option value="">All</option>
<option v-for="s in statusOptions" :key="s" :value="s">{{ s }}</option>
</select>
</th>
</tr>
</thead>
<tbody>
<tr v-if="visibleRows.length === 0">
<td colspan="6" class="no-rows-note">No transactions match the current filters.</td>
</tr>
<TransactionRow
v-for="entry in visibleRows"
:key="extractionStore.currentDocKey + ':' + entry.index"
:index="entry.index"
:transaction="entry.transaction"
:is-flagged="extractionStore.flaggedIndexes.has(entry.index)"
/>
</tbody>
</table>
</div>
</template>