Add usage tracking foundation: usageEvents + a visible pages-counter
The first piece of a stated future billing model, scoped to exactly this: a visible "pages this month" counter and the raw data recording behind it - not plan enforcement, payment processing, or the described pause/resume billing-cycle logic itself. New append-only/immutable usageEvents collection (pb_migrations/13); one event recorded per successfully delivered extraction (result.page_reports.length), not a Preview click. "This period" is explicitly the calendar month - a placeholder until a real subscription/plan record exists to anchor a custom cycle against. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
parent
206f78979b
commit
37ab655494
|
|
@ -12,10 +12,12 @@
|
||||||
import { ref, onMounted, onUnmounted } from 'vue'
|
import { ref, onMounted, onUnmounted } from 'vue'
|
||||||
import { useAuthStore } from '../stores/authStore'
|
import { useAuthStore } from '../stores/authStore'
|
||||||
import { useProjectsStore } from '../stores/projectsStore'
|
import { useProjectsStore } from '../stores/projectsStore'
|
||||||
|
import { useUsageStore } from '../stores/usageStore'
|
||||||
import * as authService from '../services/authService'
|
import * as authService from '../services/authService'
|
||||||
|
|
||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
const projectsStore = useProjectsStore()
|
const projectsStore = useProjectsStore()
|
||||||
|
const usageStore = useUsageStore()
|
||||||
|
|
||||||
const menuOpen = ref(false)
|
const menuOpen = ref(false)
|
||||||
const menuRef = ref(null)
|
const menuRef = ref(null)
|
||||||
|
|
@ -30,7 +32,14 @@ function handleOutsideClick(e) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => window.addEventListener('click', handleOutsideClick))
|
onMounted(() => {
|
||||||
|
window.addEventListener('click', handleOutsideClick)
|
||||||
|
// Billing/usage-tracking foundation - loaded once here (the one place
|
||||||
|
// in the app this counter is actually shown) rather than in App.vue's
|
||||||
|
// own onMounted alongside projects/documents, since nothing else in
|
||||||
|
// the app currently needs this value loaded ahead of time.
|
||||||
|
usageStore.loadUsage()
|
||||||
|
})
|
||||||
onUnmounted(() => window.removeEventListener('click', handleOutsideClick))
|
onUnmounted(() => window.removeEventListener('click', handleOutsideClick))
|
||||||
|
|
||||||
function handleSignOut() {
|
function handleSignOut() {
|
||||||
|
|
@ -59,13 +68,21 @@ function handleSignOut() {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="app-header-right">
|
<div class="app-header-right">
|
||||||
<!-- Layout mapper work (L.7) - the Layouts page lists every saved
|
<!--
|
||||||
column mapping (own + shared), with usage/failure stats,
|
Billing/usage-tracking foundation - moved here (top-right, where
|
||||||
version history, and the ability to edit/retire one. -->
|
the Layouts nav link used to be - removed per explicit request)
|
||||||
<RouterLink to="/layouts" class="app-nav-link" active-class="app-nav-link-active">
|
from its original top-left spot next to the logo. A visible
|
||||||
<i class="fa-solid fa-table-cells-large"></i>
|
running count of pages extracted this period (currently the
|
||||||
Layouts
|
calendar month - see usageStore.js's own docstring for why
|
||||||
</RouterLink>
|
that's a placeholder, not yet the real pause/resume-aware
|
||||||
|
billing cycle). No quota/limit is shown alongside it yet since
|
||||||
|
no plan system exists to compare against - just the raw count,
|
||||||
|
per the original explicit ask.
|
||||||
|
-->
|
||||||
|
<div class="app-usage-badge" title="Pages extracted this month">
|
||||||
|
<i class="fa-solid fa-file-lines"></i>
|
||||||
|
<span>{{ usageStore.pagesThisPeriod }} page{{ usageStore.pagesThisPeriod === 1 ? '' : 's' }} this month</span>
|
||||||
|
</div>
|
||||||
<div ref="menuRef" class="app-account">
|
<div ref="menuRef" class="app-account">
|
||||||
<button type="button" class="app-account-trigger" @click="toggleMenu">
|
<button type="button" class="app-account-trigger" @click="toggleMenu">
|
||||||
<span class="app-avatar"><i class="fa-solid fa-user"></i></span>
|
<span class="app-avatar"><i class="fa-solid fa-user"></i></span>
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,56 @@
|
||||||
|
/**
|
||||||
|
* Foundation for billing/usage tracking - see pocketbase/pb_migrations/
|
||||||
|
* 13_add_usage_events.js for the full reasoning and CLAUDE.md's "Usage
|
||||||
|
* tracking foundation" entry for the design record. No plan/quota logic
|
||||||
|
* lives here yet (free tier, page packs, subscriptions with pause/resume
|
||||||
|
* are all still just a stated intent) - this is purely the raw
|
||||||
|
* record/read layer a later billing feature will build on.
|
||||||
|
*/
|
||||||
|
import { pb } from '../repositories/pocketbaseRepository'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs one usage event for the logged-in user - called once per
|
||||||
|
* successfully DELIVERED extraction (a result the user actually gets,
|
||||||
|
* not a Preview dry run - see usageStore.js's own call sites for exactly
|
||||||
|
* where). `documentId` is optional (a usage event with no
|
||||||
|
* still-existing document is still a valid, billable record).
|
||||||
|
*/
|
||||||
|
export async function recordUsage({ documentId, pages }) {
|
||||||
|
return pb.collection('usageEvents').create({
|
||||||
|
owner: pb.authStore.record.id,
|
||||||
|
document: documentId || null,
|
||||||
|
pages,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sums `pages` across every usage event created at or after `since` for
|
||||||
|
* the logged-in user - PocketBase has no server-side SUM aggregate, so
|
||||||
|
* this fetches the (normally small) list of this period's own events and
|
||||||
|
* reduces client-side, same approach the near-match comparator and
|
||||||
|
* categorization matching already take for "no backend logic needed for
|
||||||
|
* this" client-side computation in this app.
|
||||||
|
*
|
||||||
|
* `since` is normalized from a plain ISO string ("T" separator) to
|
||||||
|
* PocketBase's own stored `created` format (a literal space separator,
|
||||||
|
* e.g. "2026-11-16 12:14:07.962Z") before being used in the filter - a
|
||||||
|
* REAL bug found by this stage's own end-to-end testing, not assumed
|
||||||
|
* safe from the filter syntax alone: PocketBase's date filter comparison
|
||||||
|
* appears to compare the filter value against the stored one as a plain
|
||||||
|
* STRING when their formats differ, and " " sorts before "T"
|
||||||
|
* lexicographically - so a same-day cutoff like "2026-11-16T11:00" was
|
||||||
|
* silently evaluating as GREATER than a later stored value like
|
||||||
|
* "2026-11-16 12:00" (the space loses to the T at the first differing
|
||||||
|
* character), making `getPagesSince` return 0 for any cutoff on the
|
||||||
|
* same calendar day as the events it should have matched. Confirmed by
|
||||||
|
* directly bisecting cutoffs (1 minute/1 hour/1 day ago, and the exact
|
||||||
|
* stored value) against the real running PocketBase before fixing this,
|
||||||
|
* not guessed at from the symptom alone.
|
||||||
|
*/
|
||||||
|
export async function getPagesSince(since) {
|
||||||
|
const normalized = since.replace('T', ' ')
|
||||||
|
const events = await pb.collection('usageEvents').getFullList({
|
||||||
|
filter: `created >= "${normalized}"`,
|
||||||
|
})
|
||||||
|
return events.reduce((sum, e) => sum + (e.pages || 0), 0)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,70 @@
|
||||||
|
/**
|
||||||
|
* Foundation for billing/usage tracking - holds the live "pages used
|
||||||
|
* this period" count AppHeader.vue's own counter badge displays, kept
|
||||||
|
* here (not a component-local ref) so it can react the instant
|
||||||
|
* useBatchExtraction.js/ManualMappingView.vue record a new extraction
|
||||||
|
* elsewhere in the component tree, the same cross-component-reactivity
|
||||||
|
* reason uiStore/extractionStore already exist as stores rather than
|
||||||
|
* local state. See CLAUDE.md's "Usage tracking foundation" entry for the
|
||||||
|
* full design record.
|
||||||
|
*
|
||||||
|
* "This period" is the current CALENDAR month (resets the 1st) -
|
||||||
|
* explicitly a placeholder, not the real billing-cycle semantics the
|
||||||
|
* user has described (a subscription period that can be paused mid-
|
||||||
|
* month and resumes counting from where it left off, not a fresh
|
||||||
|
* calendar month). That needs a real subscription/plan record to anchor
|
||||||
|
* a custom cycle against, which doesn't exist yet - this store's own
|
||||||
|
* `periodStart`/`loadUsage` is the one place that logic will need to
|
||||||
|
* change later; nothing else in this app needs to know how "the current
|
||||||
|
* period" is actually defined.
|
||||||
|
*/
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import * as usageService from '../services/usageService'
|
||||||
|
|
||||||
|
/** The start of the current calendar month, as a PocketBase-filter-compatible UTC timestamp string. */
|
||||||
|
function currentPeriodStart() {
|
||||||
|
const now = new Date()
|
||||||
|
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useUsageStore = defineStore('usage', {
|
||||||
|
state: () => ({
|
||||||
|
pagesThisPeriod: 0,
|
||||||
|
loaded: false,
|
||||||
|
}),
|
||||||
|
actions: {
|
||||||
|
/** Fetches and sums this period's own usage events - called once on app load (AppHeader.vue's own onMounted). */
|
||||||
|
async loadUsage() {
|
||||||
|
try {
|
||||||
|
this.pagesThisPeriod = await usageService.getPagesSince(currentPeriodStart())
|
||||||
|
this.loaded = true
|
||||||
|
} catch (e) {
|
||||||
|
// Best-effort - a failed usage load shouldn't block anything
|
||||||
|
// else in the app; the counter just stays at its last-known
|
||||||
|
// value (0 if this is the first load).
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logs one extraction's own page count and optimistically bumps the
|
||||||
|
* local counter immediately, rather than re-querying the full sum
|
||||||
|
* after every single extraction (cheap for one event, wasteful N
|
||||||
|
* times in a batch upload). `pages` is whatever the caller already
|
||||||
|
* has on hand (`result.page_reports.length`) - this store doesn't
|
||||||
|
* reach into a result object itself, keeping it agnostic to the
|
||||||
|
* extraction result's own shape.
|
||||||
|
*/
|
||||||
|
async recordExtraction(documentId, pages) {
|
||||||
|
if (!pages) return
|
||||||
|
try {
|
||||||
|
await usageService.recordUsage({ documentId, pages })
|
||||||
|
this.pagesThisPeriod += pages
|
||||||
|
} catch (e) {
|
||||||
|
// Best-effort, same discipline as every other non-critical
|
||||||
|
// persistence call in this app (e.g. saveExportFile) - a failed
|
||||||
|
// usage log shouldn't undo or block the extraction the user
|
||||||
|
// actually asked for and already has in front of them.
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
/// <reference path="../pb_data/types.d.ts" />
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Foundation for billing/usage tracking - a real plan hasn't been designed
|
||||||
|
* or built yet (free tier, one-time page packs, subscription tiers with
|
||||||
|
* pause/resume - all still just a stated intent, not implemented), but
|
||||||
|
* the raw usage DATA has to start being recorded now so nothing is lost
|
||||||
|
* once that plan exists. `usageEvents` is a deliberately simple, append-
|
||||||
|
* only log - one record per successfully DELIVERED extraction (a result
|
||||||
|
* the user actually gets to see/save, not a ManualMappingView.vue
|
||||||
|
* Preview click, which costs real backend compute too but isn't a
|
||||||
|
* billable deliverable - see CLAUDE.md's "Usage tracking foundation"
|
||||||
|
* entry for the full reasoning), each carrying how many PAGES that
|
||||||
|
* extraction processed (`result.page_reports.length` - the one field
|
||||||
|
* populated identically across every extraction path: dual-engine text
|
||||||
|
* PDF, OCR-only, and a forced-mapping retry).
|
||||||
|
*
|
||||||
|
* `document` is optional (not every future usage event will necessarily
|
||||||
|
* trace back to one - e.g. a later API-key-based integration) but set on
|
||||||
|
* every event this app itself ever creates, for support/audit purposes.
|
||||||
|
*
|
||||||
|
* Deliberately immutable (`updateRule`/`deleteRule` both `null`,
|
||||||
|
* superuser-only) - same pattern `layoutMappingVersions` already
|
||||||
|
* established for append-only history - a usage record is the one thing
|
||||||
|
* in this schema that must never be editable or deletable by its own
|
||||||
|
* owner, or a free-tier limit becomes trivially gameable.
|
||||||
|
*/
|
||||||
|
migrate((app) => {
|
||||||
|
let users = app.findCollectionByNameOrId('users')
|
||||||
|
let documents = app.findCollectionByNameOrId('documents')
|
||||||
|
|
||||||
|
let usageEvents = new Collection({
|
||||||
|
type: 'base',
|
||||||
|
name: 'usageEvents',
|
||||||
|
listRule: 'owner = @request.auth.id',
|
||||||
|
viewRule: 'owner = @request.auth.id',
|
||||||
|
createRule: 'owner = @request.auth.id',
|
||||||
|
updateRule: null,
|
||||||
|
deleteRule: null,
|
||||||
|
fields: [
|
||||||
|
{ type: 'relation', name: 'owner', collectionId: users.id, required: true, maxSelect: 1 },
|
||||||
|
{ type: 'relation', name: 'document', collectionId: documents.id, maxSelect: 1 },
|
||||||
|
{ type: 'number', name: 'pages', required: true },
|
||||||
|
{ type: 'autodate', name: 'created', onCreate: true },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
app.save(usageEvents)
|
||||||
|
}, (app) => {
|
||||||
|
try { app.delete(app.findCollectionByNameOrId('usageEvents')) } catch (e) {}
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue