Move document persistence from localStorage to PocketBase (Stage B.2)

New documentsService.js (saveDocument/updateDocument/listDocuments/
deleteDocument/sourceFileUrl) and a minimal projectsService.js
(getDefaultProject/listProjects, extended in B.3) replace
extractionService.js's old localStorage-backed persistResult/
restoreResult/lastBatchKeys/appendToLastBatch/startNewBatch/
discardPersisted - deleted outright, not kept alongside.

extractionStore's document entries gained a pbId field (the PocketBase
record id), set from saveDocument's create response or a listed
record's own id - needed so useRowEditing's saveEdit() knows which
record to PATCH.

RestoreBanner.vue and uiStore's restoreBannerVisible/Text/show/hide
deleted outright (not repurposed) - the banner existed because a
localStorage cache's presence was ambiguous ("did a crash happen?");
PocketBase being the real backend means a logged-in user's documents
just load, same as any other app showing your own data.
useFileUpload.restoreOnLoad() renamed loadDocuments(), simplified from
the plan's own "needs a watcher" - unnecessary, since App.vue's auth
gate already means ExtractorView can't mount before authenticated.

Two real bugs caught by executing the actual services against the live
PocketBase, not just reading them: an empty-string filter is rejected
outright rather than treated as "no filter" (fixed by omitting the key
entirely); sort:'-created' referenced a field that didn't exist -
projects/documents came out of migration 1 with no created/updated
fields at all, unlike the built-in users auth collection. Fixed with a
new migration (2_add_timestamps.js, not editing the one that already
ran) adding autodate created/updated to both, field shape copied from
users' own via the REST API.

Verified end-to-end with the real, committed services run from a
plain Node script against the live container: signup -> default
project resolves -> saveDocument with a real File -> listDocuments
finds it -> sourceFileUrl fetched for real returns the exact original
bytes -> updateDocument (simulating a row edit) -> re-listDocuments
confirms the change actually persisted. npm run build passes.
measure.py unaffected; R2/Google settings confirmed to survive the
PocketBase container rebuild.
This commit is contained in:
JasonFraser 2026-10-13 06:41:51 -04:00
parent 87b978f837
commit e59013cdcb
14 changed files with 271 additions and 205 deletions

View File

