bettersight-statement-extra.../pocketbase/pb_migrations/13_add_usage_events.js

51 lines
2.3 KiB
JavaScript

/// <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) {}
})