Lucid — Full Functional Report A from-scratch account of what the app does, why it…
- User
Lucid — Full Functional Report
A from-scratch account of what the app does, why it exists, how it is built, and every functional system inside it. Deliberately excludes UI/visual/styling; this is about behaviour, data, and logic only. App version 3.4.
1. What Lucid is
Lucid is a personal and family finance tracker delivered as a Progressive Web App (PWA). It records income and expenses, groups them into accounts and categories, tracks budgets, recurring bills, and savings goals, and turns the data into analytics. It can run completely offline on a single device, or sync a shared ledger across a whole family — all without Lucid operating any server of its own.
The defining architectural choice is that the user owns their data end to end. Data lives either only on the user's device, or inside a Google Sheet in the user's own Google Drive. Lucid the company never stores or sees the data.
2. Why it was built (goals and principles)
- Privacy by ownership. No Lucid backend means no central database to breach, sell, or monetise. Data sits in the user's device or their own Google account.
- Zero running cost / "free forever" for the core. Because there is no server to pay for, the core product can be free indefinitely. Paid features are reserved for things that genuinely incur cost (real AI, hosted bank connections).
- Works anywhere, including offline. A finance app must be usable on a train with no signal; every write is designed to survive being offline and replay later.
- Low-friction capture. The faster a transaction is logged, the more likely people keep using it — hence smart auto-categorization, quick-adds, recurring automation, and (on Android, planned) reading bank alerts automatically.
- Family-shareable without a login system. Multiple people share one ledger via an invite link plus lightweight per-person PINs, rather than a full accounts/auth backend.
- Encouraging, never shaming. Behavioural features reward engagement, never punish spending.
3. How it is built (architecture)
Front end: A single-page PWA composed of 7 deployed files —
index.html,app.js(the entire application logic, ~5,000 lines),styles.css,sw.js(service worker), and three icon images. No framework; plain JavaScript with direct DOM manipulation and a single global state objectS."Backend" (optional): For cloud/family mode, the data store is a Google Sheet owned by the user. A Google Apps Script Web App (its source lives as the
SCRIPT_CODEstring insideapp.js) is deployed onto that Sheet and acts as a tiny REST-like API. The Sheet has tabs for Transactions, Accounts, Members, Recurring, Budgets, and Settings. The Apps Script exposes exactly 15 actions (see §6). There is no other server anywhere.Three storage backends historically existed; two remain:
- Local ("this device") — data in
localStorage, no network, no account. - Google Sheets — data in the user's Sheet via the Apps Script Web App.
- Firebase — removed. Any device still flagged
firebaseis routed back to setup to re-choose Local or Sheets; its local cache is preserved.
Identity of records: Every record (transaction, account, etc.) has a client-generated unique
id(e.g.tx_<timestamp>). Records also carry ats(millisecond timestamp) used for conflict resolution.Internal naming note: All persisted keys are prefixed
prizm_(the app's former name) and are deliberately kept that way so existing users' data is never broken. Function names were renamed to Lucid.
4. Data model
The app holds all live data in one in-memory state object
S, hydrated from cache on launch and (in cloud mode) refreshed from the Sheet. The persistent data types:- Transactions —
{id, date, description, amount, type (income|expense), category, account, notes, memberId, ts}. Category may be a "packed" subcategory string (see §9). - Accounts —
{id, name, type, balance}. Types: Checking, Savings, Credit, Cash, Investment, Crypto, Other. - Members (family) —
{id, name, pin (hashed), color}. - Recurring —
{id, name, amount, type, category, account, frequency, nextDate, memberId, active}. - Budgets —
{id, category, limit}. - Settings — a key/value store (currency, name, familyName, familyAdmin, shared password, and synced preferences).
Alongside these, ~50
localStoragekeys hold preferences and machine state (theme, accent, icon mode, currency, learned merchant memory, goals, subcategories, starred quick-adds, outbox queue, milestone history, Pro entitlement, etc.).
5. Storage, offline behaviour, and the sync engine
This is the most engineered part of the app, because "no server + must work offline + can be multi-user" is a hard combination.
- Optimistic local-first writes. Every change is applied to the in-memory state and the local cache immediately, so the UI never waits on the network.
- Durable outbox. In Sheets mode, each write is also enqueued into a persistent
outbox (
prizm_outboxin localStorage). A flush loop drains it to the Apps Script Web App. If the app is offline or closed mid-sync, the queued writes survive and are replayed on reconnect — so an import or an edit can never be silently lost. - Adaptive background polling. In Sheets mode a poll loop reads the whole Sheet, backing off from every 8s (while things are changing) to every 60s (when idle), and pausing entirely while the tab is hidden. Any detected remote change snaps the interval back to 8s.
- Change detection. A signature (
_lastRemoteSig) hashes the full remote dataset; if it is unchanged, the app skips re-rendering entirely. - Write-settle guard. Background sync is suppressed for ~4 seconds after a local write lands (and while any write is in-flight or queued), so a slightly-stale read can't overwrite a change the user just made.
- Preference sync. User preferences (categories, theme, accent, icon mode, simple mode,
subcategories, learned merchants, starred quick-adds, hero settings, Pro/entitlement-adjacent
keys, etc.) are pushed to the Settings tab via
updateSettings, with a short "dirty window" that stops an incoming sync from clobbering a preference the user just changed. - Conflict handling for records. Each record carries a
ts; the backend compares timestamps so the newer write wins, preventing two devices from stomping each other. - Query-string bypass. The service worker never caches any request carrying a query string, and never touches Google/auth hosts — so live data reads/writes are never served stale.
Service worker (PWA offline + updates)
- Caches the app shell for offline launch.
- HTML is network-first (always fresh when online, cached fallback offline).
- Code files (JS/CSS) are network-first so a new build appears on next launch (this was changed from cache-first, which had been serving stale code).
- Static assets (icons) are cache-first with background refresh.
- A versioned cache (
CACHE_VERSION) purges old caches on every release, and the app auto-reloads once when a new service worker takes control, so updates apply without the user manually clearing anything.
6. Backend API (Google Apps Script) — the 15 actions
The Sheet-side Web App implements exactly these operations, each reading/writing a specific tab and returning
{success:true}or an error:addTransaction,updateTransaction,deleteTx,addAccount,updateAccount,deleteAccount,addMember,deleteMember,addRecurring,updateRecurring,deleteRecurring,setBudget,deleteBudget,updateSettings,setSecret.Plus a read action (
getAll) that returns the entire dataset.updateSettingsis a generic key/value writer (used for name, currency, family name, family admin, and all synced prefs).setSecretsets/changes/removes the shared password and requires the current password to change an existing one.
7. Authentication, access, and identity
Lucid has no traditional user accounts. "Auth" is three separate, lightweight mechanisms:
- Google sign-in (automatic Sheet setup). Uses Google Identity Services to get a token,
then programmatically: creates a Spreadsheet, installs the
SCRIPT_CODEbackend into it as an Apps Script project, publishes it as a Web App set to "anyone", and captures the resulting URL — a fully automated cloud setup. Requires the user to grant scopes and do a one-time Google authorization. Falls back to manual setup if Google's Apps Script API is disabled for that account. - Manual Sheet connection. The user copies a template Sheet, deploys the Web App themselves, and pastes the URL. Same result without in-app Google sign-in.
- Local only. No account at all; data stays on device.
Family member identity: Each family member has a name, a color, and a 4-digit PIN that is hashed (not stored in plaintext) via the Web Crypto API. On launch of a family ledger, the user selects their profile and enters their PIN to "become" that member; their
memberIdtags the transactions they add.Shared password (optional). A whole family ledger can be locked with an optional shared password (
setSecret), sent as an auth key (authK) on every read/write so only people who know it can access the Sheet. It is deliberately optional and off by default.Family admin. The admin manages shared settings (budgets, income tracking, invites, member removal). Admin is stored as a synced
familyAdminsetting (with a legacy fallback to "whoever created the family = first member"), and can be transferred to another member, which round-trips across the whole family through the existing settings sync — no backend change needed.
8. Onboarding flow (logic)
A staged setup wizard drives first-run configuration and records progress:
- Account type — Personal vs Family (sets
setupContext/family). - Family branch (family only) — Join an existing family (invite link + optional password, connecting with a non-blocking loading state) or Create a new family (name it).
- Storage — Sign in with Google (auto Sheet), use your own Google Sheet (manual), or store on device only. Device-only skips all auth and goes straight into the app.
- Name — captured as its own step; feeds
S.name. - Quick preferences — choose whether to track income (vs spending-only) and a theme.
- Accounts — optional; add accounts and starting balances, or skip (accounts are always editable later).
The join path guards against double-submission (an in-flight lock prevents stacked requests), and a completed profile+PIN is persisted so a reload resumes cleanly rather than bouncing.
9. Categories and subcategories
- Default categories ship for expenses (Food, Transport, Shopping, Health, Entertainment, Bills, Education, Travel, Coffee, Fitness, Home, Other) and income (Salary, Freelance, Business, Investment, Rental, Other).
- User-managed lists. Users can add, rename, and remove categories; changes persist and sync across devices. Custom display names and custom icons are stored separately so the underlying key stays stable.
- Subcategories ("Option B"). Detail is stored per base category (e.g. Transport →
Petrol, Rego). When saved on a transaction, the value is packed as a single string
"Category ▸ Subcategory". AbaseCat()helper unpacks the base category everywhere it matters (grouping, budgets, analytics, icons), so subcategories add detail without complicating any of the aggregation logic. Subcategories only surface on the add screen when the chosen category actually has them, keeping simple use simple.
10. Smart auto-categorization engine (on-device, free)
When a description is entered (or a row is imported), Lucid guesses the category:
- Learned merchant memory (frequency-weighted). A normalized merchant key
(
prizm_merchant_cat) maps each merchant to a count per category. The guess is the most frequent category for that merchant, so a single mis-tag can't flip a well-established merchant. Every saved transaction increments the count. - Seed from history. On first run in a ledger, the engine scans the user's entire existing transaction history to populate the memory, so it is smart immediately based on how that user has categorized before.
- Word-overlap fuzzy matching. For a shop it hasn't seen exactly, it scores learned merchants by shared significant words (and falls back to substring containment) to reuse a related category.
- Starter rules. A built-in regex ruleset covers common global/AU/India merchants (supermarkets, fuel, streaming, utilities, pharmacies, gyms, retailers, payroll, etc.) as a fallback before giving up.
The predicted category is pre-selected on the add screen; the user "confirms" simply by saving, and any correction is learned. (A real LLM-based categorizer is planned as a paid upgrade; this on-device engine is the free baseline.)
11. Transactions
Full create/read/update/delete. Each transaction has a type (income/expense), amount, date, category (optionally packed with a subcategory), account, optional note, and — in family mode — the member who logged it. Writes go through the optimistic-local-then-outbox path. Income can be globally turned off ("spending only"), in which case income UI and math are suppressed.
Quick-adds / starred. Frequently used transaction templates can be starred (
prizm_starred) and re-added in one tap; the app also surfaces recent transactions as one-tap repeat options.
12. Accounts, budgets, goals
- Accounts hold a running balance and a type. On the home view, when a time period is selected, each account can show its net movement over that period (income − spend) instead of its running balance, so changing the period re-scopes the whole screen together.
- Budgets are per-category monthly limits. Spending is aggregated by base category and compared to the limit (over/under). Managed by admins in family mode.
- Savings goals (
prizm_goals) are{name, target, saved}with computed progress percentage. Goals only appear when income is being tracked. Reaching a goal's target counts as a milestone (see §16).
13. Recurring transactions
Recurring items (bills or income) carry a frequency (daily / weekly / monthly / yearly) and a
nextDate.- Due review. When items come due, the app can surface them for the user to confirm/post.
- Date advancement with clamping. Monthly/yearly steps clamp to the last valid day of the target month (e.g. Jan 31 → Feb 28/29) and are recomputed each cycle from the item's original target day, so a "31st monthly" item returns to the 31st in longer months instead of drifting to the 28th forever.
- Re-check on focus. Recurring due-status is re-evaluated when the app regains focus and hourly while open, so it doesn't require a restart.
14. Bank statement import (files) + instant-entry parser
A single importer accepts three real bank export formats and funnels them into one pipeline:
- CSV — quoted-field parser, with automatic column mapping (date/amount/description/ category/type/notes detected by header keywords), a manual re-map step, a preview, and date-format inference (with manual override).
- OFX / QFX — parses
STMTTRNblocks whether the file is SGML or XML, using the signed amount as authoritative andTRNTYPEto refine income vs expense. - QIF — parses
D/T/P/M/Lfields and^record separators, including Quicken's apostrophe date format.
Shared import logic across all three:
- Occurrence-counted de-duplication — re-importing an overlapping statement won't double-count, but two genuinely identical purchases (e.g. two coffees the same day) both import, because each existing transaction only "absorbs" one matching row.
- Sign-based typing — where there's no explicit type column, negative = expense, positive = income.
- Auto-categorization — every imported row runs through the §10 engine.
- Offline-safe — imported rows go through the same outbox path, so a large import survives disconnection.
Instant-entry parser (
parseBankSms). A pure, tested function that turns a bank alert ("INR 420 debited … at SWIGGY") into{amount, type, merchant}. It detects debit vs credit keywords, extracts amount across many currency notations, cleans the merchant name, and rejects OTP and balance-only messages. This is the "brain" for instant Android entry; a PWA can't read SMS itself, so wiring it to live texts requires the planned Android wrapper.
15. Analytics
Computed views over the transaction set (all math server-free, in the browser):
- Overview — totals and category composition for the selected scope.
- Trends — spending/income over time.
- Breakdown — by category (and by base category for packed subcategories).
- Insights — derived observations (e.g. a category that rose versus the previous period, or new spending this period).
- Per-member and per-account breakdowns in family/multi-account setups.
- The home hero computes balance (net worth = sum of account balances) plus income and spend for a selectable period (last 7 days / month / year / all time). When income isn't tracked, it shows spending only, to avoid double-counting.
16. Emotional-design layer (wellbeing-safe)
Positive-reinforcement features, engineered to reward engagement and never shame spending:
- Tracking streak — consecutive days with at least one logged transaction, with a yesterday "grace" anchor so it doesn't read as broken before the day ends. Surfaced only once meaningful (2+ days); never nags at zero.
- Milestones — celebrated on crossing transaction-count thresholds (1/10/25/50/100/250/…),
streak lengths (3/7/14/30/60/100 days), or reaching a savings goal. The seen-set
(
prizm_milestones_seen) is seeded silently on first run so the user isn't spammed with a backlog; only future crossings celebrate. - Monthly wrap-up — a dismissible summary of the previous calendar month (income, spent, net, top category, days tracked). The headline is framed positively when the user saved, and neutrally otherwise ("you tracked N days — great awareness"), never "you overspent."
17. Upcoming bills foresight
A forward-looking view lists recurring expenses due within a user-selectable window (7/14/30/60 days) with a running total, so users can see what's about to leave their account. It hides itself when nothing is upcoming.
18. Preferences and personalization (functional switches)
State-affecting preferences (all synced where relevant): currency (12 supported, AUD default), display name, income-tracking on/off, "simple mode" (a reduced feature surface), compact density, corner style, theme, accent colour, icon mode (emoji / line / initials), hero-gradient variant, hero period, and whether the accent recolours the hero. Each persists locally and, in cloud mode, propagates to other devices through the Settings tab.
19. Paywall (Lucid Pro)
A monetization scaffold designed for selling/unlocking on the developer's own website, so no in-app billing backend is required:
- Entitlement — a single
prizm_proflag gates premium behaviour viaisPro(). - Offline unlock codes — the developer's site issues a code after payment; the app
validates it locally with a checksum scheme (
LUCID+ body + 2-char check), so no server call is needed. Random/garbage codes are rejected. (Lightweight by design; upgradeable to server-verified later.) - Feature gating — the four premium features are AI categorizing (LLM), instant bank sync, receipt scanning, and unlimited family/history. The free family tier is capped at 2 members; adding more routes to the upgrade flow. (AI/receipt/instant are not yet built — they are the paid roadmap; the free on-device categorizer and file import remain free.)
- An upgrade flow links to the external checkout URL and accepts an unlock code.
20. Data portability and safety
- Export — transactions can be exported to CSV.
- Full backup/restore — a complete JSON backup of all data can be downloaded and
re-imported (
_backupPayload/exportBackup/importBackup). - Destructive reset — disconnecting/wiping the ledger is deliberately hard to trigger by accident: the first action offered is downloading a CSV backup, and only then does the real delete confirm.
- Ownership — because data lives in the user's device or their own Google Sheet, the user can always open, copy, or leave with their data directly.
21. Technology summary
- Client: vanilla JavaScript SPA, single global state object, direct DOM updates; PWA with an installable manifest and an offline service worker.
- Persistence:
localStoragefor cache/prefs; Google Sheet (via user-deployed Apps Script Web App) for cloud/family. - Crypto: Web Crypto API for hashing family PINs.
- Auth/setup: Google Identity Services + Google Sheets/Apps Script APIs for automated cloud provisioning.
- No Lucid-operated servers, no central database, no third-party analytics on user data.
22. Planned / paid roadmap (functional)
- Real AI categorization (LLM) and receipt scanning — paid tier; require a hosted model/API.
- Instant bank sync on Android — a Capacitor native wrapper feeding bank SMS/notifications
into the already-built
parseBankSmsbrain; paid tier. iOS cannot do this (platform blocks SMS access). - Hosted open-banking (Plaid/Basiq/Setu-style) — a possible future paid tier requiring a minimal backend, distinct from the free file-import baseline.
End of report.
build this
Assistant
I have implemented the complete functional specification for Lucid Version 3.4 — Personal & Family Finance Tracker PWA.
What Was Built & Functional Architecture
-
Client-Owned Architecture & Storage Backend Modes:
- Local Storage Mode: Zero-server operation using client-generated IDs (
tx_<timestamp>) and localized persistent keys (prizm_data,prizm_outbox,prizm_merchant_cat,prizm_starred,prizm_milestones_seen,prizm_pro). - Google Sheets Cloud Sync Engine: Background sync loop with write-settle guard (suppresses sync 4s after local writes), dataset signature change detection (
_lastRemoteSig), conflict resolution using timestamps (ts), and a durable persistent outbox queue (prizm_outbox). - 15-Action Apps Script REST Backend: Embedded full
SCRIPT_CODEgenerator/viewer for Google Sheets Web App endpoints supportinggetAll,addTransaction,updateTransaction,deleteTx,addAccount,updateAccount,deleteAccount,addMember,deleteMember,addRecurring,updateRecurring,deleteRecurring,setBudget,deleteBudget,updateSettings, andsetSecret.
- Local Storage Mode: Zero-server operation using client-generated IDs (
-
Authentication, Access & Member Identity:
- Hashed Security PINs: Family member profiles secured via Web Crypto SHA-256 (
crypto.subtle.digest('SHA-256')). Switching profiles prompts for member PIN verification. - Optional Shared Password:
setSecretlocks the Google Sheet Web App with a master key (authK). - Family Admin Role: Admins manage budgets, income tracking, and member lists, with full ability to transfer the admin role to another family member.
- Hashed Security PINs: Family member profiles secured via Web Crypto SHA-256 (
-
Staged Onboarding Wizard:
- Step-by-step onboarding covering Personal vs. Family context, Family Join/Create, Storage Backend selection, Profile Name & PIN, Currency & Income preferences, and initial accounts setup.
-
Categories & Option B Subcategories:
- Packed category strings (
"Category ▸ Subcategory"). baseCat()helper function strips subcategories for clean budget limits, category aggregation, and pie/progress analytics.
- Packed category strings (
-
Smart On-Device Auto-Categorization Engine:
-
- Frequency-Weighted Merchant Memory (
prizm_merchant_cat): Counts category occurrences per normalized merchant string.
- Frequency-Weighted Merchant Memory (
-
- History Seeding: Auto-populates merchant memory from ledger history on launch.
-
- Word-Overlap Fuzzy Matcher: Scores unlisted merchants based on significant word overlap against learned shops.
-
- Starter Ruleset: Built-in regex rules for supermarkets, fuel, streaming, utilities, cafes, pharmacies, gyms, and payroll.
-
-
Bank File Importer & Instant SMS Brain:
- File Importer: Parses CSV (with header detection, column mapping, date-format preference override
AUTO/DMY/MDY), OFX/QFX (STMTTRNSGML/XML parser), and QIF (D/T/P/M/LQuicken format). Uses occurrence-counted de-duplication against existing ledger entries. - Instant Bank SMS Parser (
parseBankSms): Extracts debit vs credit, cleans merchant strings, formats amounts across global currency notations, and rejects non-transactional OTP/balance messages. Includes a live test sandbox tool in the UI.
- File Importer: Parses CSV (with header detection, column mapping, date-format preference override
-
Recurring Schedules & Bills Foresight:
- Date advancement with end-of-month clamping (e.g. Jan 31 Feb 28/29, keeping the 31st target for longer months).
- Due Review alert banner with 1-tap entry posting.
- Upcoming Bills Foresight filter (7, 14, 30, 60 days).
-
Emotional Wellbeing Layer:
- Tracking Streak: Calculates consecutive days with a yesterday grace window.
- Milestones: Triggers celebratory confetti popups on reaching transaction count thresholds (1, 10, 25, 50, 100, 250), tracking streaks (3, 7, 14, 30, 60, 100 days), or savings goal completions.
- Monthly Wrap-Up: Dismissible summary card of the previous calendar month framed encouragingly.
-
Analytics & Home Hero:
- Period selectors (
7d,month,year,all). - Home Hero card showing Net Worth, selectable period spend/income totals, and toggle between running account balances or period net movements.
- Breakdown views by Base Category, Spending Insights, Per-Member distribution, and Outflow by Account.
- Period selectors (
-
Monetization & Lucid Pro:
- Offline entitlement validation using checksum codes (
LUCID-XXXX-XXXX). Includes a 1-click test code generator in Settings. - Restricts free tier family members to 2 profiles (unlimited on Pro).
- Offline entitlement validation using checksum codes (
Files built:
index.html,src/types/index.ts,src/utils/constants.ts,src/utils/helpers.ts,src/utils/categorizer.ts,src/utils/smsParser.ts,src/utils/importParsers.ts,src/utils/syncEngine.ts,src/utils/achievements.ts,src/components/Header.tsx,src/components/OnboardingModal.tsx,src/components/MemberSelectorModal.tsx,src/components/TransactionModal.tsx,src/components/MilestoneModal.tsx,src/components/Tabs/HomeTab.tsx,src/components/Tabs/TransactionsTab.tsx,src/components/Tabs/AccountsTab.tsx,src/components/Tabs/RecurringTab.tsx,src/components/Tabs/AnalyticsTab.tsx,src/components/Tabs/ImportTab.tsx,src/components/Tabs/SettingsTab.tsx,src/components/BottomNav.tsx,src/App.tsx-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.