@ -355,6 +355,12 @@ statement files, why every document is required to belong to a project from day
project-scoped, project REQUIRED not optional, a
sourceFile field for the original PDF/image). Pure
schema, no secrets — safe to commit.
pb_migrations/2_add_timestamps.js
— projects/documents came out of migration 1 with NO
created/updated fields at all (confirmed for real, not
assumed — a plain base collection doesn't get them
automatically the way the users auth collection does).
Adds autodate created/updated to both.
pb_hooks/ensure_default_project.pb.js
— fires on every new users record (password signup and
Google OAuth2 signup both create one the same way) and
@ -665,6 +671,69 @@ built and tested; B.2 document-persistence migration and B.3 sidebar UI not star
own settings, so this was flagged and confirmed with the user before proceeding rather
than silently upserting a well-known default credential.
**PocketBase Stage B.2 - document persistence moved from localStorage to PocketBase,
2026-10-13 (B.3 sidebar UI still not started).** `extractionService.js`'s old
localStorage-backed `persistResult`/`restoreResult`/`lastBatchKeys`/`appendToLastBatch`/
`startNewBatch`/`discardPersisted` are GONE, not kept alongside the new path - one source
of truth. Replaced by two new services: `projectsService.js` (minimal for now -
`getDefaultProject()`/`listProjects()`; B.3 adds create/rename/delete) and
`documentsService.js` (`saveDocument`/`updateDocument`/`listDocuments`/`deleteDocument`/
`sourceFileUrl`). `extractionStore.js`'s document entries gained a `pbId` field (the
PocketBase record id) - needed because a row edit now has to know WHICH record to PATCH;
set from `saveDocument`'s own create response (fresh extraction) or a listed record's own
`id` (restore).
Deliberately NOT cached: `projectsService.getDefaultProject()` queries PocketBase fresh
every call rather than caching the id in a module variable - a cache would leak across a
logout/login within the same page session (user B getting user A's cached project id).
This is a local PocketBase instance; the extra round trip is cheap, correctness wins.
**`RestoreBanner.vue`/`uiStore`'s `restoreBannerVisible`/`restoreBannerText`/
`showRestoreBanner`/`hideRestoreBanner` deleted outright**, not repurposed - this followed
through on what the Stage B.1 entry flagged as likely. The localStorage version's banner
existed because loading saved data was ambiguous ("did a crash happen?"); now that
PocketBase is the real, authoritative backend, there's no ambiguity left to explain - a
logged-in user's documents just load, the same way any other app shows your own data.
`useFileUpload.js`'s `restoreOnLoad()` was renamed `loadDocuments()` to match (fetches via
`documentsService.listDocuments()`, newest first) and simplified from the plan's own
"a watcher on authStore.isAuthenticated, not just onMount" - turned out unnecessary:
`App.vue`'s auth gate means `ExtractorView` (where `onMounted(loadDocuments)` lives)
literally cannot mount before `isAuthenticated` is true, whether that's a fresh login
(the `<main>` branch mounts fresh the moment the gate flips) or a page reload while
already logged in (the Pinia authStore is seeded synchronously from the SDK's own
already-restored token before first render) - one mechanism covers both cases for free.
**Two real bugs caught via the established discipline of executing the actual service
code against the real running PocketBase, not just reading it or trusting a 200 from
`saveDocument` alone:**
- `documentsService.listDocuments()` passed `filter: ''` when there was nothing to filter
by - PocketBase rejects an empty-string filter outright (a generic 400, not a helpful
field-level error), it is NOT treated as "no filter." Fixed by omitting the `filter` key
from the options object entirely when there's no project to filter by, rather than
passing an empty string.
- Even after that fix, `listDocuments()` still failed - traced to `sort: '-created'`
referencing a field that simply didn't exist: `projects`/`documents` came out of
migration 1 with no `created`/`updated` fields at all. Unlike the `users` auth
collection (which has them built in), a plain base collection doesn't get them unless
declared explicitly - confirmed by listing the collection's own fields via the REST API
and seeing they were genuinely absent, not by guessing. Fixed with a SECOND migration
(`2_add_timestamps.js`, not editing migration 1, which had already run) adding
`{type:"autodate", name:"created", onCreate:true}` and `{..."updated", onCreate:true,
onUpdate:true}` to both collections - the exact field shape copied from `users`' own
`created`/`updated` fields via the REST API, not guessed from memory.
**Verified end-to-end with the real, already-committed services** (not a re-
implementation of their logic, the actual `documentsService.js`/`projectsService.js`
files imported and run from a plain Node script against the live container): signup →
`getDefaultProject()` resolves "General" → `saveDocument()` with a REAL `File` object as
`sourceFile` → the created record's `project` matches the default → `listDocuments()`
returns it → `sourceFileUrl()`'s URL, fetched for real, returns the exact original file
bytes (not just that the create call succeeded) → `updateDocument()` (simulating a row
edit) → re-`listDocuments()` confirms the change actually persisted, not just that the
PATCH response echoed it back. `npm run build` passes. `measure.py` + both services'
health checks unaffected (no backend Python or Docling code touched); R2/Google settings
confirmed to survive the PocketBase container rebuild (named volume, not reset).
**Governing rule: never silently correct or exclude data.** This shows up in several
concrete places, not just as an abstract principle:
- A row with an unusual status (e.g. HSBC's "Cancelled" wires) stays in the output and is
@ -1017,15 +1086,16 @@ restructure; the behavior itself predates it and is unchanged:
did) — now `uiStore.layoutVersion` bumps on that toggle (and on a resize-drag ending) and
every row's own textarea watches it to re-measure.
- All numeric displays are comma-formatted (`formatService.js`'s `fmtMoney`/`fmtNum`).
- Edits persist to `localStorage`, keyed by the source file's name+size
(`extractionService.docKeyFor`), so a crash/reload can restore in-progress edits; the
source-document preview itself can't be persisted this way and needs the same file
re-selected to reappear. As of 2026-10-13 this restores a whole BATCH, not just one
document - `lastBatchKeys()`/`appendToLastBatch()` track every docKey from the last
session, one shared restore banner covers all of them ("Restored N documents..."), and
Discard removes every currently-loaded document's saved copy at once (doesn't touch the
in-memory documents being viewed, same "don't keep this for next time" semantics the
single-document version always had).
- Edits persist to PocketBase (`documentsService.js`'s `saveDocument`/`updateDocument` -
as of 2026-10-13, replacing the earlier localStorage-only version entirely, not
alongside it). Every document a logged-in user has ever processed loads automatically
on page load/login (`useFileUpload.js`'s `loadDocuments()`, newest first) - there's no
"restore banner"/"discard" step anymore (removed outright, not repurposed): the old
banner existed because a localStorage cache's presence was ambiguous ("did a crash
happen?"); PocketBase being the real backend means there's nothing ambiguous left to
explain. A document's own source-preview now loads for real too (`sourceFileUrl`,
backed by R2) - the localStorage-only version could never do this at all ("re-select
the file to see it again" was a permanent limitation, not just an edge case).
- The Extract button shows simulated processing-phase text with an animated ellipsis while
`/api/process` is in flight (`useProcessingPhases.js`/`ProcessingIndicator.vue`, added
2026-10-12) — honestly simulated, not real progress (the backend is one synchronous

View File

@ -256,18 +256,6 @@ td.amt .cell-input{ text-align:right; font-family:var(--fm); }
.row-btn.cancel{ color:var(--t4); }
tr.editing td{ background:rgba(37,99,235,.03); }
.restore-banner{
display:none; align-items:center; justify-content:space-between; gap:12px;
font-size:12.5px; color:var(--t2); background:rgba(37,99,235,.07); border:1px solid var(--border-b);
border-radius:9px; padding:10px 14px; margin-bottom:16px;
}
.restore-banner.visible{ display:flex; }
.restore-banner button{
background:transparent; border:1px solid var(--border-2); color:var(--t3); font-family:var(--fb);
font-size:11.5px; padding:5px 10px; border-radius:7px; cursor:pointer; flex-shrink:0;
}
.restore-banner button:hover{ color:var(--t1); border-color:var(--border-b); }
/* Sits across the top of the transactions card, above the Hide Source
Doc row (TransactionsTable.vue renders it first) - no border/
background box of its own since it's already inside the card's; a

View File

@ -1,37 +0,0 @@
<script setup>
/**
* RestoreBanner.vue
*
* Shown after a batch of documents is restored from localStorage on
* page load. "Discard" clears the saved edits for every currently-
* loaded document (and the last-batch pointer, so reload won't bring
* them back) and hides the banner - the in-memory documents stay as-is
* either way, same as the single-document version's own "discard means
* don't keep this for next time, not get rid of what I'm looking at"
* behavior. Safe to use extractionStore.documents wholesale here: the
* banner auto-hides the moment any NEW batch finishes (see
* useBatchExtraction.js), so it's only ever visible while the documents
* list still matches exactly what was restored.
*/
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import * as extractionService from '../services/extractionService'
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
function discard() {
for (const doc of extractionStore.documents) {
extractionService.discardPersisted(doc.docKey)
}
extractionService.startNewBatch()
uiStore.hideRestoreBanner()
}
</script>
<template>
<div class="restore-banner" :class="{ visible: uiStore.restoreBannerVisible }">
<span>{{ uiStore.restoreBannerText }}</span>
<button @click="discard">Discard saved edits</button>
</div>
</template>

View File

@ -10,6 +10,7 @@
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import * as formatService from '../services/formatService'
import { useProcessingPhases } from './useProcessingPhases'
@ -33,7 +34,6 @@ export function useBatchExtraction() {
if (!files || !files.length) return
extractionStore.clearError()
extractionStore.startBatch(files.length)
extractionService.startNewBatch()
const openingBalance = formatService.parseNum(openingBalanceInput)
const closingBalance = formatService.parseNum(closingBalanceInput)
@ -48,7 +48,17 @@ export function useBatchExtraction() {
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,
openingBalanceInput, closingBalanceInput,
})
extractionStore.addDocument({
pbId: record.id,
docKey,
fileName: file.name,
previewUrl: URL.createObjectURL(file),
@ -60,17 +70,14 @@ export function useBatchExtraction() {
openingBalanceInput,
closingBalanceInput,
})
extractionService.persistResult(docKey, result, file.name)
extractionService.appendToLastBatch(docKey)
}
} catch (e) {
failures.push(`${file.name}: Network error - ${e.message}`)
failures.push(`${file.name}: ${e.message}`)
}
stop()
}
if (failures.length) extractionStore.setError(failures.join('; '))
uiStore.hideRestoreBanner()
uiStore.resultExpanded = false
extractionStore.endBatch()
}

View File

@ -1,21 +1,21 @@
/**
* Staging files for the next Extract click (browse/drag-drop) and
* restoring a previously-processed batch on page load. Source-preview
* URLs and image detection now live on each PROCESSED document
* (extractionStore.addDocument's previewUrl/isImage), not here - this
* composable's only job is "what's about to be uploaded," cleanly
* separate from "what's already processed and being displayed."
* loading the logged-in user's own documents from PocketBase on page
* load. Source-preview URLs and image detection now live on each
* PROCESSED document (extractionStore.addDocument's previewUrl/
* isImage), not here - this composable's only job is "what's about to
* be uploaded," cleanly separate from "what's already processed and
* being displayed."
*/
import { ref } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import { useUiStore } from '../stores/uiStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
const ACCEPTED_FILE_RE = /\.(pdf|jpe?g|png)$/i
const IMAGE_FILE_RE = /\.(jpe?g|png)$/i
export function useFileUpload() {
const extractionStore = useExtractionStore()
const uiStore = useUiStore()
const chosenFiles = ref([])
const isDragOver = ref(false)
@ -87,39 +87,34 @@ export function useFileUpload() {
}
/**
* Restores every document from the last session's batch, if any,
* before any file is chosen - one shared banner for the whole batch,
* not one per document. A restored document's source-preview stays
* unavailable (previewUrl: null) until that specific file is dropped
* again - same documented limitation the single-document version had,
* just per-document now instead of singular.
* Loads every document the logged-in user owns from PocketBase,
* newest first - called once on mount (see ExtractorView.vue), which
* only ever happens once already authenticated (App.vue's auth gate
* doesn't render this view at all until then), so there's no need to
* separately watch for a login event. Unlike the old localStorage-only
* version, a document's source-preview DOES come back now
* (documentsService.sourceFileUrl, backed by R2) - this was a real,
* previously-accepted gap ("re-select the file to see it again") that
* having the actual file in PocketBase closes for good.
*/
function restoreOnLoad() {
const keys = extractionService.lastBatchKeys()
let restoredCount = 0
for (const key of keys) {
const restored = extractionService.restoreResult(key)
if (!restored) continue
async function loadDocuments() {
const records = await documentsService.listDocuments()
for (const record of records) {
extractionStore.addDocument({
docKey: key,
fileName: restored.fileName || 'Restored document',
previewUrl: null,
isImage: false,
result: restored.result,
pbId: record.id,
docKey: record.docKey,
fileName: record.fileName,
previewUrl: documentsService.sourceFileUrl(record),
isImage: IMAGE_FILE_RE.test(record.fileName),
result: record.result,
openingBalanceInput: record.openingBalanceInput,
closingBalanceInput: record.closingBalanceInput,
})
restoredCount++
}
if (restoredCount > 0) {
const plural = restoredCount === 1 ? '' : 's'
uiStore.showRestoreBanner(
`Restored ${restoredCount} document${plural} from your last session - re-select the matching source file${plural} above to view ${restoredCount === 1 ? 'it' : 'them'} alongside the data again.`
)
uiStore.resultExpanded = false
}
}
return {
chosenFiles, isDragOver,
setFiles, removeChosenFile, clearChosenFiles, onFileInputChange, onDragOver, onDragLeave, onDrop, restoreOnLoad,
setFiles, removeChosenFile, clearChosenFiles, onFileInputChange, onDragOver, onDragLeave, onDrop, loadDocuments,
}
}

View File

@ -9,6 +9,7 @@
import { ref, reactive } from 'vue'
import { useExtractionStore } from '../stores/extractionStore'
import * as extractionService from '../services/extractionService'
import * as documentsService from '../services/documentsService'
import { fmtNum, parseNum } from '../services/formatService'
export function useRowEditing(index) {
@ -45,7 +46,7 @@ export function useRowEditing(index) {
/**
* Commits the draft to the store, re-renders from the saved data
* (picking up comma formatting), persists to localStorage, and
* (picking up comma formatting), persists to PocketBase, and
* re-checks - clearing a flag (or raising one) right after a fix, the
* same as the Download button, which uses the same recheck logic
* server-side to keep the export consistent with saved edits.
@ -60,11 +61,13 @@ export function useRowEditing(index) {
})
wasEdited.value = true
isEditing.value = false
extractionService.persistResult(
extractionStore.currentDocKey,
extractionStore.currentResult,
extractionStore.activeDocument?.fileName,
)
try {
await documentsService.updateDocument(extractionStore.activeDocument.pbId, {
result: extractionStore.currentResult,
})
} catch (e) {
extractionStore.setError('Could not save the edit: ' + e.message)
}
try {
const checkResult = await extractionService.recheck(

View File

@ -10,6 +10,6 @@
*/
import PocketBase from 'pocketbase'
const POCKETBASE_URL = import.meta.env.VITE_POCKETBASE_URL || 'http://localhost:8090'
const POCKETBASE_URL = import.meta.env?.VITE_POCKETBASE_URL || 'http://localhost:8090'
export const pb = new PocketBase(POCKETBASE_URL)

View File

@ -0,0 +1,70 @@
/**
* Business logic for persisting/restoring processed statements in
* PocketBase - replaces extractionService.js's old localStorage-backed
* persistResult/restoreResult/lastBatchKeys/appendToLastBatch/
* startNewBatch/discardPersisted, which no longer exist (one source of
* truth, not two silently-diverging ones).
*/
import { pb } from '../repositories/pocketbaseRepository'
import * as projectsService from './projectsService'
/**
* Creates a new documents record for the logged-in user. Always called
* with the original File (every extraction has one) - uploaded as
* sourceFile via multipart form data, which PocketBase stores in R2
* once pocketbase/configure-secrets.sh has run (see CLAUDE.md). project
* defaults to the user's "General" project when the caller doesn't pass
* one explicitly - true for every call site until Stage B.3's sidebar
* lets the user pick a different active project first.
*/
export async function saveDocument({
docKey, fileName, sourceFile, result, project,
openingBalanceInput, closingBalanceInput,
}) {
const projectId = project || (await projectsService.getDefaultProject()).id
const formData = new FormData()
formData.append('owner', pb.authStore.record.id)
formData.append('project', projectId)
formData.append('docKey', docKey)
formData.append('fileName', fileName)
// FormData values are strings/Blobs only - the JSON field has to be
// stringified here (confirmed necessary via a real curl test; a plain
// JSON PATCH body, used by updateDocument below, does NOT need this -
// PocketBase accepts a native nested object there instead).
formData.append('result', JSON.stringify(result))
if (openingBalanceInput) formData.append('openingBalanceInput', openingBalanceInput)
if (closingBalanceInput) formData.append('closingBalanceInput', closingBalanceInput)
formData.append('sourceFile', sourceFile)
return pb.collection('documents').create(formData)
}
/**
* Updates an existing document's result (e.g. after a row edit) - no
* sourceFile re-upload, so this goes through as a plain JSON body, not
* multipart - confirmed via a real curl test that PocketBase accepts
* `result` as a native object in that case, unlike the FormData path.
*/
export async function updateDocument(id, { result }) {
return pb.collection('documents').update(id, { result })
}
/** The logged-in user's own documents, optionally filtered to one project, newest first. */
export async function listDocuments({ project } = {}) {
const options = { sort: '-created' }
// Omit `filter` entirely when there's nothing to filter by - PocketBase
// rejects an empty-string filter outright (confirmed via a real 400,
// not assumed), it isn't treated as "no filter."
if (project) options.filter = `project = "${project}"`
return pb.collection('documents').getFullList(options)
}
export async function deleteDocument(id) {
return pb.collection('documents').delete(id)
}
/** A servable URL for a document record's original source file, or null if none was uploaded. */
export function sourceFileUrl(record) {
return record.sourceFile ? pb.files.getURL(record, record.sourceFile) : null
}

View File

@ -1,86 +1,21 @@
/**
* Business logic for extracting, persisting, and re-checking a statement -
* calls repositories only, never touches fetch()/localStorage directly.
* Business logic for extracting and re-checking a statement - calls
* repositories only, never touches fetch() directly. Document
* persistence itself (what used to live here, localStorage-backed)
* moved to documentsService.js/PocketBase - see CLAUDE.md's "PocketBase"
* entry for the full migration record.
*/
import * as extractionRepository from '../repositories/extractionRepository'
import * as localStorageRepository from '../repositories/localStorageRepository'
// Replaces the old single LAST_DOC_KEY pointer now that a session can
// restore a whole BATCH of documents, not just one - an array of
// docKeys, appended to as each document in a batch finishes (see
// appendToLastBatch/startNewBatch below).
const LAST_BATCH_KEYS = 'bse:last_batch_keys'
/**
* The localStorage key for one source file's result - keyed by the
* SOURCE file's own name+size (stable across re-selecting the same file
* after a crash), not the server's randomly-generated output filename,
* which changes every run even for the same source document.
* The docKey for one source file - keyed by the SOURCE file's own
* name+size (stable across re-selecting the same file), used as
* documentsService's own docKey field, not a localStorage key anymore.
*/
export function docKeyFor(file) {
return 'bse:doc:' + file.name + ':' + file.size
}
/**
* Saves a result (+ its source file's own name, so a restored multi-
* document batch can show which file is which) under its doc key. Does
* NOT touch the last-batch-keys list itself - see appendToLastBatch,
* a separate, explicit step so a row-edit save (which also calls this)
* doesn't need to reason about batch membership at all.
*/
export function persistResult(docKey, result, fileName) {
if (!docKey || !result) return
localStorageRepository.setItem(docKey, JSON.stringify({ fileName: fileName || null, result }))
}
/** A previously-persisted {fileName, result} for a doc key, or null if none/corrupt. */
export function restoreResult(docKey) {
const saved = localStorageRepository.getItem(docKey)
if (!saved) return null
try {
const parsed = JSON.parse(saved)
if (parsed && typeof parsed === 'object' && 'result' in parsed) {
return { fileName: parsed.fileName || null, result: parsed.result }
}
// Legacy shape from before multi-document support, where the saved
// blob WAS the result itself - still restorable, just with no
// filename to show.
return { fileName: null, result: parsed }
} catch (e) {
return null
}
}
/** The docKeys from the most recently viewed batch, for restore-on-load. */
export function lastBatchKeys() {
const saved = localStorageRepository.getItem(LAST_BATCH_KEYS)
if (!saved) return []
try {
const parsed = JSON.parse(saved)
return Array.isArray(parsed) ? parsed : []
} catch (e) {
return []
}
}
/** Appends one docKey to the last-batch list (a no-op if already present). */
export function appendToLastBatch(docKey) {
const keys = lastBatchKeys()
if (!keys.includes(docKey)) {
keys.push(docKey)
localStorageRepository.setItem(LAST_BATCH_KEYS, JSON.stringify(keys))
}
}
/** Clears the last-batch list - called once when a new Extract click begins, so an old finished batch doesn't bleed into the new one's restore list. */
export function startNewBatch() {
localStorageRepository.setItem(LAST_BATCH_KEYS, JSON.stringify([]))
}
export function discardPersisted(docKey) {
if (docKey) localStorageRepository.removeItem(docKey)
}
/**
* Whatever the user typed always wins; an intentionally blank field (no
* auto-fill, per the UI's own calculated-balance readouts) falls back to

View File

@ -0,0 +1,21 @@
/**
* Minimal for now - just enough for documentsService to resolve a
* default project id. Stage B.3 extends this with full CRUD
* (createProject/renameProject/deleteProject) for the actual sidebar UI.
*
* No caching here, deliberately: a module-level cache would leak across
* a logout/login within the same page session (user B would get user
* A's cached "default project" id) - this is a local PocketBase
* instance, the extra round trip is cheap, correctness wins.
*/
import { pb } from '../repositories/pocketbaseRepository'
/** The logged-in user's auto-created "General" project - pb_hooks/ensure_default_project.pb.js guarantees exactly one exists. */
export async function getDefaultProject() {
return pb.collection('projects').getFirstListItem('isDefault=true')
}
/** The logged-in user's own projects, default first. */
export async function listProjects() {
return pb.collection('projects').getFullList({ sort: '-isDefault,name' })
}

View File

@ -1,11 +1,12 @@
/**
* Global state for every loaded statement result - a list of documents
* (each the full server response plus its own balance-input text and
* flagged-row set) rather than a single one, so multiple files from one
* upload batch (or restored from a client project) can coexist and be
* browsed via activeIndex. Kept as one cohesive array of
* mostly-server-shaped objects rather than over-normalized, same
* discipline the old single-document shape had.
* (each the full server response plus its own PocketBase record id,
* balance-input text, and flagged-row set) rather than a single one, so
* multiple files from one upload batch (or restored from a client
* project) can coexist and be browsed via activeIndex. pbId is what
* documentsService.updateDocument targets for a row-edit save. 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'
@ -50,10 +51,10 @@ export const useExtractionStore = defineStore('extraction', {
pendingOpeningBalance: '',
pendingClosingBalance: '',
// Batch-progress fields live here, not in a composable-local ref -
// ephemeral like everything else in this store besides the explicit
// persistResult calls, and being store state (not composable-local)
// is what lets ResultCard's Download All button react to
// isBatchProcessing without a prop from a sibling component.
// ephemeral, never itself written to PocketBase (only `documents`'
// own fields are, via documentsService), and being store state (not
// composable-local) is what lets ResultCard's Download All button
// react to isBatchProcessing without a prop from a sibling component.
isBatchProcessing: false,
batchTotal: 0,
batchCurrentIndex: 0,
@ -109,10 +110,10 @@ export const useExtractionStore = defineStore('extraction', {
* focus stays elsewhere would otherwise never get its own flags
* computed at all - nothing re-triggers it later on prev/next either.
*/
addDocument({ docKey, fileName, previewUrl, isImage, result, openingBalanceInput, closingBalanceInput }) {
addDocument({ pbId, docKey, fileName, previewUrl, isImage, result, openingBalanceInput, closingBalanceInput }) {
const wasEmpty = this.documents.length === 0
this.documents.push({
docKey, fileName, previewUrl, isImage, result,
pbId, docKey, fileName, previewUrl, isImage, result,
flaggedIndexes: computeFlags(result),
openingBalanceInput: openingBalanceInput || '',
closingBalanceInput: closingBalanceInput || '',

View File

@ -10,8 +10,6 @@ export const useUiStore = defineStore('ui', {
resultExpanded: false,
pdfColHidden: false,
pdfColWidthPct: 40, // matches .pdf-col's own CSS default (flex: 0 0 40%)
restoreBannerVisible: false,
restoreBannerText: '',
/**
* Bumped whenever the transactions column's available width changes
* (the Hide/Show toggle, or a resize-drag ending) - every
@ -32,12 +30,5 @@ export const useUiStore = defineStore('ui', {
bumpLayout() {
this.layoutVersion++
},
showRestoreBanner(text) {
this.restoreBannerText = text
this.restoreBannerVisible = true
},
hideRestoreBanner() {
this.restoreBannerVisible = false
},
},
})

View File

@ -13,7 +13,6 @@ import { useExtractionStore } from '../stores/extractionStore'
import { useFileUpload } from '../composables/useFileUpload'
import { useBatchExtraction } from '../composables/useBatchExtraction'
import FileUploadZone from '../components/FileUploadZone.vue'
import RestoreBanner from '../components/RestoreBanner.vue'
import ResultCard from '../components/ResultCard.vue'
import ResizablePanels from '../components/ResizablePanels.vue'
import SourceDocumentPanel from '../components/SourceDocumentPanel.vue'
@ -22,7 +21,7 @@ import TransactionsTable from '../components/TransactionsTable.vue'
const extractionStore = useExtractionStore()
const {
chosenFiles, isDragOver,
removeChosenFile, clearChosenFiles, onFileInputChange, onDragOver, onDragLeave, onDrop, restoreOnLoad,
removeChosenFile, clearChosenFiles, onFileInputChange, onDragOver, onDragLeave, onDrop, loadDocuments,
} = useFileUpload()
const { isProcessing, phaseText, runBatch } = useBatchExtraction()
@ -46,7 +45,7 @@ function handleExtract() {
runBatch(files, extractionStore.pendingOpeningBalance, extractionStore.pendingClosingBalance)
}
onMounted(restoreOnLoad)
onMounted(loadDocuments)
</script>
<template>
@ -72,10 +71,7 @@ onMounted(restoreOnLoad)
@extract="handleExtract"
/>
<div v-if="extractionStore.documents.length > 0">
<RestoreBanner />
<ResultCard />
</div>
<ResultCard v-if="extractionStore.documents.length > 0" />
<!--
Source Document and Transactions (and the opening/closing balance

View File

@ -0,0 +1,26 @@
/// <reference path="../pb_data/types.d.ts" />
/**
* projects/documents came out of migration 1 with no created/updated
* fields at all - confirmed for real (not assumed): documentsService's
* own `sort: '-created'` failed with a generic 400 against the live
* collection, traced down to the field simply not existing (the `users`
* auth collection has one built in; a plain base collection doesn't
* unless declared explicitly). Field syntax below copied from `users`'
* own `created`/`updated` fields via the REST API, not guessed.
*/
migrate((app) => {
for (const name of ['projects', 'documents']) {
let collection = app.findCollectionByNameOrId(name)
collection.fields.add(new Field({ type: 'autodate', name: 'created', onCreate: true, onUpdate: false }))
collection.fields.add(new Field({ type: 'autodate', name: 'updated', onCreate: true, onUpdate: true }))
app.save(collection)
}
}, (app) => {
for (const name of ['projects', 'documents']) {
let collection = app.findCollectionByNameOrId(name)
collection.fields.removeByName('created')
collection.fields.removeByName('updated')
app.save(collection)
}
